public class NoLoginException extends RuntimeException {
private Integer code=300;
private String msg="用户未登录!";
}
全局异常处理
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
if (e instanceof NoLoginException) {
ModelAndView modelAndView = new ModelAndView("redirect:/index");
return modelAndView;
}
ModelAndView modelAndView = new ModelAndView("Error");
modelAndView.addObject("Code", 500);
modelAndView.addObject("msg", "系统异常,请重试...");
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
ResponseBody responseBody = handlerMethod.getMethod().getDeclaredAnnotation(ResponseBody.class);
if (responseBody == null) {
if (e instanceof ParamsException) {
ParamsException p = (ParamsException) e;
modelAndView.addObject("code", p.getCode());
modelAndView.addObject("msg", p.getMsg());
}
return modelAndView;
} else {
ResultInfo resultInfo = new ResultInfo();
resultInfo.setCode(500);
resultInfo.setMsg("系统异常,请重试!");
if (e instanceof ParamsException) {
ParamsException p = (ParamsException) e;
resultInfo.setCode(p.getCode());
resultInfo.setMsg(p.getMsg());
}
httpServletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter out = null;
try {
out = httpServletResponse.getWriter();
String json = JSON.toJSONString(resultInfo);
out.write(json);
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
return null;
}
}
return modelAndView;
}
}
拦截器(非法访问拦截器)
public class NoLoginInterceptor extends HandlerInterceptorAdapter {
@Resource
private UserMapper userMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
if (null == userId || userMapper.selectByPrimaryKey(userId) == null) {
throw new NoLoginException();
}
return true;
}
}
资源拦截器
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
public NoLoginInterceptor noLoginInterceptor() {
return new NoLoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(noLoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/CSS/**", "/images/**", "/js/**", "/lib/**","/index","/user/login");
}
}
|