Home  >  Article  >  Java  >  Compare and contrast the usage differences between @RequestParam and @PathVariable

Compare and contrast the usage differences between @RequestParam and @PathVariable

巴扎黑
巴扎黑Original
2017-07-23 14:30:022248browse

In spring MVC, the function of both is to bind the value of the parameter in the request to the method parameter in the contorl. The difference is that the URL is written differently.

When using @RequestParam, the URL is like this: http://host:port/path?Parameter name = parameter value

When using @PathVariable, the URL is like this: http://host:port/path/Parameter value

For example:

[java] view plain copy
  1. @RequestMapping(value="/user",method = RequestMethod.GET)

  2. ##public @ResponseBody

  3. # User printUser(
  4. @RequestParam( value =

    "id", required = false, defaultValue = "0")

  5. ##int id) {
  6. # User user =

    new User();
  7. ## user = userService .getUserById(id);

  8. #@RequestMapping(value=

    "/user/{id:\\d+}",method = RequestMethod.GET)
  9. public
  10. @ResponseBody

  11. ## User printUser2(

    @PathVariable
  12. int id) {
  13. ## User user = new User();

  14. user = userService.getUserById(id);

  15. return user;
  16. The access paths for the above two methods are as follows:

The above is the detailed content of Compare and contrast the usage differences between @RequestParam and @PathVariable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn