默认情况下为action定义的拦截器会拦截该action的所有方法,如果只需要拦截一部分方法,可以使拦截器继承自MethodFilterInterceptor,实现doIntercept方法,然后在配置文件中用<param name="excludeMethods">来指定不需要拦截的方法。
1.
package elia;
import java.util.Date;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class SimpleInterceptor extends MethodFilterInterceptor{
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String doIntercept(ActionInvocation invocation) throws Exception {
// LoginAction action = (LoginAction)invocation.getAction();
System.out.println(name + "Intercepter-----------"+
"Action begin: " + new Date());
long start = System.currentTimeMillis();
String result = invocation.invoke();
System.out.println(name + "Intercepter-----------"+
"Action end: " + new Date());
long end = System.currentTimeMillis();
System.out.println(name + "Intercepter-----------"+
"Action total time: " + (end - start));
return result;
}
}
2.struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<interceptors>
<interceptor name="SimpleInterceptor" class="elia.SimpleInterceptor">
<param name="name">簡単なInterceptor</param>
</interceptor>
</interceptors>
<action name="Login" class="elia.LoginAction">
<result name="input">/Login.jsp</result>
<result name="error">/error.jsp</result>
<result name="success">/Welcome.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="SimpleInterceptor">
<param name="name">renamed Interceptor</param>
// 如果excludeMethods参数和includeMethods参数都制定了同一个方法,则该方法会被拦截
<param name="excludeMethods">execute,setUsername</param>
<param name="includeMethods">execute,setUsername</param>
</interceptor-ref>
</action>
</package>
</struts>