Spring boot專案使用thymeleaf模板過程詳解
阿新 • • 發佈:2020-07-31
在spring boot 專案中使用thymeleaf模板,將後臺資料傳遞給前臺介面。
1、將後臺資料傳遞給前臺有很多種方式,可以將後臺要傳遞的資料轉換成json格式,去傳遞給前臺,也可以通過model形式去傳遞出去,這篇部落格主要是使用thymeleaf模板,將後臺資料傳遞給前臺。
2、首先要在spring boot 專案中新增如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
3、這裡後臺有關如何查詢資料,得到資料的具體過程就不在多說了,只是寫將資料庫中查詢到的資料取出來,放到model裡面。這裡就一個例子吧。
@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.前臺介面的寫法,
<span th:text="${person.name}"></span> <span th:text="${person.age}"></span>
通過這樣的方法就可以取到放入model中的person的name和age了。
(注:前臺介面要新增上這個程式碼:<html xmlns:th="http://www.thymeleleaf.org">)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。