Spring Boot支持多種視圖技術,內置如下:
FreeMarker
Groovy
Thymeleaf
Mustache
在這一節中我爲大家講解Spring中使用模板技術。
簡單介紹一下FreeMarker 模板技術。
1.首先在pom.xml文件中引入依賴
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
2.SpringBoot中模板都在resource/templates文件下面,我們創建一個簡單的test.ftl模板:
簡單的模板
<html>
<body>
${use.name}
</p>
${use.age}
</body>
</html>
3.創建Controller類
package com.unitop.Contorller;
import com.unitop.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Helloword {
//這是一個歡迎頁面
@RequestMapping("/index")
public String index( int i){
return "HeloWord SpringBoot"+i;
}
//返回的MOdelAndView視圖
@RequestMapping("/modelview")
public ModelAndView show(User user){
ModelAndView modelAndView = new ModelAndView();
User user1 =new User();//放入一個對象
user1.setAge(user.getAge());
user1.setName(user.getName());
modelAndView.addObject("use",user1);
modelAndView.setViewName("/test"); //映射頁面模板
return modelAndView;
}
}
4.User對象實體類
package com.unitop.entity;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
5.在瀏覽器裏面訪問http://127.0.0.1:8080/modelview?name=yantianpeng&age=12
6.在講解一下頁面返回的是list集合的時候頁面的接收效果
先創建一個list.ftl模板
代碼如下:
<html>
<body>
<#list list as use >
<tr>
姓名: <td>${use.name}</td>
年齡:<td>${use.age}</td>
</tr>
</#list>
</body>
</html>
7.在上一步的基礎上我們創建有個list裏面包含了兩個或者多個對象
創建一個Controller 在裏面添加一個showList方法:
@RequestMapping("/modelviewList")
public ModelAndView showList(){
ModelAndView modelAndView =new ModelAndView();
User user1 =new User();//創建對象
user1.setName("yantianpeng");
user1.setAge(26);
User user2 =new User();
user2.setAge(25);
user2.setName("馬慶");
List<User> list =new ArrayList<User>();//創建list
list.add(user1);
list.add(user2);
modelAndView.addObject("list",list);//吧list放入到modelView裏面
modelAndView.setViewName("/test");
return modelAndView;
}
- 在頁面我們訪問127.0.0.1:8080/modelviewList
注意在創建的模板中我們需要了解FreeMarker語法。