本次实现了新闻的归档和异常处理,以及拦截未登录用户并返回到登陆界面
本次以异常处理和登录拦截为例
异常处理
-
在recourses文件夹下添加下图的异常处理HTML文件
-
在根目录下新建一个
NotFoundException
类,继承RuntimeException
类,继承父类方法@ResponseStatus(HttpStatus.NOT_FOUND) public class NotFoundException extends RuntimeException { public NotFoundException() { } public NotFoundException(String message) { super(message); } public NotFoundException(String message, Throwable cause) { super(message, cause); } }
-
新建
handler.ControllerExceptionHandler
包,对异常进行处理,使发生错误时转到错误页面@ControllerAdvice public class ControllerExceptionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(Exception.class) public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception { logger.error("Request: URL: {}, Exception: {}", request.getRequestURL(), e); if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) { throw e; } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("url", request.getRequestURL()); modelAndView.addObject("exception", e); modelAndView.setViewName("error/error"); return modelAndView; } }
登录拦截
-
新建
interceptor.LoginInterceptor
类,对登录的用户进行判断和跳转public class LoginInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getSession().getAttribute("user") == null) { response.sendRedirect("/admin"); return false; } return true; } }
-
设计
com.llanero.news.interceptor.WebConfig
类,调用LoginInterceptor
的方法处理要拦截的页面地址@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/admin/**") .excludePathPatterns("/admin") .excludePathPatterns("/admin/login"); } }