spring校验

spring校验

  • pojo加注解
  • Controller加注解
  • 常用校验

pojo加注解

public class User {
	private Long id;
	//NotBlank用作字符串 NotNull可以用数字 NotEmpty用map
	@NotBlank(message="用户名不能为空")
	private String name;

	@NotBlank(message="密码不能为空")
	private String password;

	private String salt;
}

Controller加注解

//@Valid和BindingResult bindingResult是处理校验的
	   @ResponseBody
	@RequestMapping(value = "sysUser", method = RequestMethod.POST)
	public String add(@Valid User user,BindingResult bindingResult, long roleId, ServletResponse response) {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		//非空校验
		if(bindingResult.hasErrors()) {
			httpResponse.setStatus(500);
			List list = bindingResult.getFieldErrors();
			return list.get(0).getDefaultMessage();
		}
	}

常用校验

spring校验_第1张图片
spring校验_第2张图片

你可能感兴趣的:(springboot)