@RequestParam vs @PathVariable
原文地址
https://stackoverflow.com/questions/13715811/requestparam-vs-pathvariable
@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 an parameter from the URI as well — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParam
If 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) {
...
}
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"?