文章同步发布在我的个人博客(zhuoerhuobi.cn)
随着博客数量的增多,对于系统来说,一个归档功能显得必不可少。以下是基于springboot开发的按时间倒序的归档功能。
1、后端数据逻辑
首先如果能够提前在建文章表时增加文章的年、月等字段,可以方便我们从数据库有序、分层级的读取文章。由于我的article表早已创建好,其中只有创建时间戳这一个关于时间的字段,所以需要在代码进行一些较复杂的操作。
我的预想是按照年-月两层树结构来显示归档,所以我将全部文章倒序取出来之后,放在一个两级map中储存。
@GetMapping("/archive")
public String get(Model model) {
Article[] articles;
articles = articleService.selectAll();
Map<Integer,Map<Integer,Article[]>> archive = articleService.archiveArticles(articles);
而其中对文章进行合理放置的逻辑是遍历每篇文章一次,使用calendar类得到文章的年和月,然后将文章插入以该年为key的map的以该月为二级key的map中。
@Override
public Map<Integer, Map<Integer, Article[]>> archiveArticles(Article[] articles) {
Calendar calendar = Calendar.getInstance();
//hashmap是无序的,而LinkedHashMap是有序的
Map<Integer, Map<Integer, Article[]>> res = new LinkedHashMap<>();
for (int i