導入Thymeleaf、正確設置URL的輸入、相應請求、參數傳遞

1、導入Thymeleaf:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、輸入請求(URL):

@RequestMapping(value = {"/","/index","/vv"})
/* 輸入以下任意一種查看網頁:
http://127.0.0.1:端口號 
http://127.0.0.1:端口號/index
http://127.0.0.1:端口號/vv 
*/
@RequestMapping(value = {"/fff/{Id1}/{Id2}"})
/*Id1和Id2是任意輸入值,並可自動記錄下來供使用*/

3、響應請求:

@RequestMapping(path = {"/","/index","/dj"})
@ResponseBody
public String index(){
    return "hello";//返回hello字符串
}

這裏寫圖片描述

這裏寫圖片描述

4、參數傳遞:

//在這兒value跟path是等同的
@RequestMapping(value = {"/profile/{groupId}/{userId}"})
@ResponseBody
public String profile(@PathVariable("groupId") String groupId,@PathVariable("userId") int userId,@RequestParam(value="type",defaultValue = "1") int type,@RequestParam(value="key",defaultValue = "dj") String key){
    return String.format("GID{%s},UID{%d},TYPE{%d},KEY{%s}",groupId,userId,type,key);
    }

這裏寫圖片描述

//IndexController.java
@Controller
public class IndexController {
@RequestMapping(value = {"/vv"})
public String news(Model model){
    model.addAttribute("value1","DJ");

    List<String> colorss = Arrays.asList(new String[]{"RED","BLUE","GREEN"});
    model.addAttribute("colors",colorss);

    Map<String,String> map = new HashMap<String,String>();
        for(int i = 0 ;i < 4 ;i++ ){
            map.put(String.valueOf(i),String.valueOf(i*i));
        }
    model.addAttribute("maps",map);

    return "hello";//新建了一個hello模板,顯示的是模板的內容
    }
}
//hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Getting Started: Serving Web Content</title>
</head>
<body>
<p>
    <div th:text="'welcome!'+${value1}+'.'"></div>
</p>
<p>
<div th:each="color : ${colors}">
    <span th:text="${color}"></span>
</div>
</p>
<p>
<div th:each="mapEntry : ${maps}">
    <span th:text="${mapEntry.key}"></span> =
    <span th:text="${mapEntry.value}"></span>
</div>
</p>
</body>
</html>

1、< p>表示一個大的段落
2、< br>表示換行,另起一行
3、< div>表示是一個塊級元素,它的內容自動開始一個新行
4、Thymeleaf是一種針對HTML/XML定製的模板語言(當然它可以被擴展),它通過標籤中的th:text屬性來填充該標籤的一段內容。
5、獲取變量的值:${ }
6、遍歷:th:each=”color : ${colors}”
7、字符串拼接:th:text=“‘welcome!’+${value1}+’.’”

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章