参数幂等性校验失败_SpringBoot服务端数据校验

1.数据校验

1.1pojo(省略get,set方法)

public class User implements Serializable{
//	@NotBlank: 判断字符串是否为 null 或者是空串(去掉首尾空格)。
//	@NotEmpty: 判断字符串是否 null 或者是空串。
//	@Length: 判断字符的长度(最大或者最小)
//	@Min: 判断数值最小值
//	@Max: 判断数值最大值
//	@Email: 判断邮箱是否合法
	@Min(0)
	private int id;
	@NotBlank(message="用户名不能为空")//非空校验
	@Length(min=3,max=6)
	private String name;
	@NotBlank
	private String pwd;
}

校验规则表:

4a254d5779ac809904018be0a958a60a.png

ea0e4e758def4c653d288944d12881ea.png

1.2controller

@Controller
public class UserController {

	@RequestMapping("/user/save")
	/*
	*@Valid 开启对 Users 对象的数据校验
	*BindingResult:封装了校验的结果
        *如果校验失败会在容器中生成一个当前校验对象的副本,
        *key的名称会使用该对象的驼峰式的命名规则来作为 key。 
	*/
	public String saveUser(@Valid User user,BindingResult result){
		if(result.hasErrors()){
			return "add";
		}
		System.out.println(user);
		return "ok";
	}
	@RequestMapping("/{page}")
	public String showPage(@PathVariable String page,User user){
		return page;
	}	
}

注意:对象名必须要写user,如需改变需要使用@ModelAttribute注解

	/**
         *
         * 如果想为传递的对象更改名称,可以使用@ModelAttribute("aa")这表示当
           前传递的对象的 key 为 aa。
         * 那么我们在页面中获取该对象的 key 也需要修改为 aa
         * @param user
         * @return
         */
      public String saveUser(@ModelAttribute("aa")@Valid User user,BindingResult result){
		if(result.hasErrors()){
			return "add";
		}
		System.out.println(user);
		return "ok";
	}

1.3html页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
	<form th:action="@{/user/save}" method="post" >
		<!-- 此user并不是model传过来的,而是校验失败,BindingResult会生成一个bean,名字为类名小写 -->
		用户姓名:<input type="text" name="id" th:errors = "${user.id}" /><br /> 
		用户密码:<input type="password" name="name" th:errors = "${user.name}" /><br />
		用户密码:<input type="password" name="name" th:errors = "${user.pwd}" /><br />
		<input type="submit" value="OK" />
	</form>
</body>
</html>

1.4常见异常

26cf151bd9634363c5a924a1ea9ba854.png

27f77193a18e082a78ebd48a12c3808f.png

原因:

解决异常的方式。可以在跳转页面的方法中注入一个 Uesrs 对象。

注意:由于 springmvc 会将该对象放入到 Model 中传递。key 的名称会使用 该对象的驼峰式的命名规则来作为 key。 参数的变量名需要与对象的名称相同。将首字母小写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值