I have a simple scenario: automatically add a response header to every HTTP response; and I want to do this in Java.
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.
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?
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.
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"))
}
}
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: 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};
}
And also change the object AddResponseHeader
above to class AddResponseHeader
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With