您的位置:首页 > 编程语言 > Java开发

Spring MVC自动返回XML/JSON

2015-12-11 16:07 344 查看
实现极其简单:

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

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


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

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

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

[code]@XmlRootElement(name="UserEntity")


即可!

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

图示:

1.XML



2.JSON



如果是返回的实体,就能得到xml/json,如果是String/JSON,xml则不行

(可能自己配的ContentNegotiatingViewResolver能够实现,以后再探讨)

[code]    @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

[code]        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 );
                            }
                });
        });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: