“尝试使用Spring验证请求体时,”bean类[java.lang.String]的“无效属性'ssn”

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

我有一个springboot应用程序,其中一个休息控制器坐在上面。用户通过/test访问控制器并传入json,如下所示:

{"ssn":"123456789"}

我想通过至少确保没有像这样传入空ssn来验证输入:

{"ssn":""}

所以这是我的控制器:

@RequestMapping(
            value = "/test",
            method = RequestMethod.POST,
            consumes = "application/json",
            produces = "application/json")
@ResponseBody
public JsonNode getStuff(@RequestHeader HttpHeaders header,
                                 @RequestBody String payload,
                                 BindingResult bindingResult) {
    validator.validate(payload, bindingResult);
    if(bindingResult.hasErrors()) {
        throw new InvalidRequestException("The request is incorrect", bindingResult);
    }
    /* doing other stuff */
}

这是我的验证器:

@Component
public class RequestValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }

    @Override
    public void validate(Object target, Errors errors) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode ssn = null;
        try {
            ssn = mapper.readTree((String) target);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(ssn.path("ssn").isMissingNode() || ssn.path("ssn").asText().isEmpty()) {
            errors.rejectValue("ssn", "Missing ssn", new Object[]{"'ssn'"}, "Must provide a valid ssn.");
        }
    }
}

我试着用postman测试这个,我一直收到这个错误:

HTTP Status 500 - Invalid property 'ssn' of bean class [java.lang.String]: Bean property 'ssn' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

究竟是什么问题?我不明白它与吸气剂和制定者有什么关系。

编辑1:请求的有效负载的值

{"ssn":""}
java validation spring-boot bean-validation spring-web
1个回答
1
投票

默认情况下,Spring Boot配置Json解析器,因此将传递您传递给控制器​​的任何Json。 Spring期望一个名为'ssn'的属性绑定请求值。

这意味着您应该创建一个这样的模型对象:

public class Data {
    String ssn;

}

并使用它绑定您的请求正文,如下所示:

@RequestMapping(
        value = "/test",
        method = RequestMethod.POST,
        consumes = "application/json",
        produces = "application/json")
@ResponseBody
public JsonNode getStuff(@RequestHeader HttpHeaders header,
                                 @RequestBody Data payload,
                                 BindingResult bindingResult) {
    validator.validate(payload, bindingResult);
    if(bindingResult.hasErrors()) {
        throw new InvalidRequestException("The request is incorrect", bindingResult);
    }
    /* doing other stuff */
}

您还需要调整Validator以使用此新Data对象。

© www.soinside.com 2019 - 2024. All rights reserved.