spring 使用Thymeleaf渲染html页面

1. 引入 Thymeleaf 依赖

首先,你需要在 pom.xml 文件中引入 Thymeleaf 的依赖。

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

2. 创建控制器

在 Spring Boot 中创建一个控制器,用来处理请求并传递热点资源和推荐资源的数据到前端。

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

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

@Controller
public class ResourceController {

    @GetMapping("/resources")
    public String showResources(Model model) {
        // 假设从数据库或者其他服务中获取热点资源和推荐资源
        HotResource hotResource = new HotResource("热点资源1", "12345", "67890");

        List<RecommendedResource> recommendedResources = new ArrayList<>();
        recommendedResources.add(new RecommendedResource("推荐资源1", "54321"));
        recommendedResources.add(new RecommendedResource("推荐资源2", "98765"));
        recommendedResources.add(new RecommendedResource("推荐资源3", "45678"));
        recommendedResources.add(new RecommendedResource("推荐资源4", "87654"));
        recommendedResources.add(new RecommendedResource("推荐资源5", "12321"));

        // 将数据传递到模板中
        model.addAttribute("hotResource", hotResource);
        model.addAttribute("recommendedResources", recommendedResources);

        return "resources"; // 返回模板名称,Thymeleaf 会渲染 resources.html
    }
}

class HotResource {
    private String name;
    private String resourceId;
    private String recordId;

    // 构造函数、getter和setter
    public HotResource(String name, String resourceId, String recordId) {
        this.name = name;
        this.resourceId = resourceId;
        this.recordId = recordId;
    }

    public String getName() {
        return name;
    }

    public String getResourceId() {
        return resourceId;
    }

    public String getRecordId() {
        return recordId;
    }
}

class RecommendedResource {
    private String name;
    private String resourceId;

    // 构造函数、getter和setter
    public RecommendedResource(String name, String resourceId) {
        this.name = name;
        this.resourceId = resourceId;
    }

    public String getName() {
        return name;
    }

    public String getResourceId() {
        return resourceId;
    }
}

3. 修改 Thymeleaf 模板

