传递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) {
    }
});

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

@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。
posted @ 2019-02-20 17:05  梦中的鱼  阅读(10696)  评论(0编辑  收藏  举报