Right way to (1) review the data verification --Spring Boot learning

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_40914991/article/details/86648365

I. Introduction

  Use springboot very long time, have been in several small projects, recently we have time to sum up, did not talk much, this introduction about springboot data validation, I remember when the original contact with springboot do not know they can do it The following code shows directly

Second, the code shows

Controller

/**
 * @author AlgerFan
 * @date Created in 2019/1/25 16
 * @Description SpringBoot 表单数据校验
 */
@Controller
public class UsersController {
	/**
	 * 必须传递user这个对象,要不然会报错
	 * @param users
	 */
	@RequestMapping("/addUser")
	public String showPage(@ModelAttribute("user") Users users){
		return "add";
	}
	
	/**
	 * 完成用户添加
	 * @Valid 开启对Users对象的数据校验
	 * BindingResult:封装了校验的结果
	 */
	@RequestMapping("/save")
	public String saveUser(@ModelAttribute("aa") @Valid Users users, BindingResult result){
		if(result.hasErrors()){
			return "add";
		}
		System.out.println(users);
		return "ok";
	}
}

User

public class Users {
	@NotBlank(message="用户名不能为空") //非空校验
	@Length(min=2,max=6,message="最小长度为2位,最大长度为6位")
	private String name;
	@NotEmpty
	private String password;
	@Min(value=15)
	private Integer age;
	@Email
	private String email;

	//此处省略Getter和Setter以及toString方法,也可用Data注解

}

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	  xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
	<form th:action="@{/save}" method="post">
		用户姓名:<input type="text" name="name"/><span th:errors="${user.name}" style="color: red; "></span><br/>
		用户密码:<input type="password" name="password" /><span th:errors="${user.password}" style="color: red; "></span><br/>
		用户年龄:<input type="text" name="age" /><span th:errors="${user.age}" style="color: red; "></span><br/>
		用户邮箱:<input type="text" name="email" /><span th:errors="${user.email}" style="color: red; "></span><br/>
		<input type="submit" value="OK"/>
	</form>
</body>
</html>

Third, the test results presentation

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_40914991/article/details/86648365