According to law, each method has its objective:
post to insert records,
get to get/display records,
put to modify records,
delete to remove records
I made the following code, which adds a new book to the database, so I should use the post method, but I did it with the get method, I want to convert it to a post method, how to do it?
@RequestMapping(value = "/add/{id}/{name}/{author}/{price}")
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;
}
Just add the required HTTP method in the annotation
org.springframework.web.bind.annotation.RequestMapping
via the elementmethod
:Optionally you can send the data in the body of the request and not in the URL:
Since version 4.3 of Spring it is possible to use the annotation
org.springframework.web.bind.annotation.PostMapping
, which acts as a shortcut to@RequestMapping(method = RequestMethod.POST)
:Other annotations that are shortcuts:
It is correct, however for GET according to the HTTP protocol (which is the one REST is based on) its data entry is through parameters as in your GET method, but in POST it is through a body:
Example:
Controller:
to create a record is also resolved with 201 instead of 200, in the HTTP status