SpringMVC 拦截请求,判断会话是否超时

#Spring MVC 拦截器定义
Spring MVC中的拦截器,也就是Interceptor,拦截请求是经过HandlerInterceptor来实现的。在SpringMVC中定义一个拦截器很简单,主要有两种方式,第一种方式要定义一个类,该类实现HandlerInterceptor接口,或者继承实现了该接口的类,如spring已经实现的抽象类HandlerInterceptorAdapter 。第二种是实现spring的WebRequestInterceptor接口。java

实现HandlerInterceptor接口web

先来看下代码spring

1.	import javax.servlet.http.HttpServletRequest;  
2.	import javax.servlet.http.HttpServletResponse;  
3.	  
4.	import org.springframework.web.servlet.HandlerInterceptor;  
5.	import org.springframework.web.servlet.ModelAndView;  
6.	  
7.	public class LoginSessionInterceptor implements HandlerInterceptor {  
8.	  
9.	  
10.	 
11.	    @Override  
12.	    public boolean preHandle(HttpServletRequest request,  
13.	            HttpServletResponse response, Object handler) throws Exception {  
14.	        // TODO Auto-generated method stub  
15.	        return false;  
16.	    }  
17.	      
18.	   
19.	    @Override  
20.	    public void postHandle(HttpServletRequest request,  
21.	            HttpServletResponse response, Object handler,  
22.	            ModelAndView modelAndView) throws Exception {  
23.	        // TODO Auto-generated method stub  
24.	          
25.	    }  
26.	  
27.	 
28.	    @Override  
29.	    public void afterCompletion(HttpServletRequest request,  
30.	            HttpServletResponse response, Object handler, Exception ex)  
31.	    throws Exception {  
32.	        // TODO Auto-generated method stub  
33.	          
34.	    }  
35.	      
36.	}

上述代码中能够看到主要有三个方法:preHandle、postHandle、afterCompletionspring-mvc

(1 )preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) 方法,顾名思义,该方法将在请求处理以前进行调用。SpringMVC 中的Interceptor 是链式的调用的,在一个应用中或者说是在一个请求中能够同时存在多个Interceptor 。每一个Interceptor 的调用会依据它的声明顺序依次执行,并且最早执行的都是Interceptor 中的preHandle 方法,因此能够在这个方法中进行一些前置初始化操做或者是对当前请求的一个预处理,也能够在这个方法中进行一些判断来决定请求是否要继续进行下去。该方法的返回值是布尔值Boolean类型的,当它返回为false 时,表示请求结束,后续的Interceptor 和Controller 都不会再执行;当返回值为true 时就会继续调用下一个Interceptor 的preHandle 方法,若是已是最后一个Interceptor 的时候就会是调用当前请求的Controller 方法。mvc

(2 )postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) 方法,由preHandle 方法的解释咱们知道这个方法包括后面要说到的afterCompletion 方法都只能是在当前所属的Interceptor 的preHandle 方法的返回值为true 时才能被调用。postHandle 方法,顾名思义就是在当前请求进行处理以后,也就是Controller 方法调用以后执行,可是它会在DispatcherServlet 进行视图返回渲染以前被调用,因此咱们能够在这个方法中对Controller 处理以后的ModelAndView 对象进行操做。postHandle 方法被调用的方向跟preHandle 是相反的,也就是说先声明的Interceptor 的postHandle 方法反而会后执行,这和Struts2 里面的Interceptor 的执行过程有点类型。Struts2 里面的Interceptor 的执行过程也是链式的,只是在Struts2 里面须要手动调用ActionInvocation 的invoke 方法来触发对下一个Interceptor 或者是Action 的调用,而后每个Interceptor 中在invoke 方法调用以前的内容都是按照声明顺序执行的,而invoke 方法以后的内容就是反向的。app

(3 )afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) 方法,该方法也是须要当前对应的Interceptor 的preHandle 方法的返回值为true 时才会执行。顾名思义,该方法将在整个请求结束以后,也就是在DispatcherServlet 渲染了对应的视图以后执行。这个方法的主要做用是用于进行资源清理工做的jsp

了解了拦截器的原理以后,就能够开始把他加入到咱们的应用程序中了。下面用SpringMVC配置拦截器实现,会话过期跳转的处理ide

#SpringMVC 拦截器配置post

1.在spring-mvc的配置文件中加上支持的schemaurl

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        ">

2.上面加入以后,就可使用mvc:interceptors来声明拦截器了。

<mvc:interceptors>
		<mvc:interceptor>
			<!-- 匹配的是url路径, 若是不配置或/**,将拦截全部的Controller -->
			<mvc:mapping path="/**" />
			<mvc:exclude-mapping path="/resources/**"/>
			<mvc:exclude-mapping path="/login"/>
			<bean class="com.demo.filter.LoginSessionInterceptor"></bean>
		</mvc:interceptor>
</mvc:interceptors>

其中<mvc:mapping path="">能够配置要拦截的请求路径 /xxx/**表示/xx/开头的请求都会被拦截 既然有包含的拦截路径,那么也就有不包含拦截路径,这就是使用mvc:exclude-mapping

上面的配置就是把除了"/login"请求以及资源过滤,不拦截外,其余请求都要进行拦截处理,具体拦截器代码以下

#拦截器拦截会话请求,超时会话信息消失后返回登陆页

public class LoginSessionInterceptor extends HandlerInterceptorAdapter {

	private final Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.info("==============postHandle================");
		String userId = (String) request.getSession().getAttribute(LoginParamContant.LOGIN_ACCOUNT_ID);
		if (modelAndView != null) { // 加入当前时间
			modelAndView.addObject("userId", userId);
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		log.info("==============preHandle================");
		String testId = request.getParameter("testId");
		String userId = (String) request.getSession().getAttribute(LoginParamContant.LOGIN_ACCOUNT_ID);
		if (userId == null) {
			if (StringUtils.isNotBlank(testId) && testId.equals(SysParamNameConstant.PROJECT_TEST_ID)) {
				return true;
			} else {
				log.info("Interceptor:跳转到login页面!");
				request.getRequestDispatcher("/WEB-INF/jsp/login/index.jsp").forward(request, response);
				return false;
			}
		}
		return true;
	}

}
相关文章
相关标签/搜索