Struts2拦截器
自定义一个拦截器,实现当用户没有登录时不能下载:

1 import javax.servlet.http.HttpSession;
2
3 import org.aopalliance.intercept.Invocation;
4 import org.apache.struts2.ServletActionContext;
5
6 import com.dkx.action.UserAction;
7 import com.opensymphony.xwork2.ActionInvocation;
8 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
9
10 public class Userinteceptor extends AbstractInterceptor{
11
12 @Override
13 public String intercept(ActionInvocation a1) throws Exception {
14 if (a1.getAction().getClass()==UserAction.class) {
15 return a1.invoke();
16 }
17 HttpSession session=ServletActionContext.getRequest().getSession();
18 Object obj=session.getAttribute("name");
19 if (obj!=null) {
20 return a1.invoke();//继续执行
21 }else {
22 return "login";
23 }
24
25 }
26
27 }
2
3 import org.aopalliance.intercept.Invocation;
4 import org.apache.struts2.ServletActionContext;
5
6 import com.dkx.action.UserAction;
7 import com.opensymphony.xwork2.ActionInvocation;
8 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
9
10 public class Userinteceptor extends AbstractInterceptor{
11
12 @Override
13 public String intercept(ActionInvocation a1) throws Exception {
14 if (a1.getAction().getClass()==UserAction.class) {
15 return a1.invoke();
16 }
17 HttpSession session=ServletActionContext.getRequest().getSession();
18 Object obj=session.getAttribute("name");
19 if (obj!=null) {
20 return a1.invoke();//继续执行
21 }else {
22 return "login";
23 }
24
25 }
26
27 }
自定义的拦截器需要继承AbstractInterceptor类并实现他的方法。
在Struts.xml文件中配置拦截器:
1 <interceptors>
2 <interceptor name="myinteceptor" class="com.dkx.interceptor.Userinteceptor"></interceptor>
3 <interceptor-stack name="myintec">
4 <interceptor-ref name="myinteceptor"></interceptor-ref>
5 <interceptor-ref name="defaultStack"></interceptor-ref>
6 </interceptor-stack>
7 </interceptors>
8 <default-interceptor-ref name="myintec"></default-interceptor-ref>
2 <interceptor name="myinteceptor" class="com.dkx.interceptor.Userinteceptor"></interceptor>
3 <interceptor-stack name="myintec">
4 <interceptor-ref name="myinteceptor"></interceptor-ref>
5 <interceptor-ref name="defaultStack"></interceptor-ref>
6 </interceptor-stack>
7 </interceptors>
8 <default-interceptor-ref name="myintec"></default-interceptor-ref>
使用拦截器时,需要定义一个默认执行的拦截器。而且,当我们使用了自定义的拦截器,默认的拦截器(defaultStack)会失效,所以定义时也要将他包含在内。
inteceptor-rel表示引用。


浙公网安备 33010602011771号