struts2自定义拦截器

来源:互联网 发布:看门狗画面优化补丁 编辑:程序博客网 时间:2024/06/07 00:30

拦截器原理:
当请求struts2的action时,struts2会查找配置文件,并根据其配置的拦截器对象,添加到一个列表,然后一个一个地调用列表中的拦截器。

自定义拦截器一般有两类:类拦截器和方法拦截器


自定义类拦截器

自定义拦截器:继承抽象类 AbstractInterceptor ,并重写 intercept方法

public class MyClassInterceptor extends AbstractInterceptor{    @Override    public String intercept(ActionInvocation invocation) throws Exception {        String result = invocation.invoke();        //调用目标方法,并返回调用后返回的结果视图名        System.out.println("类拦截器"+result);        return result;    }}

自定义方法拦截器

自定义方法拦截器:继承抽象方法类MethodFilterInterceptor类,重写doIntercept方法

public class MyInterceptor extends MethodFilterInterceptor{    @Override    protected String doIntercept(ActionInvocation invocation) throws Exception {        String result = invocation.invoke();        //调用目标方法,并返回调用后返回的结果视图名        System.out.println("方法拦截器:"+result);        return result;    }}

struts.xml中的配置:

<struts>    <package name="Login" namespace="/" extends="struts-default">        <!-- 1、 -->        <interceptors>            <interceptor name="methodInterceptor" class="org.danni.web.interceptor.MyInterceptor"</interceptor>            <interceptor name="classInterceptor" class="org.danni.web.interceptor.MyClassInterceptor"></interceptor>        </interceptors>        <action name="mylogin_*" class="org.danni.web.action.LoginAction"            method="{1}">            <result name="loginSuccess">/index.jsp</result>            <result name="login">login.jsp</result>            <result name="input">/login.jsp</result>            <!-- 用来配置通过validate验证之后应该跳转的页面 -->            <!-- 2、 -->            <!-- 自定义类拦截器 -->            <interceptor-ref name="classInterceptor"></interceptor-ref>            <!-- 自定义方法拦截器 -->            <interceptor-ref name="">                <param name="includeMethods">login</param>      <!-- 设置哪些方法需要被自定义方法拦截器进行拦截操作 -->            </interceptor-ref>            <!-- 3、 -->            <!-- 系統默认的拦截器 -->            <interceptor-ref name="defaultStack"></interceptor-ref>            <allowed-methods>login</allowed-methods>            <!-- 方法只有设置了才可以被调用方法 -->        </action>    </package></struts>

拦截器,拦截器栈和默认的拦截器之间的关系

1、拦截器和拦截器栈是一个级别的,一个拦截器栈中可以包括许多拦截器, 一个拦截器栈中还可以包括许多拦截器栈
2、struts2中有一个系统默认的拦截器栈是 defaultStack,如果你手动引用自己的拦截器,系统默认的拦截器栈将不起作用。此时你就必需手动引入系统的拦截器栈

<interceptor-ref name="defaultStack"></interceptor-ref>

3、如果拦截器栈中有多个拦截器,在执行action之前的顺序跟配置拦截器的顺序(比如之前:1- - >2 - - >3)一致,而在action之后执行的顺序是相反的(比如之后:3- - > 2- - >1)

原创粉丝点击