struts2_方法拦截器

使用方法拦截器的步骤:

  1. 继承MethodFilterInterceptor抽象类,实现自己的方法拦截器类(重写doIntercept()方法)
  2. 在struts.xml中声明拦截器
  3. 在struts.xml中使用拦截器

MethodInterceptor.java:(自定义方法拦截器)

 1 package com.sunflower.interceptor;
 2 
 3 import com.opensymphony.xwork2.ActionInvocation;
 4 import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
 5 
 6 public class MethodInterceptor extends MethodFilterInterceptor {
 7 
 8     protected String doIntercept(ActionInvocation arg0) throws Exception {
 9         System.out.println("method interceptor before invoke--------");
10 
11         String result = arg0.invoke();
12 
13         System.out.println("method interceptor after invoke---------");
14 
15         return result;
16     }
17 
18 }

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"
14                 class="com.sunflower.interceptor.MyInterceptor">
15             </interceptor>
16             <interceptor name="domethod"
17                 class="com.sunflower.interceptor.MethodInterceptor">
18             </interceptor>
19         </interceptors>
20 
21         <action name="token" class="com.sunflower.action.Action">
22 
23             <result name="success">/welcome.jsp</result>
24             <result name="invalid.token">/alert.jsp</result>
25 
26             <!-- 使用拦截器 -->
27             <interceptor-ref name="test"></interceptor-ref>
28             <interceptor-ref name="token"></interceptor-ref>
29             <interceptor-ref name="defaultStack"></interceptor-ref>
30 
31         </action>
32 
33         <action name="myaction" class="com.sunflower.action.MyAction" method="myExecute">
34             <result name="success">/welcome.jsp</result>
35             
36             <interceptor-ref name="domethod">
37                 <param name="excludeMethods">myExecute</param>
38             </interceptor-ref>
39         </action>
40     </package>
41 </struts>    

关键点:

注意:

默认情况下(不指明excludeMethods和不指明includeMethods)会默认的将方法作为includeMethods参数.
使用自定义拦截器后面一定要加上默认拦截器栈(defaultStack),否则程序部分功能会失效

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