Struts2 :Can Interceptors can handle Unauthorized Access?
I am trying to understand Struts2 Interceptors. So please excuse if my questions are dumb.
I guess that interceptors are specific to an action class (that means before calling a specific action class, they get invoked).
For example:
<action name="test" class="com.jranch.Test">
<interceptor-ref name="GuiStack”/>
<result name="success">/secure.jsp</result>
</action>
My question is: Assume a scenario where pictures in a website must be protected from unauthorized access (Means if the user directly enters an URL in the browser, they should not be allowed to see the pictures until they are logged in).
My view is that if its related to Servlet Filters, I can write a simple filt开发者_开发问答er by putting url-pattern tag to /* to check all requests. Can Struts2 interceptors handle this as I guess they are specific to action class?
Please correct me if i am wrong.
Well As Steven told Interceptors are not specific to any Action, they in fact are the core of Struts2 framework Interceptors are a set of reusable components.In all cases they are Applied to a request processing cycle which includes from Exception Handling to Role handling. Its very trivial use case when one will write a Interceptor for a particular Action.
Use case you are talking about can be handled by Interceptor where for each request for a particular resources can be first intercepted by the Interceptor and based on out custom criteria whom to allow access we either forward the request down the calling stack or can reject the request.
public String intercept (ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext ();
Map<String, Object> session = ActionContext.getContext().getSession();
Object user = session.getAttribute (USER_HANDLE);
if (user == null) {
//Any processing
return "login"; //User is not logged in so ask him/her to login
} else {
return invocation.invoke (); //user is trusted one let her go ahead
}
}
Interceptors aren't necessarily specific to an action -- in fact, in most cases, they're applied to many actions or globally to all actions (very similar a servlet filter).
This answer talks about how to use an interceptor for authentication in a Struts2 application.
精彩评论