spring boot整合模版引擎thymeleaf

动态资源:spring boot 默认不支持jsp。

                spring boot推荐使用thymeleaf

网页=模版+数据

引入thymeleaf:

https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/#using-boot-starter

thymeleaf官网:

https://www.thymeleaf.org/

thymeleaf 3.0的文档:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

找到spring-boot-starter-thymeleaf 点击后面的pom,将依赖拷贝到项目的pom.xml中

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

	<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
	</dependency>

	<dependency>
	<groupId>org.thymeleaf.extras</groupId>
	<artifactId>thymeleaf-extras-java8time</artifactId>
	</dependency>


 使用自动装配:

                   查找两个类:

                   1、XXXAutoConfigarution

                   2、XXXProperties

    所以,我们要自动装配Thymeleaf,我们需要想找两个类ThymeleafAutoConfiguration和ThymeleafProperties类。

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

public static final String DEFAULT_PREFIX = "classpath:/templates/";

public static final String DEFAULT_SUFFIX = ".html";

...

}

通过 prefix+属性名来配置,可知prefix = "spring.thymeleaf".

由源码可知,thymeleaf的文件应该放在classpath:/templates/中后缀为html

实例:

    在controller中添加请求响应:

@RequestMapping("welcomethymeleaf")
public String welcomethymeleaf(Map<String, Object> map) {
map.put("word", "hello thymeleaf!!!");
return "thymeleaf";
}

在templates中创建thymeleaf.html:

<body>
<p th:text="${word}">Welcome to thymeleafword!</p>
</body>

输出为:

hello thymeleaf!!!

解析:

<p th:text="${word}">Welcome to thymeleafword!</p> 先从${word}中取值,如果有,则直接显示${word}的值,如果没有则显示Welcome to thymeleafword!

所以th就是替换原有html的值。

如:

    <p id="pid" class="pclass" th:text="${word}">Welcome to thymeleafword!</p>
    <p th:id="${word}" th:class="${word}" th:text="${word}">Welcome to thymeleafword!</p>

查看最终输出到浏览器的源码为:

     <p id="pid" class="pclass">hello thymeleaf!!!</p>
     <p id="hello thymeleaf!!!" class="hello thymeleaf!!!">hello thymeleaf!!!</p>

th:each 的使用实例:

controller:

@RequestMapping("thymeleafeach")
public String thymeleafeach(Map<String, Object> map) {
    ArrayList users=new ArrayList<User>();
    users.add(new User("feifei","feifei","广东.深圳.龙华"));
    users.add(new User("yoyo1","yoyo","湖南.长沙.天心"));
    map.put("users", users);
    return "thymeleaf-each";
}

html:

<body>
<table>
<th:block th:each="user : ${users}">
<tr>
<td th:text="${user.login}">...</td>
<td th:text="${user.name}">...</td>
</tr>
<tr>
<td colspan="2" th:text="${user.address}">...</td>
</tr>
</th:block>
</table>
</body>

猜你喜欢

转载自blog.csdn.net/zyfzhangyafei/article/details/89764382