使用@RequestParam接收前段參數比較方便,前端傳參的URL:前端
url = 「${ctx}/main/mm/am/edit?Id=${Id}&name=${name}」
複製代碼
後端使用集合來接受參數,靈活性較好,若是url中沒有對參數賦key值,後端在接收時,會根據參數值的類型附,賦一個初始key(String、long ……)ajax
@RequestMapping("/edit")
public String edit(Model model, @RequestParam Map<String, Object> paramMap ) {
long id = Long.parseLong(paramMap.get("id").toString());
String name = paramMap.get("name").toString;
return page("edit");
}
複製代碼
使用@PathVariable接收參數,參數值須要在url進行佔位,前端傳參的URL:spring
前臺實例:url = 「${ctx}/main/mm/am/edit/${Id}/${name}」
json
服務端接受:後端
@RequestMapping("/edit/{id}/{name}")
public String edit(Model model, @PathVariable long id,@PathVariable String name) {
return page("edit");
}
複製代碼
前端傳參的URL於後端@RequestMapping的URL必須相同且參數位置一一對應,不然前端會找不到後端地址bash
先介紹一下@RequestParam的使用場景:app
註解@RequestParam接收的參數是來自requestHeader中,即請求頭。一般用於GET請求,好比常見的url:http://localhost:8081/spring-boot-study/novel/findByAuthorAndType?author=唐家三少&type=已完結
,其在Controller 層的寫法以下圖所示: spring-boot
@RequestParam用來處理 Content-Type 爲 application/x-www-form-urlencoded 編碼的內容,Content-Type默認爲該屬性。ui
@RequestParam也可用於其它類型的請求,例如:POST、DELETE等請求。好比向表中插入單條數據,可是這樣不支持批量插入數據啊,若是改用 json 字符串來傳值的話,類型設置爲 application/json,點擊發送的話,會報錯,後臺接收不到值,爲 null。編碼
這時候,註解@RequestBody就派上用場了。
先介紹一下@RequestBody的使用場景:
註解@RequestBody接收的參數是來自requestBody中,即請求體。通常用於處理非 Content-Type: application/x-www-form-urlencoded
編碼格式的數據,好比:application/json、application/xml
等類型的數據。
就application/json類型的數據而言,使用註解@RequestBody能夠將body裏面全部的json數據傳到後端,後端再進行解析。
舉個批量插入數據的例子,Controller層的寫法以下圖所示: