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;
}