zoukankan      html  css  js  c++  java
  • 传递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。
  • 相关阅读:
    c语言变量的交换
    牛客网 多多的电子字典
    算法笔记----背包九讲 ③多重背包问题
    统计学习方法 课后习题第五章
    2020.8.2 19:00-21:00 拼多多算法岗笔试
    python构建模块
    leetcode 剑指 Offer 51. 数组中的逆序对
    pytorch的内部计算
    matplotlib
    矩阵微积分
  • 原文地址:https://www.cnblogs.com/NJM-F/p/10407763.html
Copyright © 2011-2022 走看看