Spring Boot Learn how to get started with form validation
- 2020-10-23 20:07:28
- OfStack
preface
Form validation is the process of verifying that the data submitted by the user is valid, such as whether it is empty, whether the password length is greater than 6 digits, whether it is pure digits, and so on. How does spring boot help us with form validation? Without further ado, let's take a look at the details.
Suppose there is such a registration interface:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>hello spring boot</title>
</head>
<body>
<form action="/doRegister" method="post">
<p> Name: <input type="text" name="username"/>
</p>
<p> Password: <input type="text" name="password"/>
</p>
<p><button> submit </button></p>
</form>
</body>
</html>
Need to verify the submitted username and password. Whether it is empty or not, and some other questions. What do we need to do?
First we need an entity class: User class to store the data submitted by the form:
public class User {
private int id;
@NotEmpty(message=" The user name cannot be empty ")
private String username;
@NotEmpty(message=" The password cannot be empty ")
@Length(min=6, message=" Password length must not be less than 6 position ")
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Use @NotEmpty, @Length, etc., and add the value of message to indicate what message will be if it doesn't match.
Next, write the Controller class: validate the data using the @Valid annotation, and get the results using BindingResult.
@Controller
public class FormController {
@RequestMapping(value="/register", method=RequestMethod.GET)
public String register() {
return "register";
}
@RequestMapping(value = "/doRegister", method = RequestMethod.POST)
public @ResponseBody User doRegister(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getDefaultMessage());
}
return null;
}
System.out.println(" registered ..");
return user;
}
}
This completes a simple form validation.
In addition to @NotEmpty, @Length, there are many other annotations:
conclusion