SpringMVC读取Cookie判断用户是否登录,对每一个action都要进行判断。之前使用jstl标签在页面上判断session如果没有登录就使用如下代码跳转到登录页面。
1
2
3
4
5
6
7
|
< c:if test = "${sessionScope.login == null || sessionScope.login == false}" > <!-- 未登录 --> < c:redirect url = "/login" /> </ c:if > < c:if test = "${sessionScope.login}" > <!-- 已登录 --> </ c:if > |
但是测试发现如果session过期,页面渲染就会无故中断并且不会跳转到登录页面。故尝试使用拦截器来进行登录判断。
拦截器配置文件如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!-- <mvc:mapping path="/**" /> 如果只写一个*,则不能拦截类似/*/*的请求。静态资源的请求需要判断不进行拦截 --> < mvc:interceptors > < mvc:interceptor > < mvc:mapping path = "/**" /> < bean class = "com.ts.settle.tools.interceptor.LoginInterceptor" > < property name = "excludedUrls" > < list > < value >/login</ value > < value >/static/</ value > </ list > </ property > </ bean > </ mvc:interceptor > </ mvc:interceptors > |
拦截器实现类如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public class LoginInterceptor implements HandlerInterceptor { private AvatarLogger logger = AvatarLoggerFactory.getLogger( this .getClass()); private List<String> excludedUrls; /** * 在DispatcherServlet完全处理完请求后被调用 * 当拦截器抛出异常时,依然会从当前拦截器往回执行所的拦截器的afterCompletion() */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { } //在业务处理器处理请求执行完成后,生成视图之前执行的动作 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 在业务处理器处理请求之前被调用 * 如果返回false 则退出本拦截器,本拦截器后面的postHandle与afterCompletion不再执行 */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestUri = request.getRequestURI(); for (String url : excludedUrls) { if (requestUri.contains(url)) { return true ; } } HttpSession session = request.getSession(); Boolean login = (Boolean) session.getAttribute( "login" ); if (login == null || !login) { //System.out.println(request.getContextPath()); logger.info( "Pedirect to login page" ); response.sendRedirect(request.getContextPath() + "/login" ); } return true ; } public void setExcludedUrls(List<String> excludedUrls) { this .excludedUrls = excludedUrls; } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/umgsai/p/5804766.html