itsadok
itsadok

Reputation: 29342

Is there a way to share data between interceptors and actions in the play framework?

In a Play! controller, I can create an interceptor method that will process every request before it arrives to the appropriate action.

public class Admin extends Application {

    @Before
    static void checkAuthentification() {
        if(session.get("user") == null) login();
        // otherwise,
        User loggedOnUser = User.find("byUsername", session.get("user"));
    }

    public static void index() {
        // any way to access loggedOnUser ?
        List<User> users = User.findAll();
        render(users);
    }
    …
}

Is there a way to set a value in the interceptor and access it in the action? Sort of like request.setAttribute() in servlets?

Upvotes: 3

Views: 737

Answers (2)

Joel Grenon
Joel Grenon

Reputation: 3273

Interceptors and actions share the same request context (request, response, session, etc). As stated above, you may elect to use renderArgs, but keep in mind that these values will be available in your views, which may not be what you want. If you want to keep the state between your interceptor and actions, just use the request.args hash instead.

Upvotes: 2

Pere Villega
Pere Villega

Reputation: 16439

You can use renderArgs parameter from Controller (see here) or you can store the value in the Cache (we can assume that as the value was added miliseconds ago, your value will be available while in the same request).

Upvotes: 4

Related Questions