<div>
<input type="text" />
<input type="button" value="点我" id="button" />
</div>
<script type="text/javascript" src="assets/plugins/jquery/jquery-1.11.1.js"></script>
<script >
$().ready(function(){
$("#button").click(function(){
var json= '{"personId":9527,"personName":"吴海鑫","personSex":"女","love":["LOL","CF"]}';
$.ajax({
type: 'POST',
url: "rest/test/login",
dataType: "json",
data: json,
contentType:"application/json",
success: function(data){
}
});
});
});
</script>
//上面是jsp代码 注意:使用简写的ajax请求的时候没有contentType属性,简写的date属性格式不一样
//下面是SpringMVC控制台代码
@Controller
@RequestMapping("/test")
public class testController {
@RequestMapping("/login")
public @ResponseBody List<Person> login(@RequestBody Person json) {
Person person = new Person();
person.setPersonId(9527);
person.setPersonName("吴海鑫");
person.setPersonSex("女");
person.setLove(new String[] { "LOL", "CF" });
Person person5 = new Person();
person5.setPersonId(9527);
person5.setPersonName("吴海鑫");
person5.setPersonSex("女");
person5.setLove(new String[] { "LOL", "CF" });
List<Person> personList = new ArrayList<Person>();
personList.add(person);
personList.add(person5);
return personList;
}
}
//在这里,加了@RequestBody注解,从前端得到的json格式数据会被直接转换成javabean,这里要注意的是,如果jsp用简写的ajax请求,这里加注解浏览器会报错,原因是
contentType的属性在简写方式中默认不是application/json