Spring @RequestParam vs @PathVariable Annotations – Spring @RequestParam与@PathVariable注解的对比

最后修改: 2020年 6月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll explore the differences between Spring’s @RequestParam and @PathVariable annotations.

在这个快速教程中,我们将探讨Spring的@RequestParam@PathVariable注释之间的区别。

@RequestParam and @PathVariable can both be used to extract values from the request URI, but they are a bit different.

@RequestParam@PathVariable都可以用来从请求URI中提取值,但它们有点不同。

2. Query Parameter vs URI Path

2.查询参数与URI路径

While @RequestParams extract values from the query string, @PathVariables extract values from the URI path:

@RequestParams从查询字符串中提取数值,@PathVariables从URI路径中提取数值

@GetMapping("/foos/{id}")
@ResponseBody
public String getFooById(@PathVariable String id) {
    return "ID: " + id;
}

Then we can map based on the path:

然后,我们可以根据路径进行映射。

http://localhost:8080/spring-mvc-basics/foos/abc
----
ID: abc

And for @RequestParam, it will be:

而对于@RequestParam,它将是。

@GetMapping("/foos")
@ResponseBody
public String getFooByIdUsingQueryParam(@RequestParam String id) {
    return "ID: " + id;
}

which would give us the same response, just a different URI:

这将给我们同样的响应,只是一个不同的URI。

http://localhost:8080/spring-mvc-basics/foos?id=abc
----
ID: abc

3. Encoded vs Exact Value

3.编码与精确值的关系

Because @PathVariable is extracting values from the URI path, it’s not encoded. On the other hand, @RequestParam is encoded.

因为@PathVariable是从URI路径中提取值,所以它没有被编码。另一方面,@RequestParam是编码的。

Using the previous example, ab+c will return as-is:

使用前面的例子,ab+c将返回原样。

http://localhost:8080/spring-mvc-basics/foos/ab+c
----
ID: ab+c

But for a @RequestParam request, the parameter is URL decoded:

但对于一个@RequestParam请求,参数被URL解码

http://localhost:8080/spring-mvc-basics/foos?id=ab+c
----
ID: ab c

4. Optional Values

4.可选价值

Both @RequestParam and @PathVariable can be optional.

@RequestParam@PathVariable都可以是可选的。

We can make @PathVariable optional by using the required attribute starting with Spring 4.3.3:

从Spring 4.3.3开始,我们可以通过使用required属性使@PathVariable成为可选项。

@GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})
@ResponseBody
public String getFooByOptionalId(@PathVariable(required = false) String id){
    return "ID: " + id;
}

Then we can do either:

那么我们可以做任何一个。

http://localhost:8080/spring-mvc-basics/myfoos/optional/abc
----
ID: abc

or:

或。

http://localhost:8080/spring-mvc-basics/myfoos/optional
----
ID: null

For @RequestParam, we can also use the required attribute.

对于@RequestParam,我们也可以使用required属性。

Note that we should be careful when making @PathVariable optional, to avoid conflicts in paths.

请注意,我们在使@PathVariable可选时应该小心,以避免路径中的冲突。

5. Conclusion

5.结论

In this article, we learned the differences between @RequestParam and @PathVariable.

在这篇文章中,我们了解了@RequestParam@PathVariable的区别。

The full source code for the examples can be found over on GitHub.

这些例子的完整源代码可以在GitHub上找到over