1. 程式人生 > 實用技巧 >SpringBoot專案實現歸檔功能加異常處理與登入攔截

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