@RequestParam vs @PathVariable

前端 未结 7 882
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:22

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

+ was accepted by @Re

相关标签:
7条回答
  • 2020-11-22 06:49
    • @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

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

    0 讨论(0)
提交回复
热议问题