使用SpringMVC数据验证框架validation做数据校验

在springMVC里为我们提供了基于注解的数据检验框架,框架会将所有的错误提示保存在集合里(BindingResult),我们拿到这个集合将里面的错误信息取出来提示给前台。

使得我们不需要再自己去写一堆的数据合法性检验的代码,让数据检验层代码变得优雅。接下来看如何使用:

在接收数据里的PO里面加上数据检验的注解:

 

	@NotBlank(message="名称不能为空")
	private String name;
	@NotBlank(message="类型不能为空")
  private String type;
	@DecimalMin(value="0",message="采购价钱必须大于等于0")
  private float buyPrice;    //采购价钱
	@DecimalMin(value="0",message="市场价钱必须大于等于0")
  private float marketPrice;  //市场价钱
	private String thingsDesc;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public float getBuyPrice() {
		return buyPrice;
	}
	public void setBuyPrice(float buyPrice) {
		this.buyPrice = buyPrice;
	}
	public float getMarketPrice() {
		return marketPrice;
	}
	public void setMarketPrice(float marketPrice) {
		this.marketPrice = marketPrice;
	}
	public String getThingsDesc() {
		return thingsDesc;
	}
	public void setThingsDesc(String thingsDesc) {
		this.thingsDesc = thingsDesc;
	}


接收错误信息并将错误信息提取出来

 

@Validated注解的作用是启用数据检验功能。

BindingResult里面保存了所有的error信息,getAllErrors()是获取所有的错误信息;

getDefaultMessage()方法会提取出我们在PO里加在字段上面的注解的message里的值。

 

 @RequestMapping("/addorUpdate")
	@ResponseBody
	public ReturnData add(@Validated AddOrUpdateThings things,BindingResult  bindingResult){
		ReturnData data=new ReturnData();
		if(bindingResult.hasErrors()) { 
			StringBuffer errorInfo=new StringBuffer();
			List<ObjectError> errors = bindingResult.getAllErrors(); 
			if(errors!=null&&errors.size()>0){
				for (ObjectError objectError : errors) {
					errorInfo.append(objectError.getDefaultMessage());
					errorInfo.append("\n");
				}
			}
			data.setCode("500");
			data.setMsg(errorInfo.toString());
			return data;
        }  
		//此处业务逻辑代码 ……
		data.success(null);
		return data;
	}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李秀才

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值