struts2_自定义拦截器以及注意事项

自定义拦截器的步骤:

  1. 实现com.opensymphony.xwork2.interceptor.Interceptor接口或者继承com.opensymphony.xwork2.interceptor.AbstractInterceptor抽象类,构建自己的拦截器类
  2. 在struts.xml中声明拦截器
  3. 在struts.xml中使用拦截器

 

MyInterceptor.java:(自定义拦截器)

 1 package com.sunflower.interceptor;
 2 
 3 import com.opensymphony.xwork2.ActionInvocation;
 4 import com.opensymphony.xwork2.interceptor.Interceptor;
 5 
 6 public class MyInterceptor implements Interceptor {
 7 
 8     public void destroy() {
 9     }
10 
11     public void init() {
12         System.out.println("MyInterceptor init!");
13     }
14 
15     public String intercept(ActionInvocation arg0) throws Exception {
16         System.out.println("befor intercept");
17 
18         String value = arg0.invoke();
19 
20         System.out.println("after intercept");
21 
22         return value;
23     }
24 
25 }

 这里关键是如何实现intercept, 根据自己的需要编写拦截功能

 

struts.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7     <constant name="struts.devMode" value="true"></constant>
 8     
 9     <package name="struts" extends="struts-default">
10     
11         <!-- 声明拦截器 -->
12         <interceptors>
13             <interceptor name="test" class="com.sunflower.interceptor.MyInterceptor"></interceptor>
14         </interceptors>
15     
16         <action name="token" class="com.sunflower.action.Action">
17         
18             <result name="success">/welcome.jsp</result>
19             <result name="invalid.token">/alert.jsp</result>
20             
21             <!-- 使用拦截器 -->
22             <interceptor-ref name="test"></interceptor-ref>
23             <interceptor-ref name="token"></interceptor-ref>
24             <interceptor-ref name="defaultStack"></interceptor-ref>
25             
26         </action>
27     </package>
28 </struts>    

 这里要注意的是,name="defaultStack"是struts默认的拦截器,如果在Action里面加入了自定义的拦截器,必须在末尾手工加入defaultStack拦截器,要不然默认拦截器功能不会发挥.

 

原文地址:https://www.cnblogs.com/hanyuan/p/2537232.html