问题描述
@RequestParam
和 @PathVariable
在处理特殊字符时有什么区别?
What is the difference between @RequestParam
and @PathVariable
while handling special characters?
+
被 @RequestParam
接受为空格.
在@PathVariable
的情况下,+
被接受为+
.
In the case of @PathVariable
, +
was accepted as +
.
推荐答案
@PathVariable
是从URI中获取一些占位符(Spring称之为URI模板)— 参见 Spring 参考章节 16.3.2.2 URI 模板模式@RequestParam
也是从 URI 中获取一个参数——见 Spring 参考章节 16.3.3.3 使用@RequestParam 将请求参数绑定到方法参数@PathVariable
is to obtain some placeholder from the URI (Spring call it an URI Template)— see Spring Reference Chapter 16.3.2.2 URI Template Patterns@RequestParam
is to obtain a parameter from the URI as well — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParam
如果 URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
获取到用户 1234 在 2013 年 12 月 5 日的发票,则控制器方法看起来像:
If the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
此外,请求参数可以是可选的,从 Spring 4.3.3 路径变量开始 也可以是可选的.但请注意,这可能会更改 URL 路径层次结构并引入请求映射冲突.例如,/user/invoices
是否会提供用户 null
的发票或 ID 为invoices"的用户的详细信息?
Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices
provide the invoices for user null
or details about a user with ID "invoices"?
这篇关于@RequestParam 与 @PathVariable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!