1.1控制层
@RequestMapping("archives")
public String archives(Model model){
HashMap> map=newsService.archiveNews();
Long count=newsService.countNews();
model.addAttribute("newsCount",count);
model.addAttribute("archiveMap",map);
return "archives";
}
1.2实现层
@Override
public Long countNews() {
return newsDao.count();
}
@Override
public HashMap> archiveNews() {
LinkedHashMap> map=new LinkedHashMap<>();
List years=newsDao.findGroupYear();
for(String y:years){
Listnews=newsDao.findByYear(y);
map.put(y,news);
}
return map;
}
2.1控制层
@RequestMapping("/search")
public String search(@PageableDefault(size=3,sort={"updateTime"},direction = Sort.Direction.DESC)
Pageable pageable,
String query,
Model model){
Page page=newsService.findNewsByQuery(query,pageable);
model.addAttribute("page",page);
model.addAttribute("query",query);
return "search";
}
2.2实现层
@Override
public Page findNewsByQuery(String query, Pageable pageable) {
return newsDao.findByquery(query,pageable);
}
3.1控制层
@PostMapping("/comments")
public String save(Comment comment, HttpSession session){
User user=(User)session.getAttribute("name");
if(user==null){
comment.setAdminComment(false);
}else{
comment.setAdminComment(true);
}
commentService.save(comment);
Long newsId=comment.getNews().getId();
return "redirect:/comments/"+newsId;
}
@RequestMapping("/comments/{newsId}")
public String comments(@PathVariable Long newsId, Model model){
List comments=commentService.findCommentByNewsId(newsId);
model.addAttribute("comments",comments);
return "news :: commentList";
}
3.2实现层
@Override
public void save(Comment comment) {
if(comment.getParentComment().getId()==-1){
comment.setParentComment(null);
}
commentDao.save(comment);
}
@Override
public List findCommentByNewsId(Long newsId) {
Sort sort=Sort.by("createTime");
List comments=commentDao.findByNewsIdAndParentCommentNull(newsId,sort);
return comments;
}
4.1控制层
@RequestMapping("/footer/lastestNews")
public String lastestNews(Model model){
List lastestNewsList=newsService.findTop(3);
model.addAttribute("lastestNewsList", lastestNewsList);
return "_fragments::lastestNewsList1";
}
4.2实现层
@Override
public List findTop(int i) {
Sort sort=Sort.by(Sort.Direction.DESC,"updateTime");
Pageable pageable= PageRequest.of(0,i,sort);
return newsDao.findTop(pageable);
}
5.在登录时需要先登录,不能直接进入界面
WebConfig.java
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
LoginInterceptor.java
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle)throws Exception{
if(request.getSession().getAttribute("user")==null){
response.sendRedirect("/admin");
return false;
}
return true;
}