Spring Boot - Valid Form表單參數驗證
本文介紹使用
@Valid
優雅的進行Form表單參數校驗,避免大量的if(){...}
語句…
主要依賴
lombok插件主要爲了簡化代碼,自行視情況添加使用。
thymeleaf主要爲了頁面測試
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
創建實體類
創建一個Person
實體類:
@Data
public class Person {
@NotNull
@Size(min = 4, max = 16, message = "用戶名須在4-16位之間")
private String userName;
@NotNull
@Min(value = 18, message = "年齡最小18歲")
private Integer age;
}
@NotNull
用來標示字段非空;@Size(min = 4, max = 16, message = "用戶名須在4-16位之間")
用來限定字符長度, 這個表示字符長度在4-16之間, message用於校驗失敗時的提示信息;@Min(value = 18, message = "年齡最小18歲")
表示最小值時18, 不允許小於18;
創建Controller
新建一個Controller用於測試
@Controller
public class DemoController {
@GetMapping("/")
public String formPage(Person person){
return "form";
}
@PostMapping("/")
public String checkParams(@Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "success";
}
}
@Valid
用於收集屬性進行參數校驗;BindingResult
可以進行測試檢索驗證錯誤,返回驗證結果信息;
創建HTML頁面
新建一個HTML頁面(form.html)用於表單提交
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Params Valid Demo</title>
</head>
<body>
<form action="#" th:action="@{/}" th:object="${person}" method="post">
<table>
<tr>
<td>UserName:</td>
<td><input type="text" th:field="*{userName}" th:autocomplete="off"/></td>
<td th:if="${#fields.hasErrors('userName')}" th:errors="*{userName}">UserName Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" th:autocomplete="off"/></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
創建一個成功頁面(success.html),用於校驗通過跳轉:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>SUCCESS.</h3>
</body>
</html>
運行並測試
運行啓動類:
@SpringBootApplication
public class BootValidApplication {
public static void main(String[] args) {
SpringApplication.run(BootValidApplication.class, args);
}
}
-
啓動後,打開表單頁,輸入不合參數並提交:
-
輸入正確的參數提交:
完整代碼
Github | 碼雲 |