Documentation

You are viewing the documentation for the 2.4.0 release in the 2.4.x series of releases. The latest stable release series is 3.0.x.

§HTTP Request Handlers

Play abstraction for handling requests is less sophisticated in the Play Java API, when compared to its Scala counterpart. However, it may still be enough if you only need to execute some code before the controller’s action method associated to the passed request is executed. If that’s not enough, then you should fall back to the Scala API for creating a HTTP request handler.

§Implementing a custom request handler

The HttpRequestHandler interface has two methods that needs to be implemented:

There is also a DefaultHttpRequestHandler class that can be used if you don’t want to implement both methods.

Note: If you are providing an implementation of wrapAction because you need to apply a cross cutting concern to an action before is executed, creating a filter is a more idiomatic way of achieving the same.

§Configuring the http request handler

A custom http handler can be supplied by creating a class in the root package called RequestHandler that implements HttpRequestHandler, for example:

import play.http.HttpRequestHandler;
import play.libs.F;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

import java.lang.reflect.Method;

public class RequestHandler implements HttpRequestHandler {

    @Override
    public Action createAction(Http.Request request, Method actionMethod) {
        return new Action.Simple() {
            @Override
            public F.Promise<Result> call(Http.Context ctx) throws Throwable {
                return delegate.call(ctx);
            }
        };
    }

    @Override
    public Action wrapAction(Action action) {
        return action;
    }
}

If you don’t want to place your request handler in the root package, or if you want to be able to configure different request handlers for different environments, you can do this by configuring the play.http.requestHandler configuration property in application.conf:

play.http.requestHandler = "com.example.RequestHandler"

§Performance notes

The http request handler that Play uses if none is configured is one that delegates to the legacy GlobalSettings methods. This may have a performance impact as it will mean your application has to do many lookups out of Guice to handle a single request. If you are not using a Global object, then you don’t need this, instead you can configure Play to use the default http request handler:

play.http.requestHandler = "play.http.DefaultHttpRequestHandler"

Next: Advanced routing