1. 如果使用@RequestBody接受頁面參數: public Map<String,Object> insertBudget(@ApiParam(required = true,name = "actBudgetCost",value = "預算")@RequestBody ActBudgetCost actBudgetCost, HttpServletRequest request){ } 那么前台頁面ajax應該這樣寫: $.ajax({ url: '', type: "POST", data: JSON.stringify({ "actiName":name }), dataType: "json", contentType: "application/json", async: false, success: function (result) { }, error: function (xhr, ajaxOptions, thrownError) { //console.log(thrownError); //alert any HTTP error //alert("請求出錯!"); return false; } }); 2. 如果不使用@RequestBody接受頁面參數: public Map<String, Object> regProduct(HttpServletRequest request, @ApiParam(name = "customerProAuditPO", value = "產品注冊實體")CustomerProAuditVO customerProAuditVO ) { } 那么前台頁面ajax應該這樣寫: var data = { customerName:customerName, }; $.ajax({ url:'', type: "POST", data: data, //async: false, dataType:"json", success: function(result) { var json = result; }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError); return false; } }); 復制代碼
一、問題描述
由於項目是前后端分離,因此后台使用的是spring boot,做成微服務,只暴露接口。接口設計風格為restful的風格,在get請求下,后台接收參數的注解為RequestBody時會報錯;在post請求下,后台接收參數的注解為RequestParam時也會報錯。
二、問題原因
由於spring的RequestParam注解接收的參數是來自於requestHeader中,即請求頭,也就是在url中,格式為xxx?username=123&password=456,而RequestBody注解接收的參數則是來自於requestBody中,即請求體中。
三、解決方法
因此綜上所述,如果為get請求時,后台接收參數的注解應該為RequestParam,如果為post請求時,則后台接收參數的注解就是為RequestBody。附上兩個例子,截圖如下:
get請求
post請求
另外,還有一種應用場景,接口規范為resultful風格時,舉個例子:如果要獲取某個id下此條問題答案的查詢次數的話,則后台就需要動態獲取參數,其注解為@PathVariable,並且requestMapping中的value應為value="/{id}/queryNum",截圖如下: