开发者

How do I access the HttpSession inside a Struts 2 interceptor? Should I?

开发者 https://www.devze.com 2023-04-05 00:05 出处:网络
I am seeing the concept of Interceptors in Struts2. I have seen the below example from a tutorial on Struts2.

I am seeing the concept of Interceptors in Struts2. I have seen the below example from a tutorial on Struts2.

In this example the author uses an interceptor to check the credentials by accessing the HttpSession and checks for USER_KEY in it.

Is it a bad idea to access to 开发者_JS百科HttpSession in the interceptor itself? I guess interceptors are simple servlet filters in Java EE programming.

I feel the best place to get access to HttpSession is inside the action class in Struts2.

Please correct me in case I am wrong.

public class AuthorizationInterceptor extends AbstractInterceptor {

    private static final String USER_KEY = "user";

    public String intercept(ActionInvocation invocation) throws Exception {
        Map session = invocation.getInvocationContext().getSession();
        if (session.get(USER_KEY) == null) {
            addActionError(invocation, "You must be authenticated to access this page");
            return Action.ERROR;
        }

        return invocation.invoke();
    }

    private void addActionError(ActionInvocation invocation, String message) {
        Object action = invocation.getAction();
        if (action instanceof ValidationAware) {
            ((ValidationAware) action).addActionError(message);
        }
    }
}


Accessing the HttpSession from interceptors is perfectly fine; accessing it in an action is actively discouraged.

Controlling access through an interceptor is a perfect use-case. Access control generally affects large portions of applications. Isolating it in an interceptor keeps the mainline code cleaner. Interceptors are the most appropriate place to interface with servlet spec artifacts like the session.

Actions may access session attributes through the SessionAware interface. It exposes only a Map<String, Object> of the attributes. This keeps the action decoupled from the servlet specification, making testing easier.


If you want access real HttpSession inside interceptor, you may acquire it by:

HttpSession session = ServletActionContext.getRequest().getSession();

P.S. I know, my answer is too late for your question, but it may help to others, hope =)

0

精彩评论

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

关注公众号