package com.zpedku.interceptor;
import com.zpedku.config.AppConfig;
import com.zpedku.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* session过期跳转页面拦截器
*/
@Slf4j
public class SystemSessionInterceptor implements HandlerInterceptor {
@Value("${projectName}")
private String projectName;
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object o) throws Exception {
HttpSession session = req.getSession(true);
String requestURI = req.getRequestURI();
log.info("requestURI={}",requestURI);
if(StringUtils.contains(requestURI, AppConfig.LOGIN_PATH)) return true;
SysUser sysUser = (SysUser) session.getAttribute(AppConfig.SYS_USER_SESSION);
if(sysUser!=null) return true;
if(isAjax(req)){//若是ajax请求,直接设置请求头session过期
res.setHeader("sessionstatus", "timeout");
res.sendError(518, "session timeout.");
}else{
//res.sendRedirect(req.getSession().getServletContext().getContextPath() +
//"/login.html");
res.setContentType("text/html");
res.setCharacterEncoding("utf-8");
PrintWriter out = res.getWriter();
StringBuilder builder = new StringBuilder();
builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
//builder.append("alert(\"登录已过期,请重新登录!\");");
builder.append("parent.window.location.href='"+req.getContextPath()+"/login.html';");
builder.append("</script>");
out.print(builder.toString());
out.close();
return false;
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
/**
* 判断是否是ajax请求
* @param req
* @return
*/
private boolean isAjax(HttpServletRequest req){
if( req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) return true;
return false;
}
}
spring拦截器实现seesion过期跳转首页
点赞
收藏