• SpringMVC传递JSON数据



    一、前后端传递和接收JSON数据

    1:是要Ajax默认格式来传递数据(*)

    Ajax的默认格式为:(application/x-www-form-urlencoded),相当于(username=“admin”&password=123)来传递数据(这是GET请求的固定格式)。

    前端源码:

    当Ajax以默认格式上传时,data数据直接使用JSON对象user,不用转换为JSON字符串(很方便)
     var user= {
                    "username" : username,
                    "password" : password,
                    "rememberMe":rememberMe
                };
    $.ajax({
        url : "http://...../jsontest.do",
        type : "POST",
        async : true,
        data : user,
        dataType : 'json',
        success : function(data) {
        }
    });
    

    后端使用@RequestParam注解或省略:

    //(推荐),直接省略注解
    @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);
        
    }
    
    //(不推荐)加上注解
    @RequestMapping("/jsontest.do")
    public void test(@RequestParam String username,
    @RequestParam String password,@RequestParam Boolean rememberMe,){
        System.out.println("username: " + username);
        System.out.println("password: " + password);
        System.out.println("rememberMe: " + rememberMe);
    }
    

    优点:

    1. 前端传递数据不用转换为json字符串:JSON.stringify(user)
    2. 后端接受的参数很灵活,即可以封装为User对象,亦可以使用单个参数username,rememberMe,甚至User对象和单个rememberMe参数混合使用都可以

    2:使用application/json格式来传递数据

    Content-Type使用application/json的时候,要将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) {
            }
     });
    

    后端必须使用@RequestBody 注解:

    //这种方式下所有的参数都只能封装在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. 前端需要使用JSON.stringify()将JSON对象转换为JSON字符串
    2. 后端在接受参数的时候比较麻烦,没有第1种简单,也没有第一种灵活

    二、spring-web.xml中需要如下配置

     <!-- annotation-driven 控制器映射器和控制器适配器 ,用来控制@Controller处理http请求的方式-->
        <mvc:annotation-driven>
            <mvc:message-converters><!-- register-defaults="true"表示使用默认的消息转换器 -->
                <!-- FastJson(Spring4.2x以上版本设置) -->
                <!-- 使用@responsebody注解并且返回值类型为String时,返回的string字符串带有双引号"{'user':'songfs'}",其原因是直接将string类型转成了json字符串,应该在json解析器之前添加字符串解析器-->
                <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
                <!-- FastJsonHttpMessageConverter4 使@ResponseBody支持返回Map<String,Object>等类型,它会自动转换为json-->
                <!-- 需要返回json时需要配置 produces = "application/json"。不需要再指定utf-8了 -->
                <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                    <!-- 加入支持的媒体类型 -->
                    <property name="supportedMediaTypes">
                        <list>
                            <!-- 这里顺序不能反,一定先写text/html,不然IE执行AJAX时,返回JSON会出现下载文件 -->
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                            <value>application/xml;charset=UTF-8</value>
                        </list>
                    </property>
                    <property name="fastJsonConfig">
                        <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                            <property name="features">
                                <list>
                                    <value>AllowArbitraryCommas</value>
                                    <value>AllowUnQuotedFieldNames</value>
                                    <value>DisableCircularReferenceDetect</value>
                                </list>
                            </property>
                            <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    


    原文链接:
    SpringMVC传递JSON数据的推荐方式

  • 相关阅读:
    Sqlite数据库sqlite3命令
    cerr
    include 尖括号和双引号
    C程序存储空间布局——各数据段的内存位置
    贪心算法
    CodeBlocks
    O(n)是什么
    微软公司面试题
    CSS3---结构性伪类选择器—not
    CSS3---结构性伪类选择器-root
  • 原文地址:https://www.cnblogs.com/aixing/p/13327545.html
Copyright © 2020-2023  润新知