渲染html页面,在动态Html实现上Spring Boot提供了多种模板引擎的默认配置支持;所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供的默认配置的模板引擎主要有以下几种:
-
Thymeleaf
-
FreeMarker
-
Velocity
-
Groovy
-
Mustache
Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置。
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
这里重点说下常用的thymeleaf模板:
Thymeleaf
Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于ApacheLicense 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。
Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。
以上转自 http://blog.51cto.com/wyait/1966573
下面开始使用Thymeleaf,首先导包
<dependency>
<!--Spring Boot 模板引擎thymeleaf依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.yml中配置
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
mode: HTML5
测试controller
@RequestMapping("/toShow")
public ModelAndView test(ModelAndView mv) {
mv.setViewName("/toShow");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
测试html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link th:href="@{/css/1.css}" rel="stylesheet"/>
</head>
<body>
<p th:text="'Hello111111, ' + ${title}" /><br/>
<script th:src="@{/js/jquery/1.11.0/jquery.js}"></script>
<script>
$(function(){
alert("page load finish.");
});
</script>
</body>
</html>
访问url