hibernate-validator提供了类似长度校验等。用法如下
1、pojo类上注解:
@Length(max = 11, min = 11, message = "手机号的长度必须是11位.")
private String phone;
@Email(message = "邮箱不符合规则!")
private String email;
2、在controller中接收参数时使用@Valid和BindingResult
@RequestMapping(value = "doRegister", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> doRegister(@Valid User user, BindingResult bindingResult) {}
3、判断:
if (bindingResult.hasErrors()) {
map.put("status", "400");
List<String> msgs = new ArrayList<>();
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError : allErrors) {
String msg = objectError.getDefaultMessage();
msgs.add(msg);
}
map.put("data", "参数错误!" + StringUtils.join(msgs, "|"));
return map;