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 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);
}
}
}