传递JSON数据有没有必要用RequestBody?

在使用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) { } });

后端参数的写法也很灵活:ajax

@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字符串typescript

//须要使用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) { } });

后端参数的用法也不灵活:json

//这种方式下全部的参数都只能封装在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。
相关文章
相关标签/搜索