springboot整合視圖層之Thymeleaf

Thymeleaf中有本身的表達式,和本身的語法,能夠把數據取出來後再進行判斷,遍歷等操做,另外它還封裝了strings,dates....對象,能夠利用這些對象對已有的數據進行簡單的邏輯處理;html

1.pom.xmljava

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.RELEASE</version>
  </parent>
  <groupId>com.mr.li</groupId>
  <artifactId>springboot_005</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <!-- 修改jdk版本 -->
  <properties>
       <java.version>1.7</java.version>
       <!-- 將thymeleaf的版本升級一下,好處是:不會限制自動生成的html中編碼標籤結束沒有結束符的錯誤 -->
       <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
       <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
  </properties>
  
  <dependencies>
      <!-- springBoot引入web啓動器 -->
          <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- springBoot引入thymeleaf視圖模板啓動器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  </dependencies>
</project>

2.啓動類web

package com.mr.li;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

3.MyController:各個方法的演示,方法的返回值都是對應的html名稱spring

package com.mr.li.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mr.li.pojo.User;

@Controller
public class MyController {

    /**
     * 使用thymeleaf獲取字符串:str是html的名字。
     * 將字符串添加到model屬性中,而model對象是springboot封裝過的,在這裏用於HTML中獲取。
     * @param model
     * @return
     */
    @RequestMapping("/strs")
    public String show1(Model model) {
        model.addAttribute("str", "heLLLlo world");
        return "str";
    }
    
    /**
     * 演示:在html中遍歷取出list中的內容
     * @param model
     * @return
     */
    @RequestMapping("/lists")
    public String show2(Model model) {
        List<User> list = new ArrayList<User>();
        list.add(new User(1, "小明", 15));
        list.add(new User(2, "小剛", 16));
        list.add(new User(3, "小麗", 14));
        model.addAttribute("list", list);
        return "list";
    }
    
    /**
     * 演示map:在html中取出map操做
     * @param model
     * @return
     */
    @RequestMapping("/maps")
    public String show3(Model model) {
        Map<String, User> map = new HashMap<String, User>();
        map.put("user1", new User(1, "張三", 15));
        map.put("user2", new User(2, "李四", 16));
        map.put("user3", new User(3, "王五", 17));
        model.addAttribute("map", map);
        return "map";
    }
    
    /**
     * 演示使用thymeleaf在html中操做date類型
     * @param model
     * @return
     */
    @RequestMapping("/dates")
    public String show4(Model model) {
        model.addAttribute("date", new Date());
        return "date";
    }
    
    /**
     * 演示做用域:在html中使用做用域
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/scopes")
    public String show5(HttpServletRequest request, Model model) {
        request.setAttribute("req", "my is request!!!");
        HttpSession session = request.getSession();
        session.setAttribute("session" , "my is httpsession");
        ServletContext context = request.getSession().getServletContext();
        context.setAttribute("application", "my is application!!!");
        return "scope";
    }
    /**
     * 演示在html判斷數據
     * @param model
     * @return
     */
    @RequestMapping("/decides")
    public String show6(Model model) {
        model.addAttribute("id", 2);
        model.addAttribute("sex", "男");
        return "decide";
    }
}

4.實體類,便於生成數據源,方便演示apache

package com.mr.li.pojo;

public class User {

    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
}

5.date.html 演示日期操做瀏覽器

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用Thymeleaf演示Date類型</title>
</head>
<body>
    <!-- date值是controller中model對象的屬性key名稱 -->
    1.自動解析輸出當前日期格式,爲瀏覽器默認格式:
    <span th:text="${#dates.format(date)}"></span>
    <hr/>
    2.自定義解析輸出當前日期格式yyy/MM/dd:
    <span th:text="${#dates.format(date, 'yyy/MM/dd')}"></span>
    <hr/>
    3.輸出當前年:
    <span th:text="${#dates.year(date)}"></span>
    <hr/>
    4.輸出當前月:
    <span th:text="${#dates.month(date)}"></span>
    <hr/>
    5.輸出當前日:
    <span th:text="${#dates.day(date)}"></span>
    <hr/>
</body>
</html>

訪問url: http://localhost:8080/datesspringboot

6.decide.html 用Thymeleaf演示判斷服務器

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用Thymeleaf演示if、switch判斷操做</title>
</head>
<body>
    <span th:if = "${sex} == '男'">
        此人性別:男
    </span>
    <span th:if = "${sex} == '女'">
        此人性別:女
    </span>
    <div th:switch="${id}">
        <span th:case="1">此人id爲:1</span>
        <span th:case="2">此人id爲:2</span>
        <span th:case="3">此人id爲:3</span>
    </div>
</body>
</html>

url: http://localhost:8080/decidesrestful

