SpringBoot项目实现归档功能加异常处理与登录拦截

1、归档功能

①、在NewRepository接口中添加两条查询方法头

    @Query("select function('date_format',n.updateTime,'%Y') as year from News n group by year order by year desc ")
    List<String> findGroupYear();
    @Query("select n from News n where function('date_format',n.updateTime,'%Y') =?1")
    List<News> findByYear(String year);

②、在NewService中添加如下两个方法头,并在Impl中进行实现

    public Map<String, List<News>> archiveNews() {
        List<String> years = newRepository.findGroupYear();
        Map<String, List<News>> map = new LinkedHashMap<>();
        for(String year:years){
            map.put(year,newRepository.findByYear(year));
            System.out.println(year);
        }
        return map;
    }
    public Long countNew() {
        return newRepository.count();
    }

③、新建ArchiveShowController控制类实现归档功能的前端显示

    @GetMapping("/archives")
    public String archives(Model model){
        model.addAttribute("archiveMap",newService.archiveNews());
        model.addAttribute("newsCount",newService.countNew());
        return "archives";
    }

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);
    }
}

②、新建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("Requset: URL: {},Exception: {}",request.getRequestURI(),e);
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            throw e;
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURI());
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }
}

3、登录拦截

拦截器依赖于web框架,属于面向切面编程(AOP)并且只能拦截Controller的请求,对于静态请求可以用过滤器(Filter)进行实现

①、新建LoginInterceptor拦截器,继承自HandlerInterceptorAdapter父类实现登录拦截规则

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;
    }
}

②、新建WebConfig配置类,implement WebMvcConfigurer接口,实现其中的addInterceptors接口方法

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
posted @ 2020-08-02 17:31  Dragon_xl  阅读(300)  评论(0)    收藏  举报