@RequestParam vs @PathVariable

user1857181 picture user1857181 · Dec 5, 2012 · Viewed 441.9k times · Source

What is the difference between @RequestParam and @PathVariable while handling special characters?

+ was accepted by @RequestParam as space.

In the case of @PathVariable, + was accepted as +.

Answer

Ralph picture Ralph · Dec 5, 2012

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) {
  ...
}

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"?