SpringBoot(十):thymeleaf + JSR303实现表单验证

一、Person类

package com.jms.pojo;

import lombok.Data;

import javax.validation.constraints.*;

@Data
public class Person {

    @NotBlank(message = "姓名不能为空")
    private String name;
    @Max(value = 100, message = "年龄不能超过100")
    @Min(0)
    private String age;
    private String phone;
    private String email;

}

二、Controller

package com.jms.controller;

import com.jms.pojo.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Controller
public class PersonController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("person", new Person());
        return "index";
    }

    @PostMapping("/")
    public String getPerson(@Valid Person person, Errors errors) {
        if (errors.hasErrors()) return "index";
        else return "person";
    }
}

三、thymeleaf页面

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>主页面</title>
</head>
<body>
<form method="post" th:action="@{/}" th:object="${person}">
    <div>
        <input type="text" th:field="*{name}">
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">错误提示</span>
    </div>
    <div>
        <input type="text" th:field="*{age}">
        <span th:if="${#fields.hasErrors('age')}"
              th:errors="*{age}">
        </span>
    </div>
    <div>
        <input type="text" th:field="*{phone}">
        <span th:if="${#fields.hasErrors('phone')}"
              th:errors="*{phone}">
        </span>
    </div>
    <div>
        <input type="text" th:field="*{email}">
        <span th:if="${#fields.hasErrors('email')}"
              th:errors="*{email}">
        </span>
    </div>
    <input type="submit" value="提交">
</form>
</body>

</html>

person.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>person</title>
</head>
<body>
  <P>没有错误</P>
</form>
</body>
</html>

四、测试

 

 没有错误后成功跳转person.html

 

(本文仅作个人学习记录用,如有纰漏敬请指正)

posted @ 2023-03-06 20:49  谁知道水烫不烫  阅读(76)  评论(0编辑  收藏  举报