Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing custom filters for Play! 2.2 in Java

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?

like image 423
Nino Walker Avatar asked Oct 10 '13 23:10

Nino Walker


1 Answers

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.

like image 112
James Ward Avatar answered Sep 19 '22 11:09

James Ward