struts2:使用拦截器注解

93 篇文章 0 订阅
13 篇文章 0 订阅

使用拦截器注解

   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");

      

    }

    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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值