基于Spring MVC的Rest服务验证请求正文

问题描述 投票:0回答:1

我的应用程序中有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得到验证,但是在UserDto的情况下T字段内的字段未经过验证。

所以我需要知道实现这一目标的方法或代码片段。

我已经尝试在配置中配置hibernate验证器bean,但在该场景中没有任何帮助

spring validation spring-mvc hibernate-validator spring-restcontroller
1个回答
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
  */
}
© www.soinside.com 2019 - 2024. All rights reserved.