Spring MVC+Jquery Ajax 前后台传递Json对象

关于Spring MVC3.X 接收和返回Json

 

最近开发项目时遇到此问题,解决后,特做下备忘:

1.   javabean 1: Content.java

public class Content implements Serializable {
	private static final long serialVersionUID = -8184052506726598065L;
	private Integer id;
	private Integer parentId;
	private String msgType;
	private Integer serial;
	private String content;
      getter and setter.............
}

      javabean2: Blog.java

public class Blog implements Serializable {
      private static final long serialVersionUID = 1844582159472756595L;
      private List<Content> contents;
      private Integer id;
      private String sendModel;
      private Date sendTime;
      private String sinaUser;
      private String type;
      getter and setter.............
}

 

2. 页面Js: Send.js

function doSend(){
	var account = $.trim($("#sinauser").val());
	var message = this.checkform();
	if(account!=""){
		if(message){
           //发送到后台的js对象[和javabean1和2的结构一致]			
			var data = this.parseBlog();
			//将js对象转成json对象[需jquery 的json插件]
			var json = $.toJSON(data);alert(json);
			$.ajax({
				url:"/PEMP/rest/weibo/entrance.do",
				dataType:"json",//返回值类型Json	
			        processData: false,
				contentType: "application/json",//请求内容为Json 
				type:"POST",
				async:false,
				data:json, 
				success:function(data,textStatus){
					var content="";
					var error = "";
					if(data && data.result){
						content = data.data;
						$("#token").text(content);
					}else{
						error = data.message;
						alert(error);
					}
					$("#result").html(content+error); 
					$("#message").val("");
		 		}
			});   	 
		}
	}else{
	 	alert("请选择发送到的微博帐号!");
	}
}

  

3. java后台接收类: WeiboController.java

@Controller
@RequestMapping("/weibo")
public class WeiBoController {
	@ResponseBody//返回值为Json类型[JsonResult为自己封装的Json类]	
        @RequestMapping(value = "/entrance.do", method = RequestMethod.POST)
	public JsonResult weixinInterfacePost(HttpServletResponse response,	
         @RequestBody Blog blog//接收参数为Json类型
                ) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String error = "";
		try{
                     ......//写自己的处理逻辑
           	     return JsonResult.SUCCESS; 
                   }catch(Exception err){
			err.printStackTrace();
		}
		return JsonResult.failure(error); 
	} 
}

 

你可能感兴趣的:(json,spring mvc,jQuery ajax)