Springboot Thymeleaf数据迭代实现过程
在模板文件中,可以使用“${
{
...}
}
”表达式进行数据转换,Thymeleaf会使用配置好的数据转换类,来实现转换。
例如一个User对象,简单起见假设有姓名和年龄两个字段,对象的toString()方法拼接所有字段,使用“${ user} ”会调用对象的toString()方法得到所有字段,如果在模板中只想得到姓名,可以使用自定义数据转换类实现。
在SPRint Boot中,实现过程:
(1)先实现自定义的Formatter类,并根据具体业务实现数据转换逻辑;
(2)将自定义的Formatter类注册到容器中;
(3)在模板中使用“${ { ...} } ”表达式。
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
新建一个名称为demo的Spring Boot项目。
1、pom.XMl
加入Thymeleaf依赖
dePEndency> groupId> org.springframework.boot/groupId> artifactId> spring-boot-starter-thymeleaf/artifactId> /dependency>
2、src/main/java/com/example/demo/User.java
package com.example.demo; public class User { String name; Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @override public String toString() { return "User{ " + "name='" + name + '\'' + ", age=" + age + '} '; } }
3、src/main/java/com/example/demo/UserFormatter.java
实现自定义的Formatter类
package com.example.demo; import org.springframework.format.Formatter; import java.text.ParseException; import java.util.Locale; public class UserFormatter implements FormatterUser> { /** * 字符串转换为对象 */ @Override public User parse(String s, Locale locale) throws ParseException { return null; } /** * 对象转换为字符串 */ @Override public String print(User user, Locale locale) { return "name:" + user.getName(); } }
4、src/main/java/com/example/demo/Myconfig.java
将自定义的Formatter类注册到容器中
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configurationpublic class MyConfig { @Bean public UserFormatter userFormatter(){ return new UserFormatter(); } }
5、src/main/java/com/example/demo/testController.java
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controllerpublic class TestController { @RequestMapping("/") public String test(Model model){ User user = new User(); user.setName("lc"); user.setAge(30); model.addAttribute("user", user); return "test"; } }
6、src/main/resources/templates/test.htML
div th:text="${
user}
">
/div>
div th:text="${
{
user}
}
">
/div>
浏览器访问:http://localhost:8080
页面输出:
User{
name='lc', age=30}
name:lc
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:- 浅析SpringBoot中使用thymeleaf找不到.HTML文件的原因
- SpringBoot引入Thymeleaf的实现方法
- springboot如何使用thymeleaf模板访问html页面
- IDEA+maven+SpringBoot+JPA+Thymeleaf实现Crud及分页
- springboot用thymeleaf模板的paginate分页完整代码
- Springboot Thymeleaf实现HTML属性设置
- SpringBoot2.x 集成 Thymeleaf的详细教程
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Springboot Thymeleaf数据迭代实现过程
本文地址: https://pptw.com/jishu/609541.html