概述
当前端使用 Ajax 发送请求时,服务器要以 JSON 的数据格式响应给浏览器
使用方式
@ResponseBody来实现;注解方式
@ResponseBody
1.添加 json 处理相关 jar 包

2.在配置文件当中写上 <mvc:annotation-driven/>
3.设置映射方法的返回值为 @ResponseBody
方式1-直接返回一个对象

方式2-返回一个List集合

方式3-返回一个Map集合

表单序列化
序列化方式
| 12
 3
 4
 5
 6
 7
 8
 
 | <form id="myform">user:<input type="text" name="username"><br>
 age:<input type="text" name="age" ><br>
 爱好:<input type="checkbox" name="hobby" value="篮球"> 篮球
 <input type="checkbox" name="hobby" value="乒乓球"> 乒乓球
 <input type="checkbox" name="hobby" value="足球"> 足球
 </form>
 <input type="button" id="formbtn" value="发送form">
 
 | 
序列化转Json
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | (function($){$.fn.serializeJson=function(){
 var serializeObj={};
 var array=this.serializeArray();
 var str=this.serialize();
 $(array).each(function(){
 if(serializeObj[this.name]){
 if($.isArray(serializeObj[this.name])){
 serializeObj[this.name].push(this.value);
 }else{
 serializeObj[this.name]=[serializeObj[this.name],this.value];
 }
 }else{
 serializeObj[this.name]=this.value;
 }
 });
 return serializeObj;
 };
 })(jQuery);
 
 | 
@RequestBody
作用
默认情况下我们发送的都是 Content-Type 不是 application/x-www-form-urlencoded,直接使用 @RequestParam 接收参数,如果不是 Content-Type 不是 application/x-www-form-urlencoded 编码的内容,例如 application/json, application/xml 等;使用 @RequestBody 接收
使用
发送Json参数

| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | $.ajax({type:"post",
 url:"${pageContext.request.contextPath}/formJson",
 data:JSON.stringify(serialize2),
 dataType:'json',
 contentType:'application/json',
 success:function (data) {
 alert(data.responseText)
 }
 });
 
 | 

发送二进制流

