@Validated注解

一. 在javaEE项目中经常要判断一些字段的格式是否正确。在以前基本上都是用if(啥啥 啥)else(啥啥啥) 。但是在知道@Validated之后就开始尝试用这个注解了。不但减轻代码量而 且代码更加的易读规整。

二. 下面就以简单例子来说明。

  1. Controller 层
@PostMapping("student")
@ApiOperation("学生注册")
public @ResponseBody
Map<String, Object> registerStudent(@RequestBody @Validated UserJsonBean user, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
    Map<String,Object> retMap;
    retMap=registerService.baseRegister(user,0,request);
    return retMap;

}

在要校验对象上加上@Validated注解

2.Bean层

(1)
public class UserJsonBean  extends User
(2)
public class User {
    @Id
    @Column(name="id",nullable = false)
    @GeneratedValue
   private Long id;
    @Email
    @Column(name = "user_email", nullable = false)
    private String userEmail;

3.测试

(1)传入数据

{
  "emailCode": 1234,
  "phoneCode": "1234",
  "picCode": "string",
  "userEmail": "zjut.wujinhuiqq.com",
  "userName": "wujinhui",
  "userPassword": "123456",
  "userPhone": "string"
}

(2)测试结果:

{
  "timestamp": "2018-05-25T10:19:59.898+0000",
  "status": 400,
  "error": "Bad Request",
  "errors": [
    {
      "codes": [
        "Email.userJsonBean.userEmail",
        "Email.userEmail",
        "Email.java.lang.String",
        "Email"
      ],
      "arguments": [
        {
          "codes": [
            "userJsonBean.userEmail",
            "userEmail"
          ],
          "arguments": null,
          "defaultMessage": "userEmail",
          "code": "userEmail"
        },
        [],
        {
          "defaultMessage": ".*",
          "arguments": null,
          "codes": [
            ".*"
          ]
        }
      ],
      "defaultMessage": "不是一个合法的电子邮件地址",
      "objectName": "userJsonBean",
      "field": "userEmail",
      "rejectedValue": "zjut.wujinhuiqq.com",
      "bindingFailure": false,
      "code": "Email"
    }
  ],
  "message": "Validation failed for object='userJsonBean'. Error count: 1",
  "path": "/register/student"
}

三.@Validated 相关注解