【问题标题】:Spring MVC Based Rest Services Validations for request body请求正文的基于 Spring MVC 的 Rest 服务验证
【发布时间】:2018-03-01 08:37:13
【问题描述】:

我的应用程序中有 Rest Controller,其代码如下所示:-

@RestController
@RequestMapping("/api/v1/user")
public class UserRestControllerV1 {

    @PostMapping("")
    public Response registerUser(@RequestBody @Valid final Request<UserDto> request,
                             final HttpServletRequest httpServletRequest,
                             BindingResult result){
    Response response = new Response(request);

    if(result.hasErrors()){
        response.setData(new String("Error"));
    }else {
        response.setData(new String("Test"));
    }
    return response;
}

请求类:-

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
    @JsonProperty(value = "co-relation-id")
    private String coRelationID;

    @NotNull(message = "The request body should be present")
    private T data;

    /*
     ..... various other fields
     Getters / Setters
    */
}

UserDto 类:-

public class UserDto {

    @NotNull(message = "The username should not be null")
    private String username;

    @NotNull(message = "The password should not be null")
    @JsonIgnore
    private String password;

    /*
     ..... various other fields
     Getters / Setters
    */    
}

问题:我的验证存在问题。请求类中的字段 private T data 得到验证,但 T 中的字段 - 在这种情况下 UserDto 没有得到验证。

所以我需要知道实现这个的方法或代码sn-p。

我尝试在配置中配置休眠验证器 bean,但在场景中没有帮助

【问题讨论】:

  • @Valid 放在private T data;
  • 谢谢,但如果我也想对数据字段进行验证检查怎么办?

标签: spring validation spring-mvc hibernate-validator spring-restcontroller


【解决方案1】:

@Valid 约束将指示 Bean Validator 深入研究其应用属性的类型并验证在那里找到的所有约束。

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
  @JsonProperty(value = "co-relation-id")
  private String coRelationID;

  //@NotNull(message = "The request body should be present")
  @Valid
  private T data;

  /*
   ..... various other fields
   Getters / Setters
  */
}

【讨论】:

  • 谢谢,但如果我也想对数据字段进行验证检查怎么办?
猜你喜欢
  • 2011-08-16
  • 2015-04-19
  • 2016-04-24
  • 2012-03-09
  • 2013-04-14
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2013-05-08
相关资源
最近更新 更多