Spring Boot 2 + Thymeleaf:服務器端表單驗證

表單驗證分爲前端驗證和服務器端驗證。
服務器端驗證方面,Java提供了主要用於數據驗證的JSR 303規範,而Hibernate Validator實現了JSR 303規範。
項目依賴加入spring-boot-starter-thymeleaf時,默認就會加入Hibernate Validator的依賴。html

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

新建一個名稱爲demo的Spring Boot項目。java

一、pom.xmlweb

       <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>

二、src/main/java/com/example/demo/User.javaspring

package com.example.demo;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

public class User {
    @NotBlank(message = "用戶名不能爲空")
    String name;
    @Length(min = 11, max = 11, message = "手機號長度必須11位")
    String phone;
    @Size(min = 6, max = 20, message = "密碼長度6-20位")
    String password;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

三、src/main/java/com/example/demo/FormController.java瀏覽器

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

@Controller
public class FormController {
    @RequestMapping("/{form}")
    public String form(@PathVariable String form, @ModelAttribute User user){
        return form;
    }

    @PostMapping("/submit")
    public String submit(@Valid User user, BindingResult result){
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getDefaultMessage());
            }
            return "form";
        }
        //業務邏輯處理
        return "form";
    }

}

四、src/main/resources/templates/form.html服務器

前端經過#fields對象輸出錯誤信息有2種方式,1種是在每一個字段後面輸出,另1種是所有在一塊兒輸出。app

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>表單的提交處理</title>
    <style>
        .fieldError{color: red}
    </style>
</head>
<body>
    <form method="post" th:action="@{/submit}" th:object="${user}">
       <table>
           <tr>
               <td>用戶名:</td>
               <td><input type="text" th:field="*{name}" />
                   <span class="fieldError" th:if="${#fields.hasErrors('*{name}')}" th:errors="*{name}"></span>
               </td>
           </tr>
           <tr>
               <td>手機號:</td>
               <td><input type="text" th:field="*{phone}" />
                   <span class="fieldError" th:if="${#fields.hasErrors('*{phone}')}" th:errors="*{phone}"></span>
               </td>
           </tr>
           <tr>
               <td>密碼:</td>
               <td><input type="text" th:field="*{password}" />
                   <span class="fieldError" th:if="${#fields.hasErrors('*{password}')}" th:errors="*{password}"></span>
               </td>
           </tr>
           <tr>
               <td colspan="2">
                   <input type="submit" value="提交" />
                   <div th:each="err : ${#fields.errors('*')}">
                       <span th:text="${err}" class="fieldError"></span>
                   </div>
               </td>
           </tr>
       </table>
    </form>
</body>
</html>

啓動服務後,瀏覽器訪問http://localhost:8080/form,點擊提交按鈕,結果以下:spring-boot

相關文章
相關標籤/搜索