public class CheckSessionInterceptor implements HandlerInterceptor {
/**
* 生成视图时执行,可以用来处理异常,并记录在日志中
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception exception){
}
/** -
* 生成视图之前执行,可以修改ModelAndView
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception{
}
/**
* 进入拦截器后首先进入的方法
* 返回false则不再继续执行
* 返回true则继续执行
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getContextPath();
if(request.getRequestURI().equals(path) || request.getRequestURI().equals(path + "/")) {
return true;
}
HandlerMethod handlerMethod = null;
try {
handlerMethod = (HandlerMethod)handler;
} catch(ClassCastException ex) {
return true;
}
NoCheckSession noCheckSession = handlerMethod.getMethodAnnotation(NoCheckSession.class);
ResponseBody jsonMethod = handlerMethod.getMethodAnnotation(ResponseBody.class);
if(noCheckSession == null) {
if(request.getSession().getAttribute(BaseController.LOGIN_USER) == null) {
if(jsonMethod != null) {
response.reset();
response.setContentType("application/json; charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write("{\"success\" : false, \"exceptionflag\":\"no_session\"}");
pw.flush();
pw.close();
return false;
} else {
request.getRequestDispatcher("/sys/logout").forward(request, response);
return false;
}
}
}
return true;
}
}