项目迭代之:归档、异常处理、登录拦截

项目迭代之:归档、异常处理、登录拦截

归档功能实现

一、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

    Map<String,List<News>> archiveNew();

    Long countNew();

三、NewServiceImpl

    @Override
    public Map<String, List<News>> archiveNew() {
        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;
    }

    @Override
    public Long countNew() {
        return newRepository.count();
    }

四、ArchiveShowController

package com.whut.news.web;

import com.whut.news.service.NewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ArchiveShowController {

    @Autowired
    private NewService newService;

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

}

异常处理添加

一、handler.ControllerExceptionHandler

package com.whut.news.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

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

二、NotFoundException

package com.whut.news;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

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


登录拦截功能实现

一、LoginInterceptor

package com.whut.news.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 super.preHandle(request, response, handler);
    }
}


二、WebConfig

package com.whut.news.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
}


©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页