SessionInterceptor.java
2.53 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.bjivt.web.interceptor;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.google.common.collect.Lists;
/**
* 权限中的session拦截器,用来检测某个session是否存在,不存在就跳转到登录页面
*
* lyd
*/
public class SessionInterceptor implements HandlerInterceptor {
private List<String> ignoreList = Lists.newArrayList();
private String sessionName;
private String loginUrl;
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public List<String> getIgnoreList() {
return ignoreList;
}
public void setIgnoreList(List<String> ignoreList) {
this.ignoreList = ignoreList;
}
public String getSessionName() {
return sessionName;
}
public void setSessionName(String sessionName) {
this.sessionName = sessionName;
}
/**
* 释放资源
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
/**
* 在生成视图前,就是通过拦截器反向返回给客户端时执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
/**
* 在运行业务代码前,就是用户提交数据到服务器时执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String url = request.getRequestURI();
AntPathMatcher matcher = new AntPathMatcher();
if (matcher.match(request.getContextPath() + loginUrl, url)) {
return true;
}
if (isIgnore(request.getContextPath(),url)) {
return true;
}
HttpSession session = request.getSession();
if (session.getAttribute(sessionName) != null) {
return true;
}
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath();
response.sendRedirect(basePath + loginUrl);
return false;
}
private boolean isIgnore(String contextPath,String url) {
AntPathMatcher matcher = new AntPathMatcher();
for (String matchurl : ignoreList) {
if (matcher.match(contextPath+matchurl, url)) {
return true;
}
}
return false;
}
}