SpringMVC采用json格式数据交互

  • 环境准备
    SpringMVC默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包,如图:
json数据交互相关jar包.png
  • 配置json转换器
    在注解适配器中加入messageConverters

    
        
        
        
        
        
    

如果使用则不用定义上边的内容。

  • controller编写
// 商品修改提交json信息,响应json信息
    @RequestMapping("/editItemSubmit_RequestJson")
    public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
        System.out.println(items);
        //itemService.saveItem(items);
        return items;

    }
  • 页面js方法编写
//请求json响应json
    function request_json(){
        $.ajax({
            type:"post",
            url:"${pageContext.request.contextPath }/item/editItemSubmit_RequestJson.action",
            contentType:"application/json;charset=utf-8",
            data:'{"name":"测试商品","price":99.9}',
            success:function(data){
                alert(data);
            }
        });
    }

你可能感兴趣的:(SpringMVC采用json格式数据交互)