---
title: "SpringMVC中的mvc:interceptors标签配置拦截器"
author: "平淡-幕"
date: "2015-03-24T14:10:05Z"
tags: ["Interceptors"]
categories: ["编程语言"]
slug: "springmvc-mvc-interceptors"
draft: false
lastmod: "2015-03-24T14:10:58Z"
id: 2195041
url: "https://guifan.iteye.com/blog/2195041"
---

# mvc:interceptors

## 这个标签用于注册一个自定义拦截器或者是WebRequestInterceptors.

可以通过定义URL来进行路径请求拦截，可以做到较为细粒度的拦截控制。

例如在配置文件加入

```
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- 以下配置将拦截所有的URL请求 -->

<mvc:interceptors>

<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />

</mvc:interceptors>

<!-- 以下配置将拦截特有的URL请求 -->

<mvc:interceptors>

<mvc:interceptor>

<mvc:mapping path="/secure/*"/>

<bean class="org.example.SecurityInterceptor" />

</mvc:interceptor>

<mvc:interceptor>

<mvc:mapping path="/admin/*.do"/>

<bean class="org.example.admin.ControlInterceptor" />

</mvc:interceptor>

</mvc:interceptors>

</beans>
```

 

拦截器

Spring为我们提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个适配器，继承此类，可以非常方便的实现自己的拦截器。他有三个方法：

```
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)    
        throws Exception {    
        return true;    
    }    
    public void postHandle(    
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)    
            throws Exception {    
    }    
    public void afterCompletion(    
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)    
            throws Exception {    
    }  
```

 分别实现预处理、后处理（调用了Service并返回ModelAndView，但未进行页面渲染）、返回处理（已经渲染了页面）  
在preHandle中，可以进行编码、安全控制等处理；  
在postHandle中，有机会修改ModelAndView；  
在afterCompletion中，可以根据ex是否为null判断是否发生了异常，进行日志记录。

如果基于xml配置使用Spring MVC，  
可以利用SimpleUrlHandlerMapping、BeanNameUrlHandlerMapping进行Url映射（相当于struts的path映射）和拦截请求（注入interceptors），  
如果基于注解使用Spring MVC，可以使用DefaultAnnotationHandlerMapping注入interceptors。  
注意无论基于xml还是基于注解，HandlerMapping bean都是需要在xml中配置的。