标签:
首先在springmvc的配置文件中,添加如下
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
一. 将json形式的数据传给前台
1.@Controller注解的方法中,添加如下代码:
@RequestMapping("/getPersonList")
public @ResponseBody List<Person> getPerson(){
List<Person> list = new ArrayList<Person>();
Person person1 = new Person();
person1.setUsername("tom");
person1.setRealName("realTom");
person1.setPassword("123456");
person1.setPrice(123.45);
Person person2 = new Person();
person2.setUsername("tom");
person2.setRealName("realTom");
person2.setPassword("123456");
person2.setPrice(123.45);
list.add(person2);
list.add(person1);
return list;
}
entity(Person)中添加以上属性,以及setter,getter方法即可
2.前台调用,代码如下
<a href="getPersonList">GET PERSON LIST</a>
二. 将json形式的数据传给后台
1.前台代码调用如下:
<a class="addPerson" href="addPerson"> ADD Person</a>
<script type="text/javascript">
$(function(){
$(".addPerson").click(function(){
alert("test....");
var paramData = {"username": "tom","password":"123456","realName":"realtom","price":1234.56};
$.ajax({
type:"POST",
url:"addPerson",
dataType:"json",
contentType:"application/json",
data:JSON.stringify(paramData), // 直接paramData不可以
success:function(data){
}
});
return false;
});
});
2.@Controller类中添加如下代码:
@RequestMapping(value="user/saveUser", method={RequestMethod.POST})
public void saveUser(@RequestBody List<User> users){
System.out.println("saveUser....");
System.out.println(users);
}
除了springmvc基础的jar包以外,还有如下jar包:
jackson-annotations-2.1.4.jar
jackson-core-2.1.4.jar
jackson-core-asl-1.9.13.jar
jackson-databind-2.1.4.jar
jackson-mapper-asl-1.9.13.jar
标签:
原文地址:http://www.cnblogs.com/mianteno/p/5162708.html