读书人

struts2:应用拦截器注解

发布时间: 2012-11-09 10:18:48 作者: rapoo

struts2:使用拦截器注解

使用拦截器注解

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

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

? ?Before

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

?? After

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

?? BeforeResult

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

?? ??????????????Before After 和BeforeResult注解的同名参数

参数

类型

是否必要

默认值

描述

priority

int

10

指定方法执行的优先级别

同一个注解可以用来标注多个方法,方法执行的先后顺序可以通过priority参数来指定,优先级越高,方法越先执行。在相同的优先级的情况下,方法执行的先后顺序无法保证。不过有继承关系的action类,在基类上标注的方法将先于在派生类上标注的方法执行。

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

<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 com.zhaosoft.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");

??????

??? }

1 楼 hanjiangit 2009-05-26 请问 怎么在action使用注解来引入拦截器呢 你上面使用的配置文件 2 楼 taohongxiu 2009-07-20 hanjiangit 写道请问 怎么在action使用注解来引入拦截器呢 你上面使用的配置文件
在类的前面加入
@InterceptorRefs( {@InterceptorRef("annotationInterceptor")})

读书人网 >软件架构设计

热点推荐