开发者

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 A开发者_高级运维pplication {

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


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