首先说明,网上有很多资料和例子,都声称通过自己的例子和代码就能实现SpringBoot 整合 Thymeleaf实现后台传递到前端并显示值,实测并不可行,其主要原因是因为后端代码中传递数据使用的类不对。
本文将会讲解如何正确的在SpringBoot中 整合 Thymeleaf实现后台传递到前端,并在前端显示后端传递的数据。
1、pom.xml配置:
org.springframework.boot
spring-boot-starter-thymeleaf
2、application.properties配置
如果你使用的不是.properties而是使用.yml配置,请将下方代码中的“=”换成“:”# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/ #前端html文件路径
spring.thymeleaf.cache=false # 不使用缓存,易于修改后立马呈现效果
3、controller文件代码@RequestMapping(URLConstant.HOME_PAGE)
public String index(HttpServletRequest request, ModelMap map) {
map.put("firstParam","Hello World !");
return "/linkHome/index";
}
注意:这里是一个重点,使用ModelMap 来作为数据的承载体
4、index.html配置
html文件头配置(需要引入Thymeleaf):html>
具体数据显示:
将会有如下的显示效果:Hello World !