Java Web项目配置模板引擎核心是选型、引入依赖、注册处理器、配置路径和渲染逻辑;推荐Thymeleaf,Spring Boot通过spring-boot-starter-thymeleaf自动配置,默认路径src/main/resources/templates/,返回字符串视图名即映射HTML文件,支持Model传参与URL重写。

在Java Web项目中配置模板引擎,核心是选型、引入依赖、注册处理器、配置路径和渲染逻辑。主流选择有Thymeleaf(推荐)、Freemarker、JSP(传统但逐渐淘汰)和Velocity。下面以Spring Boot + Thymeleaf为例,说明如何快速搭建并解析关键配置。
使用Maven,在pom.xml中加入Thymeleaf starter:
spring-boot-starter-thymeleaf
thymeleaf-extras-java8time等扩展Thymeleaf默认查找路径为src/main/resources/templates/(静态资源走static,模板走templates):
templates/下,如templates/index.html
"index"时,自动映射到该路径下的index.html
spring.thymeleaf.prefix=classpath:/templates/自定义前缀(一般不改)spring.thymeleaf.suffix=.html指定后缀,默认即.html,支持.htm、xml等Spring MVC控制器方法返回String视图名,由ViewResolver解析:
立即学习“Java免费学习笔记(深入)”;
@Controller(非@RestController),方法返回"user/list" → 渲染templates/user/list.html
Model或ModelMap:model.addAttribute("users", userList)
th:text="${users}"或th:each="user : ${users}"访问th:href="@{/user/{id}(id=${user.id})}",自动处理上下文路径以下配置影响开发体验和生产行为:
spring.thymeleaf.cache=false:开发时禁用模板缓存,改完HTML立即生效spring.thymeleaf.enabled=true:全局开关,设为false则禁用Thymeleaf自动配置spring.thymeleaf.encoding=UTF-8:避免中文乱码,建议显式声明spring.thymeleaf.servlet.content-type=text/html:响应Content-Typethymeleaf-extras-springsecurity6依赖,支持权限标签如sec:authorize
基本上就这些。模板引擎本身不复杂,关键是路径约定、依赖对齐和缓存控制。选Thymeleaf是因为它天然支持HTML原型、语法直观、与Spring生态无缝集成。其他引擎如Freemarker只需替换依赖+调整配置前缀后缀,逻辑类似。
以上就是在Java中如何搭建Web项目的模板引擎环境_模板引擎配置解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号