@RequestParam vs @PathVariable
In Spring MVC, the @RequestParam annotation is used to bind a request parameter to a method parameter. It is typically used to extract query parameters or form data from an HTTP request.
On the other hand, the @PathVariable annotation is used to bind a URI template variable to a method parameter. It is typically used to extract values from the path portion of a URI, such as the value of an ID in a RESTful API.
Here's an example of how you can use the @RequestParam and @PathVariable annotations in a Spring MVC controller:
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@RequestMapping("/search")
public String search(@RequestParam("q") String query) {
// search for users based on the query parameter
return "Search results for: " + query;
}
@RequestMapping("/{id}")
public String getById(@PathVariable("id") String id) {
// get user by id
return "User with ID " + id;
}
}This code defines a UserController with two request mapping methods: search and getById. The search method is mapped to the /search path and uses the @RequestParam annotation to bind the q request parameter to the query method parameter. The getById method is mapped to the /{id} path and uses the @PathVariable annotation to bind the id URI template variable to the id method parameter.
I hope this helps! Let me know if you have any questions.