1、归档
1.在NewService中定义接口
Map<String,List<News>> archiveNew();
Long countNew();
2.在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();
}
3.构建ArchiveShowController类,实现归档
@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";
}
}
2、异常处理
1.建立一个与dao、service等包同级的类
@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);
}
}
2.建立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("Resquest: 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;
}
}
3、登录拦截
1.建立interceptor包
建立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");
System.out.println("拦截");
return false;
}
System.out.println("放行");
return true;
}
}
3.建立WebConfig类实现WebMvcConfigurer接口
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}