归档
在NewService中定义方法
Map<String,List<News>> archiveNew();
在NewServiceImpl中进行实现
@Override
public Map<String, List<News>> archiveNew() {
List<String> years=newRepository.findGroupYear();
//HashMap无序,但是我们需要排序的年份,因此不用HashMap而用LinkedHashMap,按照添加的顺序进行遍历
Map<String,List<News>> map=new LinkedHashMap<>();
for(String year:years){
map.put(year,newRepository.findByYear(year));
System.out.println(year);
}
return map;
}
ArchiveShowController
@Controller
public class ArchiveShowController {
@Autowired
private NewService newService;
@GetMapping("/archives")
public String archives(Model model){
model.addAttribute("archiveMap",newService.archiveNew());
return "archives";
}
}
异常事件处理
建一个与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);
}
}
handler包
@ControllerAdvice //实现对全局异常进行处理
public class ControllerExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler
public ModelAndView exceptionhandler(HttpServletRequest request,Exception e) throws Exception{
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;
}
}
拦截器
LoginInterceptor类
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;
}
}
构建WevConfig类
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}
效果展示