spring校验
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<FieldError> list = bindingResult.getFieldErrors();
return list.get(0).getDefaultMessage();
}
}
常用校验