spring boot新闻管理——异常处理和登录拦截

本次实现了新闻的归档和异常处理,以及拦截未登录用户并返回到登陆界面
本次以异常处理和登录拦截为例

异常处理

  1. 在recourses文件夹下添加下图的异常处理HTML文件

  2. 在根目录下新建一个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);
        }
    
    }
    
  3. 新建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;
        }
    
    }
    

登录拦截

  1. 新建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;
        }
    }
    
  2. 设计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");
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值