Spring Boot 2 + Thymeleaf:表單字段綁定、表單提交處理

Spring Boot中Thymeleaf對錶單處理的一些用法:
(1)使用th:field屬性:進行表單字段綁定
(2)使用ids對象:通常用於lable配合radio或checkbox使用
(3)表單提交處理html

開發環境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8java

新建一個名稱爲demo的Spring Boot項目。
pom.xml 依賴項以下:web

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

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

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

1、使用th:field屬性spring

th:field屬性經常使用於表單字段綁定,除了自動生成id和name屬性,對不一樣的節點類型還會有不一樣的生成邏輯。
例如input還會再生成value屬性,textarea會自動設文本,select會自動選中相應的選項,若是是同個表單屬性,radio和checkbox的id會全局自動增加。
備註:
(1)使用th:field屬性時,若是html節點中已經存在相應屬性,則不會再另外生成。
(2)th:field屬性須要使用星號表達式*{...},即先使用th:object聲明表單對象,再使用th:field=*{...}對錶單域進行處理。瀏覽器

一、src/main/java/com/example/demo/User.javaapp

package com.example.demo;

public class User {
    String name;
    Integer sex;
    String[] MyColors;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public String[] getMyColors() {
        return MyColors;
    }
    public void setMyColors(String[] myColors) {
        MyColors = myColors;
    }
}

二、src/main/java/com/example/demo/FieldController.javaspring-boot

package com.example.demo;

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

import java.util.HashMap;
import java.util.Map;

@Controller
public class FieldController {
    @RequestMapping("/field")
    public String field(Model model){
        //設置用戶對象
        User user = new User();
        user.setName("小紅");
        user.setSex(0);
        model.addAttribute("user", user);
        //設置性別
        Map<String, Object> sexes = new HashMap<String, Object>();
        sexes.put("男", 1);
        sexes.put("女", 0);
        model.addAttribute("sexes", sexes);
        return "field";
    }
}

三、src/main/resources/templates/field.htmlpost

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用th:field屬性</title>
</head>
<body>
    <form th:object="${user}">
        <input type="text" th:field="*{name}" id="name1" />
        <input type="text" th:field="*{name}" />
        <input type="text" th:field="*{name}" />
        <textarea th:field="*{name}"></textarea>
        <textarea th:field="*{name}"></textarea>
        <select th:field="*{sex}">
            <option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
        </select>
        <select th:field="*{sex}">
            <option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
        </select>
        <input type="checkbox" th:field="*{name}" value="*{name}"/>
        <input type="checkbox" th:field="*{name}" value="*{name}"/>
        <input type="radio" th:field="*{name}" value="*{name}"/>
        <input type="radio" th:field="*{name}" value="*{name}"/>
    </form>
</body>
</html>

啓動服務後,瀏覽器訪問http://localhost:8080/field,網頁源代碼以下:ui

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用th:field屬性</title>
</head>
<body>
    <form>
        <input type="text" id="name1" name="name" value="小紅" />
        <input type="text" id="name" name="name" value="小紅" />
        <input type="text" id="name" name="name" value="小紅" />
        <textarea id="name" name="name">小紅</textarea>
        <textarea id="name" name="name">小紅</textarea>
        <select id="sex" name="sex">
            <option value="0" selected="selected"></option>
            <option value="1"></option>
        </select>
        <select id="sex" name="sex">
            <option value="0" selected="selected"></option>
            <option value="1"></option>
        </select>
        <input type="checkbox" value="*{name}" id="name1" name="name"/><input type="hidden" name="_name" value="on"/>
        <input type="checkbox" value="*{name}" id="name2" name="name"/><input type="hidden" name="_name" value="on"/>
        <input type="radio" value="*{name}" id="name3" name="name"/>
        <input type="radio" value="*{name}" id="name4" name="name"/>
    </form>
</body>
</html>

 

2、使用ids對象this

能夠使用ids對象的seq方法生成指定名稱的遞增id。
對於radio和checkbox自動生成的id,配合lable節點使用時,須要知道這個id,能夠使用ids對象的prev和next方法。

一、src/main/java/com/example/demo/IdsController.java

package com.example.demo;

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

@Controller
public class IdsController {
    @RequestMapping("/ids")
    public String ids(Model model){
        User user = new User();
        user.setName("小紅");
        user.setSex(0);
        model.addAttribute("user", user);
        return "ids";
    }
}

二、src/main/resources/templates/ids.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用ids對象</title>
</head>
<body>
    <form th:object="${user}">
        <input type="text" th:field="*{name}" th:id="${#ids.seq('tname')}" />
        <input type="text" th:field="*{name}" th:id="${#ids.seq('tname')}" />

        <input type="radio" th:field="*{name}" value="*{name}" th:id="${#ids.seq('rname')}"/>
        <input type="radio" th:field="*{name}" value="*{name}" th:id="${#ids.seq('rname')}"/>

        <input type="checkbox" th:field="*{name}" value="*{name}" th:id="${#ids.seq('cname')}" />
        <input type="checkbox" th:field="*{name}" value="*{name}" th:id="${#ids.seq('cname')}"/>

        <input type="radio" th:field="*{name}" value="*{name}" />
        <label th:for="${#ids.prev('name')}" th:text="單選A"></label>
        <input type="radio" th:field="*{name}" value="*{name}" />
        <label th:for="${#ids.prev('name')}" th:text="單選B"></label>

        <label th:for="${#ids.next('name')}" th:text="多選A"></label>
        <input type="checkbox" th:field="*{name}" value="*{name}" />
        <label th:for="${#ids.next('name')}" th:text="多選B"></label>
        <input type="checkbox" th:field="*{name}" value="*{name}" />
    </form>
