2

I have an @RestController that allows to POST with a few @RequestParam arguments and 2 @RequestPart arguments to be able to create an object in the service layer that needs some input + 2 files like this:

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity createBook(@RequestParam("authorId") UUID authorId,
                                           @RequestParam("pages") int pages,                                               
                                           @RequestParam("rating") BookRating rating,
                                           @RequestPart("file") MultipartFile file,
                                           @RequestPart("file2") MultipartFile file2) {

I would like to create an object that encapsulates all those parameters, so I can do something like:

public ResponseEntity createBook( CreateBookParameters params ) {

How do I do this? What annotation do I need to use in my controller? Are there any annotations I need to use in the CreateBookParameters or is this a simple POJO ?

Do I need to change anything to the request I do if I do these changes (I am testing with "form-data" setting in Postman)?

1
  • I'm not sure whether you can roll the multipart into it, but you can collect all the @RequestParams into an @ModelAttribute CreateBookParameters. Commented Jan 11, 2016 at 16:13

2 Answers 2

3

Have you tried Spring's default reflection behavior? Try this:

public class CreateBookParameters {
    private UUID authorId;
    private int pages;
    private BookRating rating;
    private MultipartFile file;
    private MultipartFile file2;

    // add getters & setters for each
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity createBook(CreateBookParameters p) {
  // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

That works! I tried about any possible annotation, but I never tried without any annotation at all. Seems I can annotate with @Valid in the controller method and use javax.validation.constraints.NotNull in the CreateBookParameters object and Spring will validate it properly.
0

Another option is to take a look at the @RequestBody annotation and see if you can use that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.