Spring MVC拦截器(Interceptor)的配置及使用
拦截器的定义实现 HandlerInterceptor 接口的定义方式spring-config.xml拦截器配置测试
拦截器的定义
在 Spring MVC 框架中定义一个拦截器需要对拦截器进行定义和配置,定义一个拦截器可以通过两种方式:一种是通过实现 HandlerInterceptor 接口或继承 HandlerInterceptor 接口的实现类来定义;另一种是通过实现 WebRequestInterceptor 接口或继承 WebRequestInterceptor 接口的实现类来定义。
实现 HandlerInterceptor 接口的定义方式
package interCeptor
;
import org
.apache
.log4j
.Logger
;
import org
.apache
.log4j
.PropertyConfigurator
;
import org
.springframework
.web
.servlet
.HandlerInterceptor
;
import org
.springframework
.web
.servlet
.ModelAndView
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
public class testInterCepetor implements HandlerInterceptor
{
private static Logger log
= Logger
.getLogger(testInterCepetor
.class.getClass());
@Override
public boolean
preHandle(HttpServletRequest request
, HttpServletResponse response
, Object handler
) throws Exception
{
log
.debug("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request
, HttpServletResponse response
, Object handler
, ModelAndView modelAndView
) throws Exception
{
log
.debug("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request
, HttpServletResponse response
, Object handler
, Exception ex
) throws Exception
{
log
.debug("afterCompletion");
}
}
spring-config.xml拦截器配置
<mvc
:interceptors
>
<!-- 拦截所有请求
-->
<bean
class="interCeptor.testInterCepetor"/>
<mvc
:interceptor
>
<!-- 拦截所有路径
-->
<mvc
:mapping path
="/**"/>
<!-- 剔除不拦截内容
-->
<mvc
:exclude
-mapping path
="/test"/>
<bean
class="interCeptor.testInterCepetor"/>
</mvc
:interceptor
>
<mvc
:interceptor
>
<!-- 拦截gototest结尾的路径
-->
<mvc
:mapping path
="/gototest"/>
<bean
class="interCeptor.testInterCepetor"/>
</mvc
:interceptor
>
</mvc
:interceptors
>
测试