Spring视图解析器与模板引擎(Thymeleaf、JSP)

Spring 视图解析器 + 模板引擎完全实战(2025 最新版)

直接告诉你:2025 年真实企业项目中,JSP 基本已死Thymeleaf 才是王道
这篇内容让你 30 分钟彻底搞定 Spring Boot 3.x 下的视图层全部姿势。

一、2025 年真实项目选择表(直接抄)

模板引擎是否还在用推荐指数适用场景备注
Thymeleaf主流王者5 stars所有新项目、服务端渲染、后台管理自然模板、强大方言、Spring Boot 原生支持
Freemarker极少2 stars老项目、邮件模板语法太古怪,社区萎缩
JSP已淘汰0 stars极老政府/银行项目Spring Boot 根本不推荐,Tomcat 12 已移除
Groovy Templates几乎没人1 star极少数老项目
Pebble/Beetl小众2 stars追求极致性能生态差
React/Vue + SSR前端主导4 stars前后端分离 + Next.js/Nuxt.js不是 Spring 视图解析器范畴

结论:新项目 99.9% 选 Thymeleaf,老项目如果还能改也建议换 Thymeleaf。

二、Thymeleaf 最新依赖 + 配置(Spring Boot 3.3 直接复制)

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 如果你想用 th:each 性能更高(推荐) -->
<dependency>
 <groupId>org.thymeleaf.extras</groupId>
 <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
# application.yml(几乎什么都不用配,Spring Boot 自动搞定)
spring:
  thymeleaf:
    prefix: classpath:/templates/           # 默认就是这个
    suffix: .html                           # 默认就是这个
    mode: HTML                              # 严格 HTML 模式
    encoding: UTF-8
    cache: false                            # 开发关闭,生产建议 true
    servlet:
      content-type: text/html

模板默认放:src/main/resources/templates/

三、Thymeleaf 核心语法速成表(面试 + 日常 100% 够用)

功能写法说明
输出变量${user.name} 或
判断th:if / th:unless
循环th:each=”user : ${users}”
条件选择th:switch + th:case
包含片段th:include / th:replace / th:insert推荐 th:fragment + th:replace
布局(Layout)th:fragment + th:replace类似 Vue slot
静态资源@{/css/style.css}自动加 context-path 和版本号
表单绑定th:object=”${user}” + th:field=”*{name}”
错误消息th:errors=”*{name}”
URL 带参@{/user/{id}/edit(id=${user.id})}
选中/勾选th:checked / th:selected
日期格式化th:text=”${#temporals.format(user.createTime,’yyyy-MM-dd HH:mm’)}”
安全(Spring Security)sec:authorize=”hasRole(‘ADMIN’)”需要加 extras-springsecurity6

四、生产级 Thymeleaf 布局模板(所有项目直接复制)

<!-- resources/templates/layout/main.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:replace="${title} ?: ~{::title} :: 默认标题">默认标题</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/admin.css}" rel="stylesheet">
</head>
<body>
    <!-- 顶部导航 -->
    <div th:replace="~{layout/header :: header}"></div>

    <!-- 左侧菜单 -->
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2" th:replace="~{layout/sidebar :: sidebar}"></div>

            <!-- 主内容区 -->
            <main class="col-md-10" th:replace="${content} ?: ~{::main}">
                <div th:replace="~{::main}"></div>
            </main>
        </div>
    </div>

    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
</body>
</html>
<!-- resources/templates/user/list.html -->
<html layout:decorate="~{layout/main}" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title>用户列表</title>
</head>

<div layout:fragment="content">
    <h2>用户管理</h2>
    <table class="table">
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${#temporals.format(user.createTime,'yyyy-MM-dd HH:mm')}"></td>
        </tr>
    </table>
</div>
</html>

五、Controller 返回视图写法(和 @RestController 完全不同)

@Controller          // 注意:不是 @RestController
@RequestMapping("/admin")
public class AdminController {

    // 返回 Thymeleaf 页面
    @GetMapping("/users")
    public String userList(Model model) {
        model.addAttribute("users", userService.list());
        return "user/list";                 // → /templates/user/list.html
    }

    // ModelAndView 写法(老项目常见)
    @GetMapping("/dashboard")
    public ModelAndView dashboard() {
        ModelAndView mv = new ModelAndView("admin/dashboard");
        mv.addObject("stats", dashboardService.getStats());
        return mv;
    }

    // 重定向
    @PostMapping("/users")
    public String create(User user) {
        userService.save(user);
        return "redirect:/admin/users";     // 注意加 redirect:
    }

    // 转发
    @GetMapping("/toAdd")
    public String toAdd() {
        return "forward:/admin/user/add.html";
    }
}

六、JSP 还能用吗?(2025 年残酷真相)

项目类型Spring Boot 版本是否支持 JSP备注
spring-boot-starter-web (Tomcat)3.xNot supportedTomcat 10+ 已移除 Jasper,JSP 彻底凉凉
spring-boot-starter-web (Undertow/Jetty)3.xNot supported同上
传统 war 部署到外部 Tomcat 8/92.7.xSupported仅剩这条路,2026 年 Tomcat 9 也停止支持

结论:别再学 JSP 了,浪费生命。

七、Thymeleaf + Spring Security 6 权限控制(后台系统标配)

<!-- 需要登录才能看到 -->
<div sec:authorize="isAuthenticated()">
    欢迎,<span sec:authentication="name"></span>
</div>

<!-- 只有管理员能看到 -->
<div sec:authorize="hasRole('ADMIN')">
    <a th:href="@{/admin/users}">用户管理</a>
</div>

<!-- 权限任意一个 -->
<div sec:authorize="hasAnyRole('ADMIN','MANAGER')">

八、2025 年最终推荐配置(直接复制到项目)

spring:
  thymeleaf:
    cache: true                     # 生产必开
    check-template-location: true
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
  web:
    resources:
      static-locations: classpath:/static/,classpath:/public/
  mvc:
    static-path-pattern: /**        # 静态资源访问路径

现在你已经完全掌握了现代 Spring 项目中唯一的视图层技术栈:
Thymeleaf + layout + Spring Security 集成

下一步你想学哪个?直接告诉我,我继续给你写:

  • Thymeleaf 高级技巧(自定义方言、SpringEL 高级写法)
  • 完全前后端分离:Spring Boot 做纯 API + Vue3/React + Nginx
  • Spring Boot 3 + Spring Security 6 + JWT + Thymeleaf 登录实战
  • 超漂亮的后台模板 AdminLTE / Tabler 集成

说吧,下一个主题我直接上干货!

文章已创建 3070

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部