1

I'm trying to validate JSON (passed by a client as a request body) before it is converted into a model in Controller method.

If validation passes then return nothing, let the process continue as it was (spring boot to convert JSON into a model marked as @RequestBody). Throw error in case validation fails (everit-org/json-schema).

I tried to two way:

  1. Implement HandlerMethodArgumentResolver, but resolveArgument() doesn't give request body details as it is already read and stored in ContentCachingRequestWrapper.

    NOTE: inputStream in ContentCachingRequestWrapper doesn't have any request body details.

  2. Using spring Interceptor. But this doesn't help me to find request body type passed in the request. As JSON schema is different for each request.

Any other approaches I can try with?

Community
  • 1
  • 1
Vinni
  • 569
  • 1
  • 8
  • 18

1 Answers1

0

I cannot add a comment ... so ...

What kind of validation do you need? If you only want to validate the fields like length of a string or range of a number and so on. I recommend you use @Validated on controller mehtod parameter, and model:

    @NotNull
    @Size(min = 32, max = 32)
    private String id;

controller:

@PatchMapping
public Object update(@RequestBody @Validated User user, Errors errors) {
    ...
}

If there is something wrong, errors.hasErrors() will return true.

edit:

OK, I did some tests, in a filter :

    HttpServletRequest httpServletRequest = (HttpServletRequest)request;
    ServletInputStream inputStream = httpServletRequest.getInputStream();
    byte[] a = new byte[1024];
    inputStream.read(a);
    System.out.println(IOUtils.toString(a));

I got a json string (a piece of request body) :

    {"template":"5AF78355A4F0D58E03CE9F55AFA850F8","bd":"" ...
Zhili
  • 141
  • 11
  • I hav JSON schema. Would like to validate request JSON against it.Dont need @Validate approach..Thanks.. – Vinni May 28 '18 at 05:55
  • Yes.There are some suggestions to use filters. I remember it vaguely,not sure if I tried it or not. Please update in case filters worked for you. – Vinni May 28 '18 at 06:02
  • Would be great if you could share a working sample project in GitHub.As I could see many others seeking for a solution. – Vinni May 28 '18 at 06:58
  • ... it's company's project, there are not much things that related with these code ... – Zhili May 28 '18 at 07:38