---
title: "struts2.0 Interceptor Configuration（拦截器配置）"
author: "mmdev"
date: "2007-07-03T16:19:00Z"
tags: []
slug: "struts2-0-interceptor-configuration"
draft: false
lastmod: "2011-12-10T16:01:32Z"
id: 1301162
url: "https://mmdev.iteye.com/blog/1301162"
---

- 多个拦截器可以组成一个拦截器堆栈。每个拦截器命名为一。
- Registering Interceptors

&lt;interceptors&gt;  
&lt;interceptor name="security" class="com.company.security.SecurityInterceptor"/&gt;  
&lt;interceptor-stack name="secureStack"&gt;  
&lt;interceptor-ref name="security"/&gt;  
&lt;interceptor-ref name="defaultStack"/&gt;  
&lt;/interceptor-stack&gt;  
&lt;/interceptors&gt;

拦截器和拦截器堆栈可以混合使用。但按顺序执行。也可以设一个默认的如：

&lt;default-interceptor-ref name="secureStack"/&gt;

- 每个Action也可以定义自己的拦截器：

A local Interceptor Stack

&lt;action name="VelocityCounter" class="org.apache.struts2.example.counter.SimpleCounter"&gt;  
&lt;result name="success"&gt;...&lt;/result&gt;  
&lt;interceptor-ref name="defaultComponentStack"/&gt;  
&lt;/action&gt;

- 另外也可以把

&lt;package name="actionName" extends="struts-default"&gt;

&lt;interceptors&gt;

&lt;interceptor name="userAccessInterceptor"

class="tool.UserAccessInterceptor"&gt;

&lt;/interceptor&gt;

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

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

&lt;/interceptor-stack&gt;

&lt;/interceptors&gt;

&lt;default-interceptor-ref name="myInter"&gt;&lt;/default-interceptor-ref&gt;

放到一个单独的文件，单独的包中，用的时候先导入文件在继承包名就可以了。

- 自定义拦截器的一般写法：

//Source file: F:/java/Oil/src/com/xj/tools/UserAccessInterceptor.java

package tool;

import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserAccessInterceptor extends AbstractInterceptor {

@Override

public void destroy() {

// TODO Auto-generated method stub

super.destroy();

}

@Override

public void init() {

// TODO Auto-generated method stub

super.init();

}

@Override

public String intercept(ActionInvocation arg0) throws Exception {

// TODO Auto-generated method stub

Map session = arg0.getInvocationContext().getSession();

String username = (String) session.get("username");

if ((username == null || username == ""))

return "input";

else {

return arg0.invoke();

}

}

}