Only add the HTTP method required in the org.springframework.web.bind.annotation.RequestMapping
annotation through the method
element:
@RequestMapping(value = "/add/{id}/{name}/{author}/{price}",
method = RequestMethod.POST)
public Book addBook(@PathVariable int id, @PathVariable String name, @PathVariable String author,
@PathVariable long price) {
Book book = new Book();
book.setId(id);
book.setName(name);
book.setAuthor(author);
book.setPrice(price);
bookService.saveBook(book);
return book;
}
Optionally you can send the data in the body of the request and not in the URL:
@RequestMapping(value = "/add",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE
method = RequestMethod.POST)
public Book addBook(
@RequestParam(name = "id", required = false, defaultValue = "0") int id,
@RequestParam(name = "name", required = true) String name,
@RequestParam(name = "author", required = true) String author,
@RequestParam(name = "price", required = true) long price) {
Book book = new Book();
book.setId(id);
book.setName(name);
book.setAuthor(author);
book.setPrice(price);
bookService.saveBook(book);
return book;
}
Since version 4.3 of Spring it is possible to use the annotation org.springframework.web.bind.annotation.PostMapping
, which acts as a shortcut of @RequestMapping(method = RequestMethod.POST)
:
@PostMapping(value = "/add",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Book addBook(
@RequestParam(name = "id", required = false, defaultValue = "0") int id,
@RequestParam(name = "name", required = true) String name,
@RequestParam(name = "author", required = true) String author,
@RequestParam(name = "price", required = true) long price) {
Book book = new Book();
book.setId(id);
book.setName(name);
book.setAuthor(author);
book.setPrice(price);
bookService.saveBook(book);
return book;
}
Other notes that are shortcuts:
org.springframework.web.bind.annotation.PostMapping
org.springframework.web.bind.annotation.DeleteMapping
org.springframework.web.bind.annotation.GetMapping
org.springframework.web.bind.annotation.PutMapping
org.springframework.web.bind.annotation.PatchMapping