springboot和thymeleaf,bootstrap集成简单例子

本文介绍了如何使用Maven配置Spring Boot项目,并集成Thymeleaf模板引擎,包括pom.xml配置、启动类与控制器的整合,以及用户实体和模版文件的实现。通过实例展示如何创建并展示用户列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目整体结构

 

maven配置:pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.burns.capital</groupId>
    <artifactId>springboot_thymeleaf_2022_5_30</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.3.12.RELEASE </version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

启动类以及控制器类写到一起了:ThyApp.java

package com.burns.capital.test.thytest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@Controller
public class ThyApp {
    public static void main(String[] args) {
        SpringApplication.run(ThyApp.class, args);
    }

    @RequestMapping("/users")
    public String listUsers(Model model) {
        model.addAttribute("users", queryUsers());
        return "users";
    }

    private List<User> queryUsers() {
        List<User> users = new ArrayList<>();
        users.add(new User(1, "userA"));
        users.add(new User(2, "userB"));
        return users;
    }

}

实体类:User.java

package com.burns.capital.test.thytest;

public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

模版文件:users.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<!--<link rel="stylesheet" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css}"/>-->
<link rel="stylesheet" href="/bootstrap-3.4.1-dist/css/bootstrap.min.css"/>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table class="table table-hover table-bordered">
    <thead>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    </thead>
    <tbody>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}">0</td>
        <td th:text="${user.name}">Angus</td>
    </tr>
    </tbody>
</table>
</body>
</html>

运行ThyApp.java

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.3.12.RELEASE)

2022-06-01 17:14:33.484  INFO 5744 --- [  restartedMain] com.burns.capital.test.thytest.ThyApp    : Starting ThyApp on DESKTOP-S27LEGK with PID 5744 (E:\idea_workspace\study\springboot_thymeleaf\2022.5.30\target\classes started by 35725 in E:\idea_workspace\study\springboot_thymeleaf\2022.5.30)
2022-06-01 17:14:33.486  INFO 5744 --- [  restartedMain] com.burns.capital.test.thytest.ThyApp    : No active profile set, falling back to default profiles: default
2022-06-01 17:14:33.519  INFO 5744 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-06-01 17:14:33.519  INFO 5744 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-06-01 17:14:34.136  INFO 5744 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-06-01 17:14:34.143  INFO 5744 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-06-01 17:14:34.144  INFO 5744 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2022-06-01 17:14:34.192  INFO 5744 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-06-01 17:14:34.192  INFO 5744 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 672 ms
2022-06-01 17:14:34.302  INFO 5744 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-06-01 17:14:34.406  INFO 5744 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-06-01 17:14:34.428  INFO 5744 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-01 17:14:34.436  INFO 5744 --- [  restartedMain] com.burns.capital.test.thytest.ThyApp    : Started ThyApp in 1.191 seconds (JVM running for 1.788)
2022-06-01 17:14:46.949  INFO 5744 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-06-01 17:14:46.949  INFO 5744 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-06-01 17:14:46.952  INFO 5744 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms

访问浏览器地址:

http://localhost:8080/usersicon-default.png?t=M4ADhttp://localhost:8080/users

 

### 使用 Spring BootThymeleaf MyBatis 搭建智慧校园项目 #### 一、环境准备 为了顺利搭建基于 Spring BootThymeleaf MyBatis 的智慧校园项目,需先准备好开发环境。确保安装了 JDK 8 或更高版本,并配置好 Maven 构建工具。 #### 二、创建 Spring Boot 工程 启动 IDE(如 IntelliJ IDEA),新建一个 Spring Initializr 项目,选择 Web, Thymeleaf 及 MyBatis Frameworks 支持[^1]。 #### 三、数据库连接设置 编辑 `application.properties` 文件来定义数据库连接参数。对于本地测试,可以选择轻量级的关系型内存数据库 H2 来简化部署流程[^2]: ```properties spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MYSQL spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= ``` #### 四、实体类设计 根据业务需求分析并建立相应的 Java 类表示表结构。例如学生信息表 Student.java: ```java public class Student { private Long id; private String name; private Integer age; // Getters and Setters... } ``` #### 五、Mapper 接口编写 利用 MyBatis 提供的接口编程方式实现持久层操作逻辑。比如针对学生的 CRUD 方法声明于 IStudentMapper.java 中: ```java @Mapper public interface IStudentMapper { @Select("SELECT * FROM student WHERE id=#{id}") public Student selectById(@Param("id") long id); // Other methods... } ``` #### 六、Service 层封装 引入 Service 组件负责处理具体业务规则服务调用链路管理。以 StudentServiceImpl.java 为例说明如何组合 Mapper 完成特定任务: ```java @Service @Transactional(readOnly = true) public class StudentServiceImpl implements IStudentService { @Autowired private IStudentMapper mapper; @Override public List<Student> findAll() { return mapper.selectAll(); } // Implement other service methods here... } ``` #### 七、Controller 控制器构建 通过 RestController 注解标记 HTTP 请求处理器,在此接收来自客户端的数据请求并向视图传递响应结果。下面是一个简单例子 ControllerDemo.java : ```java @RestController @RequestMapping("/students") public class StudentController { @Autowired private IStudentService service; @GetMapping("") public ModelAndView list(ModelAndView modelAndView){ modelAndView.addObject("studentList",service.findAll()); modelAndView.setViewName("student/list"); return modelAndView; } // Define more endpoints as needed... } ``` #### 八、页面模板制作 借助 Thymeleaf 强大的表达式语法渲染动态网页内容。在 resources/templates 下新增 HTML 文件用于呈现学籍档案概览界面。以下是部分片段展示: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Students</title> <link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css"/> <script src="/webjars/jquery/jquery.min.js"></script> <script src="/webjars/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div th:fragment="content"> <table class="table table-striped"> <thead><tr><th>ID</th><th>Name</th><th>Age</th></tr></thead> <tbody> <tr th:each="stu : ${studentList}"> <td th:text="${stu.id}">ID</td> <td th:text="${stu.name}">Name</td> <td th:text="${stu.age}">Age</td> </tr> </tbody> </table> </div> </body> </html> ``` #### 九、分页功能集成 考虑到实际应用场景中的大数据集访问效率问题,建议采用原生 SQL 查询语句配合 LIMIT 关键字完成分页效果。同时调整前端显示样式以便用户交互体验更佳[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱的叹息

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值