---
title: "struts2源码阅读-三个核心之拦截器"
author: "悲剧了"
date: "2011-10-11T15:06:30Z"
tags: []
categories: ["开源软件"]
slug: "struts2"
draft: false
lastmod: "2011-10-12T10:33:03Z"
id: 1189653
url: "https://blognojava.iteye.com/blog/1189653"
---

*晚上回家看struts2 in acion ，这本书也买了快一年了，以前还真没仔细看过，以前看过的strut2的书也只是教怎么快速入门罢了，现在顿觉很有感触。
    用了struts2快一年，从xml配置方式到annotation，比如现在项目遇到的不同的使用struts2的方式，基于modelDriver方式，零配置，注解权限控制，一直只是用，遇到问题跟踪下代码，没怎么去学习里面的东西。*

**拦截器
  没有拦截器就没有struts2,学好struts2的必须把这个先拿下。
首先拦截器是类似filter，也是责任链方式，但是filter问题在于只要配置，每个链接过来都要处理，拦截器可以给特定的action包下面的拦截器配置上，需要的链接请求或者逻辑才进行处理，省了不少性能**

***看框架使用：***
首先是StrutsPrepareAndExecuteFilter配置在xml中的入口，顺着这个filter再debug下，发现好多东东，远远超过看什么书，然后去积累的强。
  简单的比如：有别的filter要先处理就配置在前面，然后再chain这个，不然会出问题

> 
> This filter is better to use when you don't have another filter that needs access to action context information, such as Sitemesh.
> 

  复杂的比如：里面的代理action处理类，原来执行是代理类来做的

> 
> 
>     /**
>      * Creates an {@link ActionProxy} for the given namespace and action name by looking up the configuration.The ActionProxy
>      * should be fully initialized when it is returned, including having an {@link ActionInvocation} instance associated.
>      *
>      * @param namespace    the namespace of the action, can be <tt>null</tt>
>      * @param actionName   the name of the action
>      * @param methodName   the name of the method to execute
>      * @param extraContext a Map of extra parameters to be provided to the ActionProxy, can be <tt>null</tt>
>      * @param executeResult flag which tells whether the result should be executed after the action
>      * @param cleanupContext flag which tells whether the original context should be preserved during execution of the proxy.
>      * @return ActionProxy  the created action proxy
>      * @since 2.1.1
>      */
>     public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext);
> 
> 


那么参数处理等配置默认拦截器又是怎么处理的？
  struts2在调用拦截器方法的时候，set进去了ActionInvocation，在处理完动作的时候会调用ActionInvocation的invock方法，这个就象filter里面的chain一样，做了个传递，所以可以在调用chain的前面进行预处理，chain后买进行善后
利用这个特点，自己给项目上加一个ExceptionInterceptor

```java

public class ExceptionInterceptor implements Interceptor {
	protected final Log log = LogFactory.getLog(ExceptionInterceptor.class);

	

	@Override
	public void init() {
		log.info("Exception Interceptor start init");
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result;
		try{
			result=invocation.invoke();
		}catch (Exception e) {
                        result="exceptionPage";
			log.error("exception page ", e);
		}
		
		return result;
	}
	
	@Override
	public void destroy() {
		log.info("Exception Interceptor destroy");
	}


}


```

    默认开启的拦截器有很多特色，也导致struts2有了根据项目需要可以有很多使用方式。