Springboot Thymeleaf數(shù)據(jù)迭代實現(xiàn)過程
在模板文件中,可以使用“${{...}}”表達式進行數(shù)據(jù)轉(zhuǎn)換,Thymeleaf會使用配置好的數(shù)據(jù)轉(zhuǎn)換類,來實現(xiàn)轉(zhuǎn)換。
例如一個User對象,簡單起見假設有姓名和年齡兩個字段,對象的toString()方法拼接所有字段,使用“${user}”會調(diào)用對象的toString()方法得到所有字段,如果在模板中只想得到姓名,可以使用自定義數(shù)據(jù)轉(zhuǎn)換類實現(xiàn)。
在Sprint Boot中,實現(xiàn)過程:
(1)先實現(xiàn)自定義的Formatter類,并根據(jù)具體業(yè)務實現(xiàn)數(shù)據(jù)轉(zhuǎn)換邏輯;
(2)將自定義的Formatter類注冊到容器中;
(3)在模板中使用“${{...}}”表達式。
開發(fā)環(huán)境: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
實現(xiàn)自定義的Formatter類
package com.example.demo;
import org.springframework.format.Formatter;
import java.text.ParseException;
import java.util.Locale;
public class UserFormatter implements Formatter<User> {
/**
* 字符串轉(zhuǎn)換為對象
*/
@Override
public User parse(String s, Locale locale) throws ParseException {
return null;
}
/**
* 對象轉(zhuǎn)換為字符串
*/
@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;
@Configuration
public 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;
@Controller
public 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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
用vbscript實現(xiàn)修改屏幕保護的等待時間長度
用vbscript實現(xiàn)修改屏幕保護的等待時間長度...2007-04-04
vbscript獲取文件的創(chuàng)建時間、最后修改時間和最后訪問時間的方法
這篇文章主要介紹了vbscript獲取文件的創(chuàng)建時間、最后修改時間和最后訪問時間的方法,本文通過FileSystemObject對象實現(xiàn),需要的朋友可以參考下2014-08-08

