SpringBoot中怎么搭建Thymeleaf环境,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
在甘孜州等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都网站设计、成都做网站 网站设计制作按需搭建网站,公司网站建设,企业网站建设,成都品牌网站建设,网络营销推广,外贸营销网站建设,甘孜州网站建设费用合理。
1. 依赖
首先我们是需要一个springboot项目,基本的pom结构大都相似
org.springframework.boot spring-boot-starter-parent 2.0.4.RELEASE UTF-8 UTF-8 Finchley.RELEASE 1.8 org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
在这个项目中,我们主要需要引入两个依赖包,一个web,一个thymeleaf
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf
2. 配置参数
通常我们直接使用默认的thymeleaf参数配置即可,下面给出几个常用的配置
spring: thymeleaf: mode: HTML encoding: UTF-8 servlet: content-type: text/html cache: false
thymeleaf的参数,主要对应的是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
II. 项目搭建演示
1. 项目结构
搭建一个web项目和我们之前的纯后端项目有点不一样,前端资源放在什么地方,依赖文件怎么处理都是有讲究的,下面是一个常规的项目结构

如上图,前端资源文件默认放在resources目录下,下面有两个目录
templates:存放模板文件,可以理解为我们编写的html,注意这个文件名不能有问题static: 存放静态资源文件,如js,css,image等
2. Rest服务
我们这里提供了三个接口,主要是为了演示三种不同的数据绑定方式(和Freemaker这篇博文基本一样)
@Controller
public class IndexController {
@GetMapping(path = {"", "/", "/index"})
public ModelAndView index() {
Map data = new HashMap<>(2);
data.put("name", "YiHui Thymeleaf");
data.put("now", LocalDateTime.now().toString());
return new ModelAndView("index", data);
}
/**
* 一般不建议直接使用jdk的String.split来分割字符串,内部实现是根据正则来处理的,虽然更强大,但在简单的场景下,性能开销更大
*/
private static String[] contents =
("绿蚁浮觞香泛泛,黄花共荐芳辰。\n清霜天宇净无尘。\n登高宜有赋,拈笔戏成文。\n可奈园林摇落尽,悲秋意与谁论。\n眼中相识几番新。\n龙山高会处,落帽定何人。").split("\n");
private static Random random = new Random();
@GetMapping(path = "show1")
public String showOne(Model model) {
model.addAttribute("title", "临江仙");
model.addAttribute("content", contents[random.nextInt(6)]);
return "show1";
}
@GetMapping(path = "show2")
public String showTow(Map data) {
data.put("name", "Show2---->");
data.put("now", LocalDateTime.now().toString());
return "show2";
}
} 上面的三种case中
第一个是最好理解的,在创建
ModelAndView时,传入viewName和数据第二个是通过接口参数Model,设置传递给view的数据
第三种则直接使用Map来传递数据
三个接口,对应的三个html文件,如下
index.html
YiHui's SpringBoot Demo
show1.html
YiHui's SpringBoot Demo 标题!内容
show2.html
YiHui's SpringBoot Demo 标题!内容
在上面的模板文件中,需要注意引用css样式文件,路径前面并没有static,我们对应的css文件
index.css
.title {
color: #c00;
font-weight: normal;
font-size: 2em;
}
.content {
color: darkblue;
font-size: 1.2em;
}
.sign {
color: lightgray;
font-size: 0.8em;
font-style: italic;
}3. 演示
启动项目后,可以看到三个页面的切换,模板中的数据根据后端的返回替换,特别是主页的时间,每次刷新都会随之改变

看完上述内容,你们掌握SpringBoot中怎么搭建Thymeleaf环境的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
网页题目:SpringBoot中怎么搭建Thymeleaf环境
文章来源:http://www.jxjierui.cn/article/psccdj.html


咨询
建站咨询
