标签:thymeleafword spring Welcome boot thymeleaf public
动态资源:spring boot 默认不支持jsp。
spring boot推荐使用thymeleaf
网页=模版+数据
引入thymeleaf:
https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/#using-boot-starter
thymeleaf官网:
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>
标签:thymeleafword,spring,Welcome,boot,thymeleaf,public 来源: https://blog.csdn.net/zyfzhangyafei/article/details/89764382
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。