Spring MVC自动返回XML/JSON


实现极其简单:

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

    
    
    <mvc:annotation-driven/>

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

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

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

@XmlRootElement(name="UserEntity")

即可!


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


图示:

1.XML
Spring MVC自动返回XML/JSON_第1张图片

2.JSON
Spring MVC自动返回XML/JSON_第2张图片


如果是返回的实体,就能得到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 );
                            }
                });
        });

你可能感兴趣的:(Spring框架学习)