在使用SpringMVC的時候自己一直避免使用RequestBody,因為覺的它在參數處理的時候不夠方便。
理由如下:
1.不使用RequestBody時是這樣的:
前端參數可以直接使用JSON對象:
//此時請求的ContentType默認是application/x-www-form-urlencoded: var user= { "username" : username, "password" : password, "rememberMe":rememberMe }; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, data : user, dataType : 'json', success : function(data) { } });
后端參數的寫法也很靈活:
@RequestMapping("/jsontest.do") public void test(User user,String username,String password,Boolean rememberMe){ System.out.println(user); System.out.println("username: " + username); System.out.println("password: " + password); System.out.println("rememberMe: " + rememberMe); }
2.而使用RequestBody是這樣的:
前端使用application/json的時候,必須要將JSON對象
轉換為JSON字符串
//需要使用JSON.stringify()將JSON對象轉化為JSON字符串 var user= { "username" : username, "password" : password }; $.ajax({ url : "http://...../jsontest.do", type : "POST", async : true, contentType: "application/json; charset=utf-8", data : JSON.stringify(user), dataType : 'json', success : function(data) { } });
后端參數的用法也不靈活:
//這種方式下所有的參數都只能封裝在User對象中,不能單獨設置參數 @RequestMapping("/jsontest") public void test(@RequestBody User user ){ String username = user.getUsername(); String password = user.getPassword(); } 或者 @RequestMapping("/jsontest") public void test(@RequestBody Map map ){ String username = map.get("username").toString(); String password = map.get("password").toString(); } 或者 public void test(@RequestBody String jsonData) { JSONObject jsonObject = JSON.parseObject(jsonData); String username= jsonObject.getString("username"); String username= jsonObject.getString("password"); }
兩者比較很明顯:
第1種有以下優點:
1.前端傳遞數據不用轉換為json字符串:JSON.stringify(user)
2.后端接受的參數很靈活,即可以封裝為User對象,亦可以使用單個參數username,rememberMe,甚至User對象和單個rememberMe參數混合使用都可以
而第2種則沒有第1種簡單和靈活。所以我選擇了不使用RequestBody,而前端發送的格式也同樣不再是application/json了,而是application/x-www-form-urlencoded。