SpringBoot项目添加新闻首页与详情页
1、在New、Tag和Type的Repository接口中添加相应的数据库查询语句与对应方法头
NewRepository中添加:
@Query("select n from News n where n.title like ?1 or n.content like ?1") Page<News> findByQuery(String query, Pageable pageable); @Query("select n from News n where n.recommend=true") List<News> findTop(Pageable pageable);
TagRepository中添加:
@Query("select t from Tag t")
List<Tag> findTop(Pageable pageable);
TypeRepository中添加:
@Query("select t from Type t")
List<Type> findTop(Pageable pageable);
2、在New、Tag和Type的Service接口中添加相应的显示和搜索方法头,New中额外添加样式转化方法头
NewService中添加:
//主页显示新闻列表 Page<News> listNew(Pageable pageable); //主页推荐最新新闻列表 List<News> ListRecommendNewTop(Integer size); //全局搜索 Page<News> listNew(String query,Pageable pageable); News getAndConvert(Long id);
TagService中添加:
List<Tag> listTag(String ids);
List<Tag> listTagTop(Integer size);
TypeService中添加:
List<Type> listTypeTop(Integer size);
3、在相应的Service中进行这些方法的实现;以List<News> ListRecommendNewTop(Integer size)和List<Tag> listTagTop(Integer size)为例
public List<News> ListRecommendNewTop(Integer size) { Sort sort =Sort.by(Sort.Direction.DESC,"updateTime"); Pageable pageable= PageRequest.of(0,size,sort); return newRepository.findTop(pageable); }
public List<Tag> listTagTop(Integer size) { Sort sort =Sort.by(Sort.Direction.DESC,"newsList.size"); Pageable pageable= PageRequest.of(0,size,sort); return tagRepository.findTop(pageable); }
4、在主页控制类中定义并实现主页,查找页,详情页的前后端交互类;以search为例
@PostMapping("/search")
public String search(@PageableDefault(size=3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
@RequestParam String query, Model model){
model.addAttribute("page",newService.listNew("%"+query+"%",pageable));
model.addAttribute("query",query);
return "search";
}

浙公网安备 33010602011771号