'Trying to throw 400 when there is an extra key value pair which is not defined in the @RequestBody bean

@Data
@Getter @Setter
public class S3UploadRequest {
    private String fileName;
    private String applicationName;
    private String content;

}

 @PostMapping(value = "/writeFileToS3", produces = {MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody
    ServiceResponse validateAndUploadFileToS3(@RequestBody S3UploadRequest requestParam,
                                              HttpServletRequest request,
                                              HttpServletResponse httpServletResponse){
/*method body*/
}

Now when I pass below json request:

{
"fileName" : "abc",
"applicationName" : "abc,
"content" : "abc"
}

This works fine.

Now, when I add an extra key,value pair in the request

 {
    "fileName" : "abc",
    "applicationName" : "abc,
    "content" : "abc",
    "extraKey" : "extraValue"
    }

Now I want to throw 400 because there isnt any "extraKey" field defined in the bean but it neglects the additional key value pair which is "extraKey":"extraValue" and ends the request with 200OK.

How can I achieve this?

Yes, I can do this by considering rawtype as input like

  public String method(@RequestBody Map<String,String> request){
    }

Now I'll iterate Map and compare every key and throw Validation Exceptio with 400 status code for the keys which are not present in the map.

But how can I achieve the same thing using @RequestBody with Bean?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source