1. 程式人生 > >springboot伺服器校驗規則

springboot伺服器校驗規則

一、依賴

<!--web啟動器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf啟動器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、controller

public class User {
    @NotEmpty//不去首尾空格
    @Length(min = 2,max = 6)
    private String name;
    @NotBlank(message = "密碼不能為空") //去掉首尾空格
    private String password;
    @Min(value = 20)
    @Max(value = 99)
    private Integer age;

    @Email
    private String email;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [name="+name+",passwor="+password+",age="+age;
    }
}
@Controller
public class UserController {

    @RequestMapping(value = "/addUser")
    public String showPage(@ModelAttribute("aa") User user){
        return "add";
    }

    @RequestMapping(value = "/save")
    public String saveUser(@ModelAttribute("aa") @Valid User user, BindingResult result){
        if (result.hasErrors()){
            return "add";
        }
       System.out.println(user);
        return "ok";
    }
}

三、頁面

add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form th:action="@{/save}" method="post">
        姓名:<input type="text" name="name"/><font color="red" th:errors="${aa.name}"></font><br/>
        密碼:<input type="password" name="password"/><font color="red" th:errors="${aa.password}"></font><br/>
        年齡:<input type="text" name="age"/><font color="red" th:errors="${aa.age}"></font><br/>
        郵箱:<input type="text" name="email"/><font color="red" th:errors="${aa.email}"></font><br/>
        提交:<input type="submit" value="ok"/><br/>
    </form>
</body>
</html>

ok.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    ok
</body>
</html>