# 常用註解 @PathVariable 與 @RequestParam ###### tags: `Spring` `springframework` `Spring-web` 先說一下Request瞭解一下請求參數是什麼 在訪問各種各樣網站時,經常會發現網站的URL的最後一部分會像是:?xxxx=yyyy&zzzz=wwww。這就是 HTTP 協議中的 Request 參數,它有什麼用呢?先來看一個例子: 在 google 搜尋 hackmd 瀏覽器的 URL 就會變成: `https://www.google.com/search?q=hackmd&oq=hackmd&aqs=chrome..69i57j0l3j69i60l4.7956j0j7&sourceid=chrome&ie=UTF-8` 我們可以看到 `?q=hackmd`,就是搜尋時請求的參數,不同參數之間用`&`分隔,且每個參數以`name=value`的方式表示,在這個例子中輸入不同關鍵字,在搜尋結果的頁面 URL 中 q 的參數就會不同。 ### Re `http://localhost:8080/springmvc/hello/101?param1=10¶m2=20` ``` @RequestMapping("/hello/{id}") public String getDetails(@PathVariable(value="id") String id, @RequestParam(value="param1", required=true) String param1, @RequestParam(value="param2", required=false) String param2){ ....... } ``` 相信大家可能注意到了, @RequestParam 和 @PathVariable 都能夠完成類似的功能,因為本質上,它們都是使用者的輸入,只不過輸入的部分不同,一個在URL路徑部分,另一個在參數部分,簡單的說就是 URL 寫法不同,如下: 使用 @RequestParam 時,URL 是這樣的:`http://host:port/path?參數名=參數值` 使用 @PathVariable時,URL是這樣的:`http://host:port/path/參數值`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up