Struts2拦截器总结<转>

由于项目中在登录跳转到其他应用程序模块的时候有用到拦截器,因此查看了一下相关资料。

原文地址:http://blog.csdn.net/sendfeng/article/details/4248120

Struts2拦截器总结:

一、编写拦截器

1、  实现接口com.opensymphony.xwork2.Intercepter(或继承com.opensymphony.xwork2.AbstractInterceptor)

2、  在interceptor方法中加入如下代码:

        public String intercept(ActionInvocation arg0) throws Exception {

           System.out.println("Before");   //在Action之前调用

           String result = arg0.invoke();  //如果此拦截器之后还有拦截器,则调用下个拦截器的intercept方法

                                           //如果之后没有了拦截器,则调用Action的execute方法

           System.out.println("After");

            return result;   

        }

二、在Struts.xml中配置拦截器

1、  在struts.xml中声明拦截器和拦截器Stack,拦截器Stack可以包括多个拦截器和其他Stack。

       <interceptors>

           <!-- 拦截器 -->

           <interceptor name="MyInterceptor" class="com.test.interceptor.MyInterceptor"></interceptor>

           <!-- 拦截器Stack -->

<interceptor-stack name="validationWorkflowStack">

<interceptor-ref name="basicStack"/>

                <interceptor-ref name="validation"/>

                <interceptor-ref name="workflow"/>

</interceptor-stack>

    </interceptors>

2、  将拦截器配置到单个Action中,只拦截此Action中的execute方法。

<action name="register" class="com.test.action.RegisterAction" method="test">

           <result name="success">/success.jsp</result>

           <result name="input">/register2.jsp</result>

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

    </action>

3、  将拦截器配置到所有Action中,拦截所有Action中的execute方法。

<default-interceptor-ref name="MyInterceptor"></default-interceptor-ref>

对已经单独配置了拦截器的Action不起作用

 

三、拦截Action中指定的方法

1、 继承com.opensymphony.xwork2.interceptor.MethodFilterInterceptor。

2、 因为是针对某个Action的方法,所以只能配置在Action内部

<action name="register" class="com.test.action.RegisterAction" method="test">

           <result name="success">/success.jsp</result>

           <result name="input">/register2.jsp</result>

           <interceptor-ref name="MyInterceptor">

              <param name="includeMethod">test,execute</param><!-- 拦截textexecute方法,方法间用逗号分隔 -->

              <param name="excludeMethod">myfun</param>        <!-- 不拦截myfun方法 -->

</interceptor-ref>

    </action>

 

四、struts2拦截器的interceptor方法中,参数ActionInvocation可用来获取页面用户输入的信息。

public String intercept(ActionInvocation arg0) throws Exception {

       Map map = arg0.getInvocationContext().getSession();

       if(map.get("user") == null) {

           return Action.LOGIN;

       } else {

           return arg0.invoke();

       }

    }

原文地址:https://www.cnblogs.com/tanglc/p/4031963.html