zoukankan      html  css  js  c++  java
  • SpringMVC中Json数据格式转换

    1    @RequestBody

    作用:

    @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。

    List.action?id=1&name=zhangsan&age=12

    本例子应用:

    @RequestBody注解实现接收http请求的json数据,将json数据转换为java对象

     2    @ResponseBody

    作用:

    该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

    本例子应用:

    @ResponseBody注解实现将controller方法返回对象转换为json响应给客户端

    3  环境配置

      3.1 jar包准备

      Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包,如下:

      3.2 springmvc.xml文件中的配置

      1) 如果配置文件中配置过注解驱动(<mvc:annotation-driven/>), 则无需多余配置

      2) 如果没有配置注解驱动, 则需如下配置(不推荐使用这种方式)

      <!--注解适配器 -->

        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

           <property name="messageConverters">

           <list>

           <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>

           </list>

           </property>

        </bean>

     4. Controller的编写

     @RequestMapping("/testJson.action")
        @ResponseBody
        public Items testJson (@RequestBody Items items) {
            return items;
        }

      对应jsp页面中js的编写

    function jsonTest () {
                $.ajax({
                    type:"post",
                    url:"${pageContext.request.contextPath}/item/testJson.action",
                    contentType:"application/json;charset=utf-8",
                    data:'{"name":"测试商品","price":99.9}',
                    success:function (data) {
                        alert(data.name);
                    }
                });
            }

  • 相关阅读:
    JS运动基础
    用setTimeout模拟QQ延时提示框
    jQuery面向对象的写法
    AngularJS学习笔记
    Scrollbar的样式
    postfix/dovecot邮件服务器
    Git 命令及git服务器
    一个分页功能的实现
    SSE(Server-Sent Events)
    qq上网正常浏览器上不了网
  • 原文地址:https://www.cnblogs.com/rodge-run/p/6545630.html
Copyright © 2011-2022 走看看