SpringMVC讀取Cookie判斷用戶是否登錄,對每一個action都要進(jìn)行判斷。之前使用jstl標(biāo)簽在頁面上判斷session如果沒有登錄就使用如下代碼跳轉(zhuǎn)到登錄頁面。
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 > |
但是測試發(fā)現(xiàn)如果session過期,頁面渲染就會無故中斷并且不會跳轉(zhuǎn)到登錄頁面。故嘗試使用攔截器來進(jìn)行登錄判斷。
攔截器配置文件如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!-- <mvc:mapping path="/**" /> 如果只寫一個*,則不能攔截類似/*/*的請求。靜態(tài)資源的請求需要判斷不進(jìn)行攔截 --> < 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 > |
攔截器實現(xiàn)類如下
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完全處理完請求后被調(diào)用 * 當(dāng)攔截器拋出異常時,依然會從當(dāng)前攔截器往回執(zhí)行所的攔截器的afterCompletion() */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { } //在業(yè)務(wù)處理器處理請求執(zhí)行完成后,生成視圖之前執(zhí)行的動作 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 在業(yè)務(wù)處理器處理請求之前被調(diào)用 * 如果返回false 則退出本攔截器,本攔截器后面的postHandle與afterCompletion不再執(zhí)行 */ 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; } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/umgsai/p/5804766.html