</body>
</html>

啓動服務後,瀏覽器訪問http://localhost:8080/ids,網頁源代碼以下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用ids對象</title>
</head>
<body>
    <form>
        <input type="text" id="tname1" name="name" value="小紅" />
        <input type="text" id="tname2" name="name" value="小紅" />

        <input type="radio" value="*{name}" id="rname1" name="name"/>
        <input type="radio" value="*{name}" id="rname2" name="name"/>

        <input type="checkbox" value="*{name}" id="cname1" name="name" /><input type="hidden" name="_name" value="on"/>
        <input type="checkbox" value="*{name}" id="cname2" name="name"/><input type="hidden" name="_name" value="on"/>

        <input type="radio" value="*{name}" id="name1" name="name" />
        <label for="name1">單選A</label>
        <input type="radio" value="*{name}" id="name2" name="name" />
        <label for="name2">單選B</label>

        <label for="name3">多選A</label>
        <input type="checkbox" value="*{name}" id="name3" name="name" /><input type="hidden" name="_name" value="on"/>
        <label for="name4">多選B</label>
        <input type="checkbox" value="*{name}" id="name4" name="name" /><input type="hidden" name="_name" value="on"/>
    </form>
</body>
</html>

 

3、表單的提交處理

提交後,在控制器方法中使用@ModelAttribute映射表單對象。

一、src/main/java/com/example/demo/FormController.java

package com.example.demo;

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FormController {
    @RequestMapping("/form")
    public String form(Model model){
        setConstant(model);
        User user = new User();
        user.setName("小明");
        user.setSex(1);
        user.setMyColors(new String[]{"white", "black"});
        model.addAttribute("user", user);
        return "form";
    }

    @PostMapping("/submit")
    public String submit(@ModelAttribute User user, Model model){
        setConstant(model);
        model.addAttribute("user", user);
        System.out.println("姓名:" + user.getName());
        System.out.println("性別:" + (user.getSex().intValue() == 1 ? "男" : "女"));
        System.out.println("喜歡的顏色:" + Arrays.toString(user.getMyColors()));
        //return "redirect:/form";
        return "form";
    }

    //設置常量
    private void setConstant(Model model){
        Map<String, Object> sexes = new HashMap<String, Object>();
        sexes.put("男", 1);
        sexes.put("女", 0);
        model.addAttribute("sexes", sexes);
        String[] colors = new String[]{"red", "white", "black"};
        model.addAttribute("colors", colors);
    }
}

二、src/main/resources/templates/form.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表單的提交處理</title>
</head>
<body>
    <form method="post" th:action="@{/submit}" th:object="${user}">
       <table>
           <tr>
               <td>用戶名:</td>
               <td><input type="text" th:field="*{name}" /></td>
           </tr>
           <tr>
               <td>性別:</td>
               <td><select th:field="*{sex}">
                       <option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
                    </select>
               </td>
           </tr>
           <tr>
               <td>喜歡的顏色:</td>
               <td>
                   <span th:each="color : ${colors}">
                       <input type="checkbox"  th:field="*{myColors}" th:value="${color}" />
                       <label th:for="${#ids.prev('myColors')}" th:text="${color}"></label>
                   </span>
               </td>
           </tr>
           <tr>
               <td colspan="2">
                   <input type="submit" value="提交" />
               </td>
           </tr>

       </table>



    </form>
</body>
</html>

啓動服務後,瀏覽器訪問http://localhost:8080/from,頁面以下圖:

 

 網頁源代碼以下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表單的提交處理</title>
</head>
<body>
    <form method="post" action="/submit">
       <table>
           <tr>
               <td>用戶名:</td>
               <td><input type="text" id="name" name="name" value="小明" /></td>
           </tr>
           <tr>
               <td>性別:</td>
               <td><select id="sex" name="sex">
                       <option value="0"></option>
                       <option value="1" selected="selected"></option>
                    </select>
               </td>
           </tr>
           <tr>
               <td>喜歡的顏色:</td>
               <td>
                   <span>
                       <input type="checkbox"  value="red" id="myColors1" name="myColors" /><input type="hidden" name="_myColors" value="on"/>
                       <label for="myColors1">red</label>
                   </span><span>
                       <input type="checkbox"  value="white" id="myColors2" name="myColors" checked="checked" /><input type="hidden" name="_myColors" value="on"/>
                       <label for="myColors2">white</label>
                   </span><span>
                       <input type="checkbox"  value="black" id="myColors3" name="myColors" checked="checked" /><input type="hidden" name="_myColors" value="on"/>
                       <label for="myColors3">black</label>
                   </span>
               </td>
           </tr>
           <tr>
               <td colspan="2">
                   <input type="submit" value="提交" />
               </td>
           </tr>

       </table>



    </form>
</body>
</html>

點擊提交按鈕,IDEA控制檯輸出:

姓名:小明
性別:男
喜歡的顏色:[white, black]
相關文章
相關標籤/搜索