struts2拦截器的使用
1.编写拦截器
自定义一个实现interceptor接口的类,或者继承AbstractInterceptor的类;
public class MyInterceptor implements Interceptor {
private String hello;
public void destroy() {
System.out.println("destroy============");
}
public void init() {
System.out.println("init============");
System.out.println("hello=================");
}
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("intercept1============");
String result = invocation.invoke();
return result;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
2.在struts.xml的package中注册上一步的拦截器
<!-- 拦截器配置 -->
<interceptors>
<interceptor name="myInterceptor" class="com.test.interceptor.MyInterceptor">
<param name="hello">nihao</param>
</interceptor>
<interceptor name="myInterceptor2" class="com.test.interceptor.MyInterceptor2"></interceptor>
<interceptor name="myInterceptor3" class="com.test.interceptor.MyInterceptor3"></interceptor>
<!-- 拦截器栈配置,拦截栈可以包含拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="myInterceptor"></interceptor-ref>
<interceptor-ref name="myInterceptor2"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 将自定义拦截器设置为默认拦截器-->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
3.在需要使用的action中引用上述拦截器
<action name="login" class="com.struct2.test.LoginAction">
<result name = "input">/login2.jsp</result>
<result name = "login" type ="redirect">/login.jsp</result>
<result name = "success">/result.jsp</result>
<result name = "invalid.token">/login2.jsp</result>
<!-- 防止表单重复提交的拦截器 -->
<interceptor-ref name="token"></interceptor-ref>
<!-- 指定/排除某些方法的拦截器,指定和排除同时存在时,指定的优先级高-->
<interceptor-ref name="myInterceptor3">
<param name="includeMethods">execute,test</param>
<param name="excludeMethods">execute,test</param>
</interceptor-ref>
<!-- 当提供自定义的拦截器后,默认拦截器失效,所以要手动包含进来-->
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
浙公网安备 33010602011771号