zoukankan      html  css  js  c++  java
  • 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>
    

      

  • 相关阅读:
    斯坦福机器学习视频之线性回归习题详解
    linuxc程序设计之passwd与shadow解析(转)
    DeepLearning之MLP解析
    The Linux Environment之getopt_long()
    插入排序
    堆排序
    归并排序
    快速排序
    CyclicBarrier与CountDownLatch的区别
    判断是否是平衡二叉树(左子树与右子树高度不大于1)
  • 原文地址:https://www.cnblogs.com/xzmiyx/p/9890746.html
Copyright © 2011-2022 走看看