resources/templates 目录下创建 resources.html,并使用 Thymeleaf 语法动态渲染数据。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>资源推荐</title>
    <style>
        /* 样式部分和前面的保持一致 */
        body {
            font-family: 'Arial', sans-serif;
            background-color: #e0f7fa; /* 清爽的淡蓝色背景 */
            margin: 0;
            padding: 0;
            height: 100vh;
        }
        .container {
            width: 70vw;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            margin: 0 auto;
            position: relative;
            top: 0;
        }
        .section {
            margin-bottom: 30px;
        }
        .section h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        .section .item {
            margin: 10px 0;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            background-color: #fafafa;
            border: 1px solid #ddd;
            transition: all 0.3s ease;
        }
        .section .item:hover {
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-3px);
        }
        .section .item a {
            display: block;
            text-decoration: none;
            color: #00796b;
            font-size: 16px;
            font-weight: bold;
            transition: color 0.3s ease;
        }
        .section .item a:hover {
            color: #004d40;
        }
        .section .item p {
            margin: 5px 0;
            color: #555;
            font-size: 14px;
        }
        .hot-resource {
            border: 2px solid #f44336;
            background-color: #ffebee;
        }
        .recommended-resource {
            border: 2px solid #4caf50;
            background-color: #e8f5e9;
        }
        .scrollable-content {
            max-height: 60vh;
            overflow-y: auto;
            padding-right: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 热点资源部分 -->
        <div class="section">
            <h2>热点资源</h2>
            <div class="item hot-resource">
                <a th:href="@{/resource/hot(id=${hotResource.resourceId})}" target="_blank" th:text="${hotResource.name}">热点资源名称</a>
                <p th:text="'资源ID:' + ${hotResource.resourceId}">资源ID</p>
                <p th:text="'热点记录ID:' + ${hotResource.recordId}">热点记录ID</p>
            </div>
        </div>

        <!-- 推荐资源部分,带有滚动效果 -->
        <div class="section">
            <h2>推荐资源</h2>
            <div class="scrollable-content">
                <div th:each="recommendedResource : ${recommendedResources}">
                    <div class="item recommended-resource">
                        <a th:href="@{/resource/recommend(id=${recommendedResource.resourceId})}" target="_blank" th:text="${recommendedResource.name}">推荐资源名称</a>
                        <p th:text="'推荐资源ID:' + ${recommendedResource.resourceId}">推荐资源ID</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

4. 运行程序并测试

启动 Spring Boot 应用,访问 /resources,你应该会看到动态渲染的 热点资源推荐资源 内容。

5. 后端数据源

  • 热点资源和推荐资源的数据可以从数据库、API、或其他数据源中获取,在控制器中通过相应的服务层进行查询,然后将结果传递到视图。
  • 你还可以根据实际需要进行分页、排序、筛选等功能的扩展。

通过这种方式,热点资源和推荐资源内容可以由 Java 动态渲染,且页面布局和样式依然保持一致。

在 SSM(Spring + Spring MVC + MyBatis)框架中,通常使用 JSP 作为视图层技术。但如果你希望使用 **Thymeleaf** 来渲染 HTML 页面并显示 MySQL 数据,你需要将默认的 JSP 视图解析器替换为 Thymeleaf 模板引擎。 下面是一个完整的实现流程:从项目结构、配置到代码示例,展示如何在 SSM 架构中集成 Thymeleaf,并从 MySQL 查询数据后在 HTML 页面上显示。 --- ### ✅ 实现目标 - 使用 SSM(Spring + Spring MVC + MyBatis) - 集成 Thymeleaf 作为模板引擎 - 从 MySQL 查询用户数据 - 在 HTML 页面通过 Thymeleaf 渲染数据显示 --- ## 一、项目结构(Maven) ```bash src/ ├── main/ │ ├── java/ │ │ └── com/example/ │ │ ├── controller/UserController.java │ │ ├── service/UserService.java │ │ ├── service/impl/UserServiceImpl.java │ │ ├── mapper/UserMapper.java │ │ └── entity/User.java │ ├── resources/ │ │ ├── mybatis-config.xml │ │ ├── mapper/UserMapper.xml │ │ ├── jdbc.properties │ │ └── spring/ │ │ ├── applicationContext.xml │ │ └── spring-mvc.xml │ └── webapp/ │ └── WEB-INF/ │ └── templates/ │ └── user_list.html ``` --- ## 二、添加依赖(pom.xml) ```xml <dependencies> <!-- Spring 核心 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.21</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.21</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.21</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.11</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!-- MySQL 连接驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.16</version> </dependency> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.15.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.15.RELEASE</version> </dependency> </dependencies> ``` --- ## 三、数据库准备 ```sql CREATE DATABASE ssm_demo; USE ssm_demo; CREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), email VARCHAR(100) ); INSERT INTO user(name, email) VALUES ('张三', 'zhangsan@example.com'); INSERT INTO user(name, email) VALUES ('李四', 'lisi@example.com'); ``` --- ## 四、Java 实体类 ```java // com/example/entity/User.java package com.example.entity; public class User { private Integer id; private String name; private String email; // Getters and Setters public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } ``` --- ## 五、Mapper 接口与 XML 映射 ```java // com/example/mapper/UserMapper.java package com.example.mapper; import com.example.entity.User; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("SELECT * FROM user") List<User> findAll(); } ``` 或者使用 XML 方式(推荐): ```xml <!-- resources/mapper/UserMapper.xml --> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.UserMapper"> <select id="findAll" resultType="com.example.entity.User"> SELECT * FROM user </select> </mapper> ``` --- ## 六、Service 层 ```java // com/example/service/UserService.java package com.example.service; import com.example.entity.User; import java.util.List; public interface UserService { List<User> getAllUsers(); } // com/example/service/impl/UserServiceImpl.java package com.example.service.impl; import com.example.entity.User; import com.example.mapper.UserMapper; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> getAllUsers() { return userMapper.findAll(); } } ``` --- ## 七、Controller 控制器 ```java // com/example/controller/UserController.java package com.example.controller; import com.example.entity.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/users") public String listUsers(Model model) { List<User> users = userService.getAllUsers(); model.addAttribute("users", users); return "user_list"; // 对应 templates/user_list.html } } ``` --- ## 八、Thymeleaf 页面HTML) ```html <!-- src/main/webapp/WEB-INF/templates/user_list.html --> <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <h1>用户列表</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}">1</td> <td th:text="${user.name}">张三</td> <td th:text="${user.email}">zhangsan@example.com</td> </tr> </table> </body> </html> ``` --- ## 九、Spring 配置文件 ### 1. `resources/jdbc.properties` ```properties jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm_demo?useSSL=false&serverTimezone=UTC jdbc.username=root jdbc.password=your_password ``` ### 2. `resources/spring/applicationContext.xml`(整合 MyBatis) ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 加载数据库配置 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- Mapper 扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper"/> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 组件扫描 --> <context:component-scan base-package="com.example.service"/> </beans> ``` ### 3. `resources/spring/spring-mvc.xml`(启用 Thymeleaf) ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描 Controller --> <context:component-scan base-package="com.example.controller"/> <!-- 启用注解驱动 --> <mvc:annotation-driven/> <!-- 静态资源处理 --> <mvc:default-servlet-handler/> <!-- Thymeleaf 视图解析器 --> <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML" /> <property name="characterEncoding" value="UTF-8" /> <property name="cacheable" value="false"/> <!-- 开发时关闭缓存 --> </bean> <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver"/> </bean> <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine"/> <property name="characterEncoding" value="UTF-8"/> <property name="order" value="1"/> <property name="viewNames" value=".*"/> </bean> </beans> ``` ### 4. `web.xml` 配置 DispatcherServlet ```xml <!-- src/main/webapp/WEB-INF/web.xml --> <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <display-name>SSM Thymeleaf Demo</display-name> <!-- Spring Context --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring MVC --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` --- ## 十、运行项目 1. 将项目部署到 Tomcat。 2. 访问:`http://localhost:8080/your_project_name/users` 3. 应该能看到从 MySQL 查询出的用户列表。 --- ### ✅ 总结 以上代码实现了: - 使用 SSM 框架连接 MySQL; - 使用 MyBatis 查询数据; - 使用 Spring MVC 控制器传递数据; - 使用 Thymeleaf 模板渲染 HTML 页面; - 成功在浏览器中显示数据库内容。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值