客戶端傳遞參數給服務端的兩種方式:請求參數 和 路徑變量
請求參數
請求參數可以發送值傳遞給服務器,請求參數採用key=value的形式並使用“&”符號進行參數間的分隔,例如:
http://localhost:8080/xxx/user?name=Tom&password=123456
傳遞過來的值Spring MVC需要解析,採用@RequestParam的形式來註釋方法中的參數,獲取上面兩個參數的方法爲:
@GetMapping("/name")
public User getUserByName(@RequestParam("id") Integer userId, @RequestParam("name") String username){
}
或者
@GetMapping("/xxx/user")
public User getUser(HttpServletRequest request){
Integer userId = Integer.decode(request.getParameter("id"));
String username = request.getParameter("name");
}
路徑變量
路徑變量類似請求參數,但是沒有key部分。由名稱可知路徑中存在變量,例如要傳遞一個age爲23的參數到服務端,其請求的URL爲:
http://localhost:8080/xxx/user/Tom/25;
服務端接受和處理的方法爲:
@GetMapping("/name/{name}/{id}")
public User getUserByName(@PathVariable("name")String username, @PathVariable("id")Integer userId){
}
參數寫在路徑上好,還是寫在請求參數上好
在RESTful風格中,/user/{name} 和 /user/{id} 兩個路徑,它們的http-method是一樣的,接收的都是String字符串。那麼當客戶端發送請求傳遞過來一個參數時,是給/user/{name}呢?還是給/user/{id}呢?
所以,在RESTful風格中,當兩個路徑的http-method一樣時,那麼路徑就不要一樣。比如可以將上面的/user/{name}改成/user/name/{name}