Spring mvc @PathVariable

后端 未结 8 860
轮回少年
轮回少年 2020-11-27 11:41

Can you give me a brief explanation and a sample in using @PathVariable in spring mvc? Please include on how you type the url?
I\'m struggling in getting th

8条回答
  •  生来不讨喜
    2020-11-27 11:58

    suppose you want to write a url to fetch some order, you can say

    www.mydomain.com/order/123
    

    where 123 is orderId.

    So now the url you will use in spring mvc controller would look like

    /order/{orderId}
    

    Now order id can be declared a path variable

    @RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
    public String getOrder(@PathVariable String orderId){
    //fetch order
    }
    

    if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring

    Also note that PathVariable differs from requestParam as pathVariable is part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

    API DOC
    Spring Official Reference

提交回复
热议问题