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; } }