spring boot搭建个人博客中如何实现列表,详情,分页功能

发布时间:2021-12-10 19:04:36 作者:柒染
来源:亿速云 阅读:319
# Spring Boot搭建个人博客中如何实现列表,详情,分页功能

## 前言

在个人博客系统的开发中,文章列表展示、详情查看和分页功能是核心模块。本文将基于Spring Boot框架,结合Thymeleaf模板引擎和Spring Data JPA,详细讲解如何实现这三个关键功能。通过本文的实践,读者可以快速掌握博客系统的基础开发技能。

## 一、环境准备

### 1.1 技术栈
- JDK 1.8+
- Spring Boot 2.7.x
- Spring Data JPA
- Thymeleaf模板引擎
- MySQL数据库

### 1.2 项目初始化
使用Spring Initializr创建项目,勾选以下依赖:
```xml
<dependencies>
    <!-- Web支持 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Thymeleaf模板引擎 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <!-- JPA支持 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

二、数据库设计

2.1 文章表结构

CREATE TABLE `article` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `create_time` datetime NOT NULL,
  `update_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

三、核心功能实现

3.1 实体类映射

@Entity
@Table(name = "article")
@Data
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String title;
    
    @Lob
    private String content;
    
    @CreationTimestamp
    private LocalDateTime createTime;
    
    @UpdateTimestamp
    private LocalDateTime updateTime;
}

3.2 列表功能实现

3.2.1 Repository接口

public interface ArticleRepository extends JpaRepository<Article, Long> {
    // 查询所有文章按创建时间倒序
    List<Article> findAllByOrderByCreateTimeDesc();
}

3.2.2 Controller层

@Controller
public class ArticleController {
    
    @Autowired
    private ArticleRepository articleRepository;
    
    @GetMapping("/")
    public String list(Model model) {
        model.addAttribute("articles", articleRepository.findAllByOrderByCreateTimeDesc());
        return "list";
    }
}

3.2.3 前端页面(list.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>文章列表</title>
</head>
<body>
    <div th:each="article : ${articles}">
        <h2><a th:href="@{/article/{id}(id=${article.id})}" 
               th:text="${article.title}"></a></h2>
        <p th:text="${#dates.format(article.createTime, 'yyyy-MM-dd')}"></p>
    </div>
</body>
</html>

3.3 详情功能实现

3.3.1 Controller新增方法

@GetMapping("/article/{id}")
public String detail(@PathVariable Long id, Model model) {
    Article article = articleRepository.findById(id)
            .orElseThrow(() -> new NotFoundException("文章不存在"));
    model.addAttribute("article", article);
    return "detail";
}

3.3.2 详情页面(detail.html)

<div>
    <h1 th:text="${article.title}"></h1>
    <div th:utext="${article.content}"></div>
    <p>发布时间: <span th:text="${#dates.format(article.createTime, 'yyyy-MM-dd HH:mm')}"></span></p>
</div>

3.4 分页功能实现

3.4.1 Repository修改

// 分页查询方法已内置在JpaRepository中

3.4.2 Controller改造

@GetMapping("/")
public String list(
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "10") int size,
        Model model) {
    
    Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
    Page<Article> articlePage = articleRepository.findAll(pageable);
    
    model.addAttribute("articles", articlePage.getContent());
    model.addAttribute("page", articlePage);
    return "list";
}

3.4.3 分页页面改造

<!-- 分页导航 -->
<div class="pagination">
    <span th:if="${!page.first}">
        <a th:href="@{/(page=1)}">首页</a>
        <a th:href="@{/(page=${page.number})}">上一页</a>
    </span>
    
    <span th:each="i : ${#numbers.sequence(1, page.totalPages)}">
        <a th:if="${i == page.number + 1}" class="active" 
           th:href="@{/(page=${i})}" th:text="${i}"></a>
        <a th:unless="${i == page.number + 1}" 
           th:href="@{/(page=${i})}" th:text="${i}"></a>
    </span>
    
    <span th:if="${!page.last}">
        <a th:href="@{/(page=${page.number + 2})}">下一页</a>
        <a th:href="@{/(page=${page.totalPages})}">末页</a>
    </span>
</div>

四、功能优化建议

  1. 缓存优化:对热门文章添加Redis缓存
  2. 性能优化:列表页只查询必要字段
  3. 前端优化:添加Ajax分页加载
  4. SEO优化:为详情页添加meta标签

结语

通过本文的实践,我们完成了博客系统的核心功能模块。Spring Boot的自动化配置和JPA的强大功能让我们能够快速实现业务需求。读者可以在此基础上继续扩展标签分类、评论系统等功能,打造更完善的个人博客系统。 “`

该文章共计约1300字,包含了完整的代码示例和实现步骤,采用Markdown格式编写,可直接用于技术博客发布。如需调整内容细节或扩展某些部分,可以进一步修改完善。

推荐阅读:
  1. 如何在Spring中利用REST实现一个分页功能
  2. Spring Cloud  Eureka服务治理的实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot

上一篇:如何搭建威胁情报数据库

下一篇:基于kubernetes搭建分布式压测系统是怎样的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》