struts2拦截器使用注解

来源:互联网 发布:win10风扇控制软件 编辑:程序博客网 时间:2024/06/05 23:08
使用拦截器注解

   Struts2在com.opensymphony.xwork2.interceptor.annotations包中定义了3个拦截器注解类型,让你可以不用编写拦截器类,直接通过注解的方式指定action执行之前和之后需要调用的方法。

   Struts2提供的3个拦截器注解类型都只能应用到方法级别。如下:

  Before

   标注一个action方法,该方法将在action的主要方法(如execute方法)调用之前调用。如果标注的方法有返回值,并且不为空,那么它的返回值将作为Action的结果代码。

   After

   标注一个action方法,该方法将在action的主要方法以及result执行之后调用,如果标注的方法有返回值,那么这个返回值将被忽略。

   BeforeResult

   标注一个action方法,该方法将在action的主要方法调用之后,在result执行之前调用,如果标注的方法有返回值,那么这个返回值将被忽略。

      


要使用拦截器注解,需要配置

<interceptors>

           <!-- 配置注解拦截器 -->

           <interceptor name="annotationInterceptor" class="com.opensymphony.xwork2.interceptor.annotations. AnnotationWorkflowInterceptor"/>  

           <interceptor-stack name="annotatedStack">

           <interceptor-ref name="annotationInterceptor"/>

           <interceptor-ref name="defaultStack"/>

           </interceptor-stack>

       </interceptors>

例子:

package action.action;

 

import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.interceptor.annotations.After;

import com.opensymphony.xwork2.interceptor.annotations.Before;

import com.opensymphony.xwork2.interceptor.annotations.BeforeResult;

 

public class AnnotationAction implements Action {

 

 

    @Before

    public void before(){

      

       System.out.println("before");

    }

   

    @After

    public void after(){

       System.out.println("after");

      

    }

   

    @BeforeResult

    public void beforeResult(){

       System.out.println("beforeResult");

      

    }

    public String execute() throws Exception {

       // TODO Auto-generated method stub

       return null;

    }

}

这个例子非常简单,只是演示了被拦截器注解标注的方法的执行顺序,在struts.xml中配置action

<action name="annotation" class="com.zhaosoft.action.AnnotationAction">

       <result>/index.jsp</result>

       <interceptor-ref name="annotatedStack"/>

       </action>

访问annotation.action控制台输出如下:

before

2008-11-21 6:42:00 com.opensymphony.xwork2.validator.ActionValidatorManagerFactory <clinit>

信息: Detected AnnotationActionValidatorManager, initializing it...

beforeResult

after
原创粉丝点击