最近在调试一个Spring Boot向Thymeleaf模板传参数的例子,但踩了很多坑,这里就把详细过程记录下来,以供大家参考。
先说下,这里遇到哪些坑呢?
1 我用的是IDEA社区版,这不支持JSP,我本来向传到JSP的,由于不支持,所以只能传到HTML。
2 HMML里,必须要引入Thymeleaf模板,否则无法从ModelAndView里接收到参数。
好,然后给出我搭建项目的步骤,先创建一个名为ModelAndViewDemo的Maven项目里,而在下表里,给出了重要文件的说明。
重要文件 | 说明 |
---|---|
pom.xml | 引入了该项目所用到的依赖包,尤其地,引入了Thymeleaf的依赖包 |
SpringBootApp.java | 启动类 |
Controller.java | 控制器类,在其中通过ModelAndView对象和前端Thymeleaf交互 |
Application.properties | 配置文件,其中包含了Thymeleaf的相关配置 |
hello.html | 包含Thymeleaf模板的前端页面文件,请注意它是在resources目录的templates目录里,这个目录结构需要和配置文件里的配置保持一致 |
第一步,在pom.xml里,包含本项目的依赖包,关键代码如下所示。其中,通过第6行到第9行的代码,引入了thymeleaf模板的依赖包。
1 <dependencies>
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter-web</artifactId>
5 </dependency>
6 <dependency>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter-thymeleaf</artifactId>
9 </dependency>
10 </dependencies>
第二步,编写启动类。
1 package prj;
2 import org.springframework.boot.SpringApplication;
3 import org.springframework.boot.autoconfigure.SpringBootApplication;
4 @SpringBootApplication
5 public class SpringBootApp {
6 public static void main(String[] args) {
7 SpringApplication.run(SpringBootApp.class, args);
8 }
9 }
第三步,编写控制器类,代码如下所示。
1 package prj.controller;
2 import org.springframework.web.bind.annotation.RequestMapping;
3 import org.springframework.web.bind.annotation.RestController;
4 import org.springframework.web.servlet.ModelAndView;
5 @RestController
6 public class Controller {
7 @RequestMapping("/welcome")
8 public ModelAndView welcome() {
9 ModelAndView modelAndView = new ModelAndView("hello");
10 modelAndView.getModel().put("name", "Tom");
11 return modelAndView;
12 }
13 }
在第8行的welcome方法里,先是在第9行创建了ModelAndView类型的对象,并通过构造函数,指定该对象里的视图为“hello”,随后通过第10行的代码,在该对象的Model里,以键值对的形式,添加了键是name值是Tom的数据。结合起来看,welcome方法将向hello视图返回一个键值对数据。
第四步,在application.properties里,编写thymeleaf模板的相关参数,具体代码如下。
1 #启用thymeleaf视图
2 spring.thymeleaf.enabled=true
3 #设置Content-Type值
4 spring.thymeleaf.content-type=text/html
5 ## 检查模板是否存在,然后再呈现
6 spring.thymeleaf.check-template-location=true
7 # 不启用缓存
8 spring.thymeleaf.cache=false
9 # 构建前缀
10 spring.thymeleaf.prefix=classpath:/templates/
11 # 构建后缀
12 spring.thymeleaf.suffix=.html
在对应的参数项前都有注释,大家可以自行阅读,不过这里有如下两大注意点。
第五步,需要编写包含thymeleaf模板的hello.html页面,代码如下所示。
1 <!DOCTYPE html>
2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <meta charset="UTF-8">
5 <title>welcome</title>
6 </head>
7 <body>
8 Welcome:<span th:text="${name}"></span>
9 </body>
10 </html>
其中在第2行,指定了第8行要用到的th标签的命名空间,这是来自于thymeleaf模板。
而在第8行里,通过th:text="
完成开发后启动该项目,并如控制器里welcome方法之前的@RequestMapping注解所示,在浏览器里输入http://localhost:8080/welcome,就能看到输出“Welcome:Tom“的字样。而从发起请求到展示数据,主要经历了如下的流程。