springmvc中@ReuqestBody和@ResponseBody传输json数据

来源:互联网 发布:mac不能保存书签 编辑:程序博客网 时间:2024/06/07 02:24

springmvc-4.2.4
pom.xml下要增加的依赖fasterxml的jar包:没有话会出现400错误

<dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.7.3</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-core</artifactId>    <version>2.7.3</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-annotations</artifactId>    <version>2.7.3</version></dependency>

加上spring-serlvet.xml中加上下面配置即可

<mvc:annotation-driven />

ajax请求代码片

<script type="text/javascript">    $(".btn").click(function() {        alert("点击按钮");        $.ajax({            type : "POST",            url : "catching",            //必须加否则报415错误            contentType : "application/json",            dataType : "json",            data : JSON.stringify({                "id" : 1,                "computerName" : "某某",                "publishDate" : "2010-10-20 00:00:00",                "position" : "java开发实习生"            }),            success : function(msg) {                alert(msg["id"]);//输出2            }        })    });</script>

控制器代码

@RequestMapping(value = "/catching", method = RequestMethod.POST)@ResponseBodypublic Info catching(HttpSession session, @RequestBody Info info) {    info.setId("2");    info.setComputerName("某某xx");    return info;}

这样返回给界面的数据会自动包装成json格式,如下:
{“id”:”2”,”computerName”:”某某xx”,”publishDate”:”2010-10-20 00:00:00”,”position”:”java开发实习生”}

注意:springmvc json解析会出现死循环,在一对多的情况下
比如一个班级对应多个学生class–>student,这时class类中就会有一个students属性,要避免死循环要在class上加注解@JsonIgnoreProperties(value={“students”})

0 0
原创粉丝点击