Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

playframework - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...