---
title: "Struts 2.0 拦截器"
author: "mgoann"
date: "2009-05-06T15:57:53Z"
tags: ["Apache", "HTML", "JSP", "Struts", "XML"]
categories: ["企业架构"]
slug: "struts-2-0"
draft: false
lastmod: "2009-05-06T16:00:04Z"
id: 380201
url: "https://mgoann.iteye.com/blog/380201"
---

**Struts 2.0 拦截器**

**简介**

 

在Struts 2.0 中的拦截器，要实现com.opensymphony.xwork2.interceptor.Interceptor接口，在struts.xml中配置。可以用拦截器来完成调用Action业务逻辑之前的预处理或是之后的善后处理。还可以通过配置多个拦截器来满足action需求。

 

Interceptor  stack是由多个拦截器组成的拦截器组，在拦截器组中可以对每一个拦截器映射。所有进行配置拦截器时，不必对每一个拦截器进行配置，而只需对interceptor stack进行配置即可。在struts 2中默认配置了一个全局interceptor stack，包括Exception Interceptor、Validation Interceptor等。

 

**实例**

 

在这个实例当中，我将配置一个时间拦截器，用来统计每个action的请求时间。

 

```
package interceptor;   
  
import com.opensymphony.xwork2.ActionInvocation;   
import com.opensymphony.xwork2.interceptor.Interceptor;   
  
public class ActionTimer implements Interceptor{   
    public String intercept(ActionInvocation next) throws Exception {   
        long t1 = System.currentTimeMillis();   
        String s= next.invoke();   
        long t2 = System.currentTimeMillis();   
        System.out.println("Action "+next.getAction().getClass().getName()+" took "+(t2-t1)+" millisecs");   
        return s;   
    }   
       
    public void init() {   
    }   
    public void destroy() {   
    }   
}
```

 

 

 

struts.xml：

 

```
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC   
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
    "http://struts.apache.org/dtds/struts-2.0.dtd">  
<struts>  
    <package name="interceptor" extends="struts-default">  
        <interceptors>  
            <interceptor name="actiontimer"  
                class="interceptor.ActionTimer" />  
  
            <interceptor-stack name="demostack">  
                <interceptor-ref name="defaultStack" />  
                <interceptor-ref name="actiontimer" />  
            </interceptor-stack>  
        </interceptors>  
        <default-interceptor-ref name="demostack" />  
        <action name="InterceptorDemo"  
            class="interceptor.action.InterceptorDemo">  
            <result>/interceptor/interceptordemo.jsp</result>  
        </action>  
    </package>  
  
</struts>  
```

 

 

 

interceptordemo.jsp：

```
<html>  
<head>  
  
</head>  
<body>  
</body>  
</html>  
```