前言
在项目的后续开发阶段,注重在某些功能上进行优化, 并将不完善的功能进行修补。这一次的博客将细纹管理系统的归档功能、异常处理以及登陆拦截加上。
实现过程
归档功能
在编写SQL语句时,最好先在IDEA中进行验证,确定SQL语句的功能完全正确。然后再将查询语句注释到Java程序中。
接着在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);
在service中增加归档和查询获取的接口
//归档
Map<String,List<News>> archiveNew();
//新闻数
Long countNew();
实现这两个接口
@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();
}
在controller进行更新
@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";
}
}
同时前端的HTML页面中需要接受两个信息的接收。
登陆拦截
在springboot框架中,本身存在登陆拦截的拦截器,这里可以对这个功能进行继承。处理器拦截器(HandlerInterceptor)是SpringWebMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于处理器进行预处理和后处理。应用场景之一就是权限检查,如登陆检测,进入处理器检测是否登陆,如果没有直接返回到登陆页面。
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类将HandlerInterceptorAdapter注入,实现拦截的功能。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}
异常处理
异常处理也是程序设计的常规操作了,可以借助springboot本省的异常处理进行设计。
定义一个异常类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的package,存放新建的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 mv=new ModelAndView();
mv.addObject("url",request.getRequestURL());
mv.addObject("exception",e);
mv.setViewName("error/error");
return mv;
}
}
结语
拦截器是一个比较关键的知识。springboot对传统Filter进行增强,添加更多细粒度的操作,分别实现预处理、后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、返回处理(已经渲染了页面)。在preHandle(预处理)中,可以进行编码、安全控制等处理;在postHandle(后处理)中,有机会修改ModelAndView;在afterCompletion(返回处理)中,可以根据ex是否为null判断是否发生了异常,进行日志记录。总之,传统的filter可以完成的功能,HandlerInterceptorAdapter都以完成。而异常处理就是在Java中也有非常丰富的接口可以进行使用了,每一种针对的情况都不一样。