Springboot数据校验

SpringBoot中使用了Hibernate-validate校验框架

1.在实体类中添加校验规则

校验规则:

@NotBlank: 判断字符串是否为null或者是空串(去掉首尾空格)。
@NotEmpty: 判断字符串是否null或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法

例:

public class User {
	@NotBlank(message="用户名不能为空")//非空校验
	@Length(min=2,max=6,message="名字长度最小为两位,最大为六位")
	private String name;
	@NotBlank(message="年龄不能为空")
	@Min(value=10)
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public User(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "user [name=" + name + ", age=" + age + "]";
	}
	public User() {
		
	}
	
}

2.在 Controller 中开启校验

	@RequestMapping("/save")
	public String save(@Valid User user,BindingResult result) {
		if(result.hasErrors()) {
			return "add";
		}
		return "ok";
		
	}

  说明:@Valid 开启对 Users 对象的数据校验,BindingResult:封装了校验的结果

3.页面获取错误提示信息

	<form th:action="@{/save}" method="post">
		用户姓名:<input type="text" name="name" /><font color="red" th:errors="${user.name}"></font><br /> 
		用户年龄:<input type="text" name="age" /><font color="red" th:errors="${user.age}"></font><br /> 
			<input type="submit" value="OK" />
	</form>

  

posted @ 2018-11-01 17:53  梦里不觉秋已深  Views(925)  Comments(0Edit  收藏  举报