Spring MVC中使用Thymeleaf模板引擎

时间:2022-11-17 16:40:24

来源https://zhuanlan.zhihu.com/p/20934954

Ricky发表在天码营

新一代Java模板引擎Thymeleaf一定让你惊叹于Thymeleaf的强大,但是真正在Web应用结合Web特性使用模板引擎,还需要进行一定的配置和学习。

Thymeleaf于Spring集成

Thymeleaf除了基本的模板引擎,还提供了一套Spring集成技术使得在Spring MVC中能够使用它完全替代JSP作为模板引擎,它的功能特性如下:

  • Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
  • 模板中的表达式支持Spring表达式语言(Spring EL)
  • 表单支持,并兼容Spring MVC的数据绑定与验证机制
  • 国际化支持

如果你还不了解Thymeleaf,请一定先阅读新一代Java模板引擎Thymeleaf

配置TemplateEngine

<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>

<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>

上述配置的TemplateEngine从/WEB-INF/templates/目录中读取文件夹,默认的后缀名是.html,所以在渲染模板时只需要提供模板的名字(例如index.html可以省略为index),TemplateEngine就可以找到对应的模板内容。

为了能够方便的让@Controller进行渲染(类似JSP),例如:

@Controller
public class IndexController {

@RequestMapping("/")
public String index() {
return "index";
}
}

还需要配置Spring中的ViewResolver:

<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>

@Controller

Spring MVC中@Controller用于处理HTTP请求并返回内容到浏览器。在渲染模板前,ThymeleafViewResolver会自动把当前的Model加入到Context中:

@Controller
public class IndexController {

@RequestMapping("/")
public String index(Model model) {
model.addAttribute("list", Lists.newArrayList("a", "b", "c"));
return "index";
}
}

这样在index模板中可以访问表达式${list}得到`["a", "b", "c"]的值。

表单

Command对象用来在Spring MVC中绑定表单与后端对象,Thymeleaf提供的th:object属性可以用来指定Command对象:

<form action="#" th:action="@{/}" th:object="${command}" method="post">
<label>Title</label>
<input type="text" th:field="*{title}"/>
<label>Text</label>
<input type="text" th:field="*{text}"/>
<br/>
<input type="submit" value="Add"/>
</form>

<div>
<div th:each="entry: ${entries}">
<h2 th:text="${entry.title}">Title</h2>
<p th:text="${entry.text}">Text</p>
</div>
</div>

指定th:object属性后,各个<input>中还需要指定th:field,这与后端绑定对象的字段名要一致。在@Controller中的方法如下:

@RequestMapping(value = "/", method = GET)
public String index(Model model) {
model.addAttribute("entries", getAll());
model.addAttribute("command", new Entry());
return "index";
}

@RequestMapping(value = "/", method = POST)
public String post(Entry entry) {
add(entry.title, entry.text);

return "redirect:/";
}

post()方法的参数Entry entry是根据HTTP请求的输入title和text值自动进行的绑定。

在Spring Boot中使用Thymeleaf

Spring Boot能够简化Spring应用配置、加速开发,对于Thymeleaf模板引擎提供了内置支持,在Spring Boot应用中只需要引入:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

所有Thymeleaf的相关依赖都会被加载到类路径中,更重要的是,上文中所有TemplateEngine,ThymeleafViewResolver等bean都在应用启动后被自动实例化,默认情况下模板的目录位于src/main/resources/templates/文件夹中,所以开发者只需要在这个文件夹中添加模板文件即可。

如果需要改变一些配置,可以在application.properties中写入:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added

改变这些配置的值,也就会自动改变Spring Boot帮助我们实例化的bean的配置。