---
title: "Struts002——拦截器Interceptor的原理和自定义（续）"
author: "zenoh"
date: "2011-05-21T21:12:44Z"
tags: []
categories: ["企业架构"]
slug: "struts002-interceptor"
draft: false
lastmod: "2011-05-21T21:12:44Z"
id: 1053932
url: "https://zenoh.iteye.com/blog/1053932"
---

**自定义拦截器**

[接上个话题](/blog/1053486 "接上一个话题")所有的Struts 2的拦截器都直接或间接实现接口

 MyInterceptor.java

```
package com.zenoh.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class MyInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = null;

		// invocation.invoke()之前的代码，将会在Action之前被依次执行
		String actionName = invocation.getAction().getClass().getName();
		// 获取此次调用的Action的方法名
		String method = invocation.getProxy().getMethod();
		System.out.println("开始执行" + actionName + "的" + method + "方法");

		result = invocation.invoke(); // 调用下一个资源
		// invocation.invoke()之后的代码，将会在Action之后被逆序执行
		
		System.out.println("执行" + actionName + "的" + method + "方法完毕");

		return result;
	}
}
```

 

src/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>
	<include file="struts-default.xml"></include>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="InterceptorDemo" namespace="/" extends="struts-default">

		<interceptors>
		    <!-- 自定义拦截器 -->   
			<interceptor name="myInterceptor" class="com.zenoh.interceptor.MyInterceptor"></interceptor>
			<!-- 自定义的拦截器栈 -->
			<interceptor-stack name="myStack">
			<interceptor-ref name="defaultStack"/>
				<interceptor-ref name="myInterceptor"/>
			</interceptor-stack>
		</interceptors>
        <default-action-ref name="index" />

        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>

        <action name ="Timer" class ="com.zenoh.action.TimerInterceptorAction" >
        	<!-- 这里配置拦截器 -->
        	<interceptor-ref name="myInterceptor"/>    
            <interceptor-ref name ="timer"/>    
            <result>/Timer.jsp</result>    
        </action >
    </package>
</struts>
```

 Struts2拦截器的原理: 客户端请求某一个Action时，都会经过配置好的拦截器。