Home > front end >  Multiple objects in @RequestBody possible?
Multiple objects in @RequestBody possible?

Time:12-08

Is it possible to pass multiple objects to the @RequestBody from Spring Boot like this?

public void storeSecretKey(@RequestBody final KeyStoreRequest keyStoreRequest, @RequestBody final SecretKeyDTO secretKeyDTO) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException { 

or do i have to write like a wrapper class that combines both of the objects that i need data from?

CodePudding user response:

@RequestBody will be used to read the body of the http request which is just 1.

Then inside the body of the http request there can be several objects contained, but all should belong to the same body of http request.

If we talk about json then the http body request would be in the form

{
   object1: { },
   object2: { },
   ...
}

So you can have only 1 @RequestBody which could then contain several nested objects like object1, object2, ...etc

In your case it would be

@Getter
@Setter
public class WrapperRequestExample {  
     private KeyStoreRequest keyStoreRequest;
     private SecretKeyDTO secretKeyDTO;
}

and your controller will then be

 public void storeSecretKey(@RequestBody WrapperRequestExample wrapperRequestExample) {
        wrapperRequestExample.getKeyStoreRequest(); //access keyStoreRequest
        wrapperRequestExample.getSecretKeyDTO(); //access secretKeyDTO
    }

CodePudding user response:

You can add multiple body parameters to your path operation function, even though a request can only have a single body.

  • Related