作者微信 bishe2022

代码功能演示视频在页面下方,请先观看;如需定制开发,联系页面右侧客服
SpringMVC中Json数据格式转换

Custom Tab

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的包,如下:

ggggggggggggggg.png

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);
                }
            });
        }

转载自:https://www.cnblogs.com/rodge-run/p/6545630.html

Home