基於SpringBoot從零構建博客網站

顯示文章列表一般都是採用分頁顯示,比如每頁10篇文章顯示。這樣就不用每次就將所有的文章查詢出來,而且當文章數量特別多的時候,如果一次性查詢出來很容易出現OOM異常。

後臺的分頁插件採用的是mybatis-plus自帶的,前端顯示時利用boostrap的風格顯示。

1、開啟分頁插件

對於mybatis-plus框架,開啟分頁插件是很簡單的,只需要加一個配置類,即:

/**
* Mybatis Plus分頁配置類
*
* @author lzj
* @since 1.0
* @date [2019-08-11]
*/
@EnableTransactionManagement
@Configuration
@MapperScan("com.swnote.*.dao.*")
public class MybatisPlusConfig {

/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}

這樣就將分頁插件配置好了。

2、文章分頁後臺邏輯

mybatis-plus框架很友好的提供好分頁查詢的功能,為此在後臺可以直接調用,核心的邏輯為:

/**
* 分頁加載出文章列表頁面
*
* @param code
* @param pageIndex
* @param model
* @param session
* @return
*/
@RequestMapping(value = "/u/{code}/article/{pageIndex}", method = RequestMethod.GET)
public String list(@PathVariable("code") String code, @PathVariable("pageIndex") int pageIndex, Model model, HttpSession session) throws Exception {
// 根據code獲取用戶信息
User user = userService.getByCode(code);
if (user == null) {
log.error("code:" + code + ",不存在的用戶");
throw new Exception("不存在的用戶");
}
String userId = user.getUserId();

// 獲取登錄信息
User tempUser = (User) session.getAttribute(Const.SESSION_USER);

// 判斷是否是該用戶的筆記集
boolean flag = false;
if (tempUser != null && userId.equals(tempUser.getUserId())) {
flag = true;
}

// 構建查詢條件
Map<string> params = new HashMap<string>();
params.put("userId", userId);
if (!flag) {
params.put("status", Article.STATUS_SUCCESS);
}

// 分頁查詢
IPage<article> articles = articleService.page(new Page<article>(pageIndex, 10), new QueryWrapper<article>().allEq(params).orderByDesc("publishTime"));

// 獲取文章相關的信息
List<article> list = articles.getRecords();
if (list != null && !list.isEmpty()) {
list.stream().forEach(article -> {

// 作者用戶ID,獲取用戶信息
User articleUser = userService.getById(article.getUserId());
if (StringUtils.isEmpty(articleUser.getRealName())) {
article.setUserName(articleUser.getLoginName());
} else {
article.setUserName(articleUser.getRealName());
}

// 根據專欄ID,獲取專欄信息
if (!StringUtils.isEmpty(article.getGroupId())) {
Group articleGroup = groupService.getById(article.getGroupId());
article.setGroupName(articleGroup.getName());
}
});
}

model.addAttribute("user", user);
model.addAttribute("articles", articles);
return Const.BASE_INDEX_PAGE + "blog/article/list";
}
/<article>/<article>/<article>/<article>/<string>/<string>

裡面最主要的分頁查詢代碼為:

// 分頁查詢
IPage<article> articles = articleService.page(new Page<article>(pageIndex, 10), new QueryWrapper<article>().allEq(params).orderByDesc("publishTime"));
/<article>/<article>/<article>

3、文章分頁前臺邏輯

其實分頁前臺邏輯主要是將分頁的頁碼生成好,在此羅列出生成分頁頁碼的核心代碼如下:




${articles.total}條 共${articlePages}頁






  • #if>






  • #if>


#if>

這個mybatis-plus框架生成分頁數據好像生成的總頁數沒有傳過來,所以在前臺將總頁數計算出來,即:


前臺文章列表展示風格如下:

基於SpringBoot從零構建博客網站 - 分頁顯示文章列表功能


分享到:


相關文章: