What is the purpose of the @RequestParam annotation in Spring MVC?
A) To bind HTTP request parameters to method arguments
B) To bind a URI template variable to a method parameter
C) To handle exceptions in a Spring MVC application
D) To inject dependencies into a controller
Answer:
A) To bind HTTP request parameters to method arguments
Explanation:
The @RequestParam annotation in Spring MVC is used to bind HTTP request parameters to method arguments. It allows you to capture values from query strings or form data and pass them as arguments to the handler method.
For example:
@Controller
public class MyController {
@GetMapping("/search")
public String search(@RequestParam("q") String query, Model model) {
model.addAttribute("query", query);
return "searchResults";
}
}
In this example, the @RequestParam("q") annotation binds the value of the q parameter in the query string to the query method parameter. When a request is made to /search?q=Spring, the query parameter will be set to “Spring”, and the search method will return the “searchResults” view with the query attribute set.
The @RequestParam annotation is versatile and can be used for both required and optional parameters, with the ability to specify default values.