What is the difference between @GetMapping and @PostMapping annotations in Spring MVC?
A) @GetMapping is used for HTTP GET requests, and @PostMapping is used for HTTP POST requests
B) @GetMapping is used for database queries, and @PostMapping is used for data insertions
C) @GetMapping is used to map URLs, and @PostMapping is used to handle form submissions
D) @GetMapping is for read operations, and @PostMapping is for write operations
Answer:
A) @GetMapping is used for HTTP GET requests, and @PostMapping is used for HTTP POST requests
Explanation:
The @GetMapping
and @PostMapping
annotations in Spring MVC are specialized versions of the @RequestMapping
annotation, used to map HTTP GET and POST requests, respectively. These annotations are part of the Spring 4.3+ release and provide a more concise way to handle specific HTTP methods.
For example:
@Controller
public class MyController {
@GetMapping("/form")
public String showForm() {
return "form";
}
@PostMapping("/submit")
public String submitForm() {
return "result";
}
}
In this example, the showForm()
method is mapped to handle GET requests to /form
, and the submitForm()
method is mapped to handle POST requests to /submit
. The @GetMapping
annotation is typically used for retrieving data or displaying forms, while the @PostMapping
annotation is used for submitting form data or creating new resources. These annotations make it easier to manage different HTTP methods in a clean and readable way.