1

I have a springboot application with a rest controller sitting up top. The user access the controller through /test and passes in a json like so:

{"ssn":"123456789"}

I want to validate the input by at least making sure there's not an empty ssn being passed in like so:

{"ssn":""}

So here's my controller:

@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 */
}

And here's my validator:

@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.");
        }
    }
}

I tried testing this with postman and I keep getting this error:

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?

What exactly is the problem here? I don't understand what it's talking about in relation to getters and setters.

Edit 1: The value of the payload as requested

{"ssn":""}
4

1 回答 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 */
}

您还需要调整您的验证器以使用这个新的数据对象。

于 2016-03-25T13:34:43.500 回答