Spring MVC自动返回XML/JSON


实现极其简单:

1.在你的application.xml中加上注释:

    <!-- 扩充了注解驱动,可以将请求参数直接绑定到控制器参数,参考 @RequestParam("username") String userName -->
    <!-- 2015-12-11 还能实现同一资源 多种表述,按需返回JSON/XML -->
    <mvc:annotation-driven/>

其实这个注释一般都加上了,只是今天折腾了半天才发现它这么强大!

2.要想得到xml,一般都只能是返回实体的时候转换。

我们只需要在实体类上标注

@XmlRootElement(name="UserEntity")

即可!


这两步加入后,根据需要,就能返回json/xml啦!


图示:

1.XML
这里写图片描述

2.JSON
这里写图片描述


如果是返回的实体,就能得到xml/json,如果是String/JSON,xml则不行
(可能自己配的ContentNegotiatingViewResolver能够实现,以后再探讨)

    @RequestMapping(value="/bind",method=RequestMethod.POST)
    @ResponseBody
    public User TestBind(@RequestBody User user){
        System.out.println(ReflectionToStringBuilder.toString(user));
        System.out.println(JSONObject.toJSONString(user));
//      return JSONObject.toJSONString(user);
        return user;
    }

3.javascript ajax得到json / xml

        var postResponse;
        $("button#post1").click(function(){
            $.ajax({
                  type: 'POST',
                  contentType: "application/json;charset=utf-8",
                  url:  basepath + "user/bind",
                  // 要post json数据,一定要转换类型 否则格式为a=2&b=3&now=14...
                  data: JSON.stringify({ 
                        "userName":"名",
                        "credits":3,
                        "password":"asdasd"
                        }),
                  // 相当于Accept application/xml
                  dataType: "json", 
                  // dataType: "xml", 
                  success: function(data,status){
                            postResponse = data;
                            alert("Data:" + postResponse.userName + "\n" 
                                          + postResponse.credits + "\n" + postResponse.password 
                                          + "\n" + "\nStatus:" + status );
                            }
                });
        });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值