7.list.html list處理數據演示session

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用Thymeleaf演示List類型</title>
</head>
<body>
        <table border="1">
        <tr>
            <th>ID</th>
            <th>名稱</th>
            <th>年齡</th>
            <th>索引</th>
            <th>計數</th>
            <th>集合大小</th>
            <th>計數是否爲偶數</th>
            <th>計數是否爲奇數</th>
            <th>當前是否爲集合中的第一個元素</th>
            <th>當前是否爲集合中最後一個元素</th>
        </tr>
        <!-- u:是當前遍歷的對象,var:是Thymeleaf幫咱們封裝的當前對象 -->
        <tr th:each="u,var : ${list}">
            <td th:text="${u.id}"></td>
            <td th:text="${u.name}"></td>
            <td th:text="${u.age}"></td>
            <td th:text="${var.index}"></td>
            <td th:text="${var.count}"></td>
            <td th:text="${var.size}"></td>
            <td th:text="${var.even}"></td>
            <td th:text="${var.odd}"></td>
            <td th:text="${var.first}"></td>
            <td th:text="${var.last}"></td>
        </tr>
    </table>
</body>
</html>

url : http://localhost:8080/lists

8.map.html map處理數據演示

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用Thymeleaf演示Map類型</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>名稱</th>
            <th>年齡</th>
        </tr>
        <!--遍歷map方式一 -->
        <!-- <tr th:each="maps : ${map}">
            <td th:each="user : ${maps}" th:text="${user.value.id}"></td>
            <td th:each="user : ${maps}" th:text="${user.value.name}"></td>
            <td th:each="user : ${maps}" th:text="${user.value.age}"></td>
        </tr> -->
        <!-- 遍歷map方式二:拿出map而後循環會拿出他的對象,輸出每一個對象,value爲關鍵字 -->
        <tr th:each="user : ${map}">
            <td th:text="${user.value.id}"></td>
            <td th:text="${user.value.name}"></td>
            <td th:text="${user.value.age}"></td>
        </tr>
    </table>
</body>
</html>

url: http://localhost:8080/maps

9.str.html string類型處理數據演示

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用Thymeleaf演示String類型</title>
</head>
<body>
    演示輸出:
    <span th:text=" ${str}"></span>
    <hr/>
    1.檢查此字符串是否爲空:
    <span th:text="${#strings.isEmpty(str)}"></span>
    <hr/>
    2.檢查此str字符串送是否包含「h」:
    <span th:text="${#strings.contains(str,'h')}"></span>
    <hr/>
    3.檢查str中的第一個字符是否爲「b」:
    <span th:text="${#strings.startsWith(str,'b')}"></span>
    <hr/>
    4.檢查str中最後一個字符是否爲「s」:
    <span th:text="${#strings.endsWith(str,'s')}"></span>
    <hr/>
    5.輸出str的長度:
    <span th:text="${#strings.length(str)}"></span>
    <hr/>
    6.截取str中某段字符的內容,包頭不包尾,若只有一個值則今後值日後直到結束:
    <span th:text="${#strings.substring(str,3,5)}"></span>
    <hr/>
    7.輸出此字符「o」的索引值:
    <span th:text="${#strings.indexOf(str,'o')}"></span>
    <hr/>
    8.將str全部字符轉爲大寫:
    <span th:text="${#strings.toUpperCase(str)}"></span>
    <hr/>
    9.將str全部字符轉爲小寫:
    <span th:text="${#strings.toLowerCase(str)}"></span>
    <hr/>
</body>
</html>

url: http://localhost:8080/strs

10.scope.html 做用域演示

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>使用Thymeleaf演示Request、HttpSession、Application(ServletContext)做用域類型</title>
</head>
<body>
    <!-- httpServletRequest對象是Thymeleaf提供的,方法也是,都不能錯,req是controller中賦值時的key -->
    Request做用域的值獲取,賦值在controller中:<span th:text="${#httpServletRequest.getAttribute('req')}"></span>
    <hr/>
    <!-- 第一個session是Thymeleaf提供的,第二個session是controller中賦值的key -->
    Session做用域獲取值,賦值在controller中:<span th:text="${session.session}"></span>
    <hr/>
    <!-- 第一個application是Thymeleaf提供的,第二個application是controller中賦值的key -->
    Application做用域獲取值,賦值在controller中:<span th:text="${application.application}"></span>
</body>
</html>

url: http://localhost:8080/scopes

項目結構:

關於url:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf-URL</title>
</head>
<body>
    <a th:href="@{http://www.baidu.com}">絕對路徑</a><br/>
    <a href="http://www.baidu.com">絕對路徑2</a>
    <hr/>
        <!-- 此時回去找名爲show的這個controller  -->
    <a th:href="@{/show}">相對路徑</a>
    <hr/>
    <a th:href="@{~/project2/resourcename}">相對於服務器的根</a>
    <hr/>
    <a th:href="@{/show(id=1,name=zhagnsan)}">相對路徑-傳參</a>
    <hr/>
    <a th:href="@{/path/{id}/show(id=1,name=zhagnsan)}">相對路徑-傳參-restful</a>
</body>
</html>

以上就是thymeleaf的簡單應用

相關文章
相關標籤/搜索