本次迭代任务主要实现用户界面根据不同的类型、标签显示新闻以及根据年份对新闻的归档。
一、新闻显示
界面显示
查出新闻的总数。
@Override
public Long conutNews() {
return newsDao.count();
}
分类型显示
我们需要根据不同类型的类型ID来从数据库中识别数据。
三个重要参数:
- Pageable pageable:数据在页面分页展示时使用
- Long id:类型ID,用来查找数据
- Model model:Model对象,用来将数据从后端传到前端显示
第一个是数据在页面分页展示时使用,第二个参数是分类的id,用来查找数据,第三个是Model对象,用来将数据从后端传到前端显示。
@Controller
public class TypeShowController {
@Autowired
private TypeService typeService;
@Autowired
private NewsService newsService;
@RequestMapping("/types/{id}")
public String types(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
@PathVariable Long id, Model model){
List<Type> types = typeService.findTop(7);
if(id==-1){
id = types.get(0).getId();
}
NewsQuery newsQuery = new NewsQuery();
newsQuery.setTypeId(id.toString());
Page<News> page = newsService.searchNews(pageable, newsQuery);
model.addAttribute("page",page);
model.addAttribute("types",types);
return "types";
}
}
分标签显示
@Controller
public class TagShowController {
@Autowired
private TagService tagService;
@Autowired
private NewsService newsService;
@RequestMapping("/tags/{id}")
public String tag(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
@PathVariable Long id, Model model){
List<Tag> tags=tagService.findTop(7);
if(id==-1){
id=tags.get(0).getId();
}
Page<News> page=newsService.searchNews(pageable,id);
model.addAttribute("page",page);
model.addAttribute("tags",tags);
return "tags";
}
}
二、年份归档
Controller层
将不同的年份的新闻放到HashMap中,并在前端对其进行遍历。我们在ArchiveController中将HashMap和数量Count查出来,传到前端。
@RequestMapping("archives")
public String archives(Model model){
HashMap<String, List<News>> map = newsService.archiveNews();
Long count = newsService.conutNews();
model.addAttribute("newsCount",count);
model.addAttribute("archiveMap",map);
return "archives";
}
Service层
在NewsServiceImpl中查出来HashMap
@Override
public HashMap<String, List<News>> archiveNews() {
LinkedHashMap<String, List<News>> map=new LinkedHashMap<>();
List<String> years = newsDao.findGroupYear();
for(String year:years){
List<News> news = newsDao.findByYear(year);
map.put(year,news);
}
return map;
}