(1)编写filter
- 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
- 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
/** * 拦截器示例 * @author chenpengye * 2015年12月10日 上午10:23:50 */
public class SessonFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(SessonFilter.class);
@Override
public void init(FilterConfig filterConfig)
throws ServletException {
}
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException,ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
String uri = httpRequest.getRequestURI();
String ctxpath = httpRequest.getContextPath();
String userid = (String)session.getAttribute(
"userid");
if(uri.contains(
"/user/login") || uri.contains(
"/user/regPage") ){
chain.doFilter(request,response);
}
else{
if(userid ==
null){
String contextPath = httpRequest.getContextPath();
String redirect = contextPath ;
if (httpRequest.getHeader(
"x-requested-with") !=
null
&&
"XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader(
"x-requested-with"))) {
httpResponse.setHeader(
"sessionstatus",
"timeout");
httpResponse.setStatus(
403);
httpResponse.addHeader(
"loginPath",ctxpath);
chain.doFilter(request,response);
log.debug(
"ajax request");
return ;
}
httpResponse.sendRedirect(redirect);
return;
}
else{
chain.doFilter(request,response);
}
}
}
@Override
public void destroy() {
}
}
主要参考
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
if (httpRequest.getHeader(
"x-requested-with") !=
null
&&
"XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader(
"x-requested-with"))) {
httpResponse.setHeader(
"sessionstatus",
"timeout");
httpResponse.setStatus(
403);
httpResponse.addHeader(
"loginPath",ctxpath);
chain.doFilter(request,response);
log.
debug(
"ajax request");
return ;
}
(2)配置js
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
$(document).ajaxComplete(
function(event,xhr,settings) {
if(xhr.getResponseHeader(
"sessionstatus")==
"timeout"){
if(xhr.getResponseHeader(
"loginPath")){
alert(
"会话过期,请重新登陆!");
window.location.replace(xhr.getResponseHeader(
"loginPath"));
}
else{
alert(
"请求超时请重新登陆 !");
}
}
});