本次实现了新闻的归档和异常处理,以及拦截未登录用户并返回到登陆界面
本次以异常处理和登录拦截为例
异常处理
-
在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"); } }
Spring异常处理与登录拦截
本文详细介绍了在Spring框架中实现异常处理和登录状态拦截的方法。通过创建自定义异常类和异常处理器,确保应用程序能够优雅地处理运行时错误,并引导用户至错误页面。同时,设计了登录拦截器,有效管理未登录用户的访问权限。
658

被折叠的 条评论
为什么被折叠?



