1, SpringMVC 中的r拦截器:主要作用是拦截用户的请求并进行相应的处理。例如:通过它来进行权限验证,或者是来判断用户是否登陆。
2,定义拦截器有两种方式:(1)实现HandlerInterceptor 接口 (2)实现WebRequestInterceptor接口。
3,java代码
public class CheckSessionInterceptor implements HandlerInterceptor {
/**
* preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,
* SpringMVC中的Interceptor拦截器是链式的,可以同时存在。
* 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,
* 而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。
* SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返回值为false,
* 当preHandle的返回值为false的时候整个请求就结束了。
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object obj) throws Exception {
if(request.getRequestURI().indexOf("/login.do")>0 || request.getRequestURI().indexOf("/doLogin.do") > 0
|| request.getRequestURI().indexOf("/activeInfo.do") > 0|| request.getRequestURI().indexOf("/active.do") > 0
|| request.getRequestURI().indexOf("/resetPasswordInfo.do") > 0|| request.getRequestURI().indexOf("/resetPassword.do") > 0
|| request.getRequestURI().indexOf("/auth/") > 0){
return true;
}
if(request.getSession().getAttribute(BaseController.userIsLoginSessionName)!=null){
return true;
}else{
response.sendRedirect("/pecan_web");
return false;
}
}
/**
* postHandle方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。
* postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之后,也就是在Controller的方法调用之后执行,
* 但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操作。
* 这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用。
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object obj, ModelAndView mav) throws Exception {
}
/**
* afterCompletion方法 只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。
* 该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,
* 这个方法的主要作用是用于清理资源的。
*/
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception err)
throws Exception {
}
}
4,配置文件
schema头文件
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
<mvc:interceptors>
<!-- <bean class="com.host.app.web.interceptor.AllInterceptor"/> 直接放在interceptors下的 将会拦截所有请求-->
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.yjcloud.interceptor.CheckSessionInterceptor"/><!--对特定请求拦截 -->
</mvc:interceptor>
</mvc:interceptors>