为 Play 编写自定义过滤器!2.2 Java [英] Writing custom filters for Play! 2.2 in Java
问题描述
我有一个简单的场景:自动为每个 HTTP 响应添加一个响应头;我想用 Java 来做这件事.
I have a simple scenario: automatically add a response header to every HTTP response; and I want to do this in Java.
看src/play-filters-helpers/src/main/java/play/filters/*
,有Actions 可以用作注释.我想避免将 @AddMyHeader
添加到每个处理程序.
Looking at src/play-filters-helpers/src/main/java/play/filters/*
, there are examples of Actions which can be applied as annotations. I'd like to avoid adding @AddMyHeader
to every handler.
查看 src/play-filters-helpers/src/中的 Scala 过滤器main/scala/play/filters/*
和 GzipFilter
特别是,我看到了一个清晰的机制,但我对 Scala 不够熟悉,无法推断到 Java.
Looking at the Scala Filters in src/play-filters-helpers/src/main/scala/play/filters/*
and GzipFilter
specifically, I see a clear mechanism, but I'm not familiar enough with Scala to extrapolate to Java.
那么:我从这里去哪里?
So: where do I go from here?
推荐答案
遗憾的是,目前还没有一种从 Java 创建和使用过滤器的好方法.但是您可以使用 Scala 轻松完成所需的工作.
Unfortunately there isn't a good way to create and use Filters from Java yet. But you can do what you need pretty easily with Scala.
创建一个新文件 app/filters/AddResponseHeader.scala
包含:
Create a new file app/filters/AddResponseHeader.scala
containing:
package filters
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object AddResponseHeader extends Filter {
def apply(f: (RequestHeader) => Future[SimpleResult])(rh: RequestHeader): Future[SimpleResult] = {
val result = f(rh)
result.map(_.withHeaders("FOO" -> "bar"))
}
}
并创建一个新文件 app/Global.scala
包含:
And create a new file app/Global.scala
containing:
import filters.AddResponseHeader
import play.api.mvc.WithFilters
object Global extends WithFilters(AddResponseHeader)
这应该对每个响应应用一个新的响应头.
That should apply a new response header to every response.
UPDATE:有一种方法可以在 Global.java
文件中使用它:
UPDATE: There is a way to use this in a Global.java
file:
@Override
public <T extends EssentialFilter> Class<T>[] filters() {
return new Class[] {AddResponseHeader.class};
}
并将上面的 object AddResponseHeader
更改为 class AddResponseHeader
.
And also change the object AddResponseHeader
above to class AddResponseHeader
.
这篇关于为 Play 编写自定义过滤器!2.2 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!