---
title: " struts2:使用拦截器注解"
author: "zhaosoft"
date: "2008-11-21T07:42:01Z"
tags: []
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2008-11-21T07:42:01Z"
id: 272290
url: "https://zhaosoft.iteye.com/blog/272290"
---

**使用拦截器注解**

   **Struts2在**com.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类，在基类上标注的方法将先于在派生类上标注的方法执行。**

**要使用拦截器注解，需要配置**

&lt;interceptors&gt;

           &lt;!-- 配置注解拦截器 --&gt;

           &lt;interceptor name="annotationInterceptor" class="com.opensymphony.xwork2.interceptor.annotations. AnnotationWorkflowInterceptor"/&gt;  

           &lt;interceptor-stack name="annotatedStack"&gt;

           &lt;interceptor-ref name="annotationInterceptor"/&gt;

           &lt;interceptor-ref name="defaultStack"/&gt;

           &lt;/interceptor-stack&gt;

       &lt;/interceptors&gt;

**我们看一个例子：**

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

      

    }