johnwick0831
johnwick0831

Reputation: 948

Can someone please clarify @RequestBody

I have done some reading and research on @RequestBody but I am still unable to wrap my thick head around the purpose of it.

Given the scenario:

From what I read in a similar question answered, how does that apply in this scenario? What does it mean by converting A to B and then B to A so that users can see it as a JSON object. I'm so confused!

Upvotes: 0

Views: 483

Answers (1)

codependent
codependent

Reputation: 24442

From the javadoc:

Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

In your example there is no point in using @RequestBody. You want to get the author name corresponding to a book

You send GET/books/myBook/author

The Controller would be

@RestController
public class BooksRestController{

    @RequestMapping(value="/books/{bookName}/author", method=RequestMethod.GET)
    public Map<String,String> getAuthor(@PathVariable bookName){
        ...
        Map<String,String> author = new HashMap<String,String>();
        author.put("author",bookAuthor);
        return author;
    }
}

The response would be {"author":"whoever"}.

Now imagine that you want to create a book. That's when you would use @RequestBody, to automatically parse the JSON sent in the HTTP POST body into a Book object.

Request: POST /books - Body {"name" : "SomeBook", "author":"SomeAuthor"}

Controller:

@RestController
public class BooksRestController{

    @RequestMapping(value="/books", method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public Book createBook(@RequestBody Book book){
        ...
        //save book
        book = bookService.save(book);
        return book;
        //Book is going to be serialized as JSON because of the implicit 
        //@ResponseBody annotation from @RestController
    }

Book.class:

public class Book{
    private String name;
    private String author;
    //getters setters;
}

Upvotes: 4

Related Questions