项目中使用拦截器主要分两步。1在配置文件中配置拦截器
2写一个拦截类,实现HandlerInteceptor借口。然后在它的方法里进行拦截实现。
首先来看看在spring上下文中的配置
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<bean class="com.mvc.Interceptor.TestInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/hello/mvc"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<bean class="com.mvc.Interceptor.InterceptorTest2"/>
</mvc:interceptor>
</mvc:interceptors>
2下面就是来看看我的实现类
package com.mvc.Interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class TestInterceptor implements HandlerInterceptor {
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("afterCompletion方法。是请求执行完后执行");
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
arg0.setCharacterEncoding("utf-8");//解决中文乱码输出问题。
return false;
}
}
下面来找张图片讲解下多个拦截器的拦截规则