在spring boot 項(xiàng)目中使用thymeleaf模板,將后臺(tái)數(shù)據(jù)傳遞給前臺(tái)界面。
1、將后臺(tái)數(shù)據(jù)傳遞給前臺(tái)有很多種方式,可以將后臺(tái)要傳遞的數(shù)據(jù)轉(zhuǎn)換成json格式,去傳遞給前臺(tái),也可以通過(guò)model形式去傳遞出去,這篇博客主要是使用thymeleaf模板,將后臺(tái)數(shù)據(jù)傳遞給前臺(tái)。
2、首先要在spring boot 項(xiàng)目中添加如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3、這里后臺(tái)有關(guān)如何查詢數(shù)據(jù),得到數(shù)據(jù)的具體過(guò)程就不在多說(shuō)了,只是寫(xiě)將數(shù)據(jù)庫(kù)中查詢到的數(shù)據(jù)取出來(lái),放到model里面。這里就一個(gè)例子吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@RequestMapping ( "/" ) public String index(Model model){ Person single= new Person( "aa" , 11 ); List<Person> people = new ArrayList<Person>(); Person p1= new Person( "xx" , 22 ); Person p2= new Person( "dd" , 33 ); Person p3= new Person( "zz" , 44 ); people.add(p1); people.add(p2); people.add(p3); model.addAttribute( "singlePerson" ,single); model.addAttribute( "people" ,people); return "index" ; } |
4.前臺(tái)界面的寫(xiě)法,
<span th:text="${person.name}"></span> <span th:text="${person.age}"></span>
通過(guò)這樣的方法就可以取到放入model中的person的name和age了。
(注:前臺(tái)界面要添加上這個(gè)代碼:<html xmlns:th="http://www.thymeleleaf.org">)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/kuangwl/p/13381812.html