ITeye博客

Struts+jsonplugin

hjy2099 · 2010-04-19 20:42 · JAVA · 编程语言 · Ajax · Spring · Struts · json · jQuery · Markdown

JSON官方文档

http://www.json.org/json-zh.html

 

jQuery官方文档

http://docs.jquery.com/Main_Page

 

Js代码 复制代码

  1. <SPAN style="FONT-SIZE: small">function removerecordbyid(recordid){
  2. $("#showallrecord table tr").each(
  3. function(){
  4. var seq=parseInt($(this).children("td").html());
  5. var thisrecord = this;
  6. if(seq==recordid)
  7. if(confirm("您确认执行删除操作么?")){
  8. $.ajax({
  9. type: "POST",
  10. url:"removeRecordById.action",
  11. dataType:"json",
  12. data:{"msg.id":recordid},
  13. success:function(json){
  14. if(json.status==4){
  15. alert("删除失败,只有提交留言的ip才能删除");
  16. }else{
  17. $(thisrecord).remove();
  18. //                          alert("删除成功");
  19. }
  20. },
  21. error:function(){
  22. alert("del error");
  23. }
  24. });
  25. }
  26. });
  27. }
  28. function getrecordbypage(page){
  29. $.ajax({
  30. type: "POST",
  31. url:"listAllRecordByPage.action",
  32. dataType:"json",
  33. data:{"page":page},
  34. success:function(json){
  35. var strs="<table border=\"1\"><tr id='colattr'><td>key-id</td><td>昵称</td><td>留言时间</td><td width='120'>邮箱</td><td width='120'>博客</td><td width='250'>留言</td><td>操作</td></tr>";
  36. for(i=0;i<json.records.length;i++){
  37. str="<tr id='"+json.records[i].id+"' onclick='lineclick(this);'><td>"+json.records[i].id+"</td><td>"+json.records[i].from+"</td><td>"+json.records[i].addDate+"</td><td>"+json.records[i].mail+"</td><td>"+json.records[i].site+"</td><td>"+json.records[i].cont+"</td><td><a onclick='removerecordbyid("+json.records[i].id+");'>删除</a></td></tr>"
  38. strs=strs+str
  39. }
  40. strs=strs+"</table>"
  41. $("#showallrecord").html(strs);
  42. },
  43. error:function(){
  44. alert("error");
  45. }
  46. });
  47. };</SPAN>
function removerecordbyid(recordid){ 
   		$("#showallrecord table tr").each(
  		function(){
		  var seq=parseInt($(this).children("td").html());
		  var thisrecord = this;
		  if(seq==recordid)
		  	if(confirm("您确认执行删除操作么?")){
		  		$.ajax({
					type: "POST",
					url:"removeRecordById.action",
					dataType:"json",
					data:{"msg.id":recordid},
					success:function(json){
						if(json.status==4){
							alert("删除失败,只有提交留言的ip才能删除");
						}else{
							$(thisrecord).remove();
//							alert("删除成功");	
						}
					},
					error:function(){
						alert("del error");
					}
				});
		  	}
		});
	}
	
	
		function getrecordbypage(page){
		$.ajax({
			type: "POST",
			url:"listAllRecordByPage.action",
			dataType:"json",
			data:{"page":page},
			success:function(json){
				var strs="<table border=\"1\"><tr id='colattr'><td>key-id</td><td>昵称</td><td>留言时间</td><td width='120'>邮箱</td><td width='120'>博客</td><td width='250'>留言</td><td>操作</td></tr>";
				for(i=0;i<json.records.length;i++){
					str="<tr id='"+json.records[i].id+"' onclick='lineclick(this);'><td>"+json.records[i].id+"</td><td>"+json.records[i].from+"</td><td>"+json.records[i].addDate+"</td><td>"+json.records[i].mail+"</td><td>"+json.records[i].site+"</td><td>"+json.records[i].cont+"</td><td><a onclick='removerecordbyid("+json.records[i].id+");'>删除</a></td></tr>"
					strs=strs+str
				}
				strs=strs+"</table>"
				$("#showallrecord").html(strs);
			},
			error:function(){
				alert("error");
			}
		});
		
	};

 

注意dataType:"json"这个参数一定不能少,否则不能正确识别

一下是Struts action代码

Java代码 复制代码

  1. <SPAN style="FONT-SIZE: small">public class CrudMsgAction extends ActionSupport{
  2. private Record msg;
  3. private int index;
  4. private RecordService recordService;
  5. private List<Record> records;
  6. private int status = 0;
  7. private int page = 0;
  8. @JSON(serialize=false)
  9. public RecordService getRecordService() {
  10. return recordService;
  11. }
  12. //other getter and setter
  13. @Override
  14. public String execute() throws Exception {
  15. return SUCCESS;
  16. }
  17. /**
  18. * 返回所有记录的JSON数据
  19. * @return list . All of the record.
  20. * @throws Exception
  21. */
  22. public String listAllRecord() throws Exception{
  23. List<Record> list = recordService.listAllRecord();
  24. //      List list = Arrays.asList(allRecord);
  25. //      List<Record> list2 = (List<Record>)list;
  26. //      Record rec = (Record)list.get(0);
  27. records = list;
  28. return SUCCESS;
  29. }
  30. public String listAllRecordByPage() throws Exception{
  31. List<Record> list = recordService.listAllRecord(page);
  32. records = list;
  33. return SUCCESS;
  34. }
  35. /**
  36. * 插入记录
  37. * @return update the view with AJAX when struts2 action return
  38. * @throws Exception
  39. */
  40. public String insertRecord() throws Exception{
  41. //插入留言日期设置
  42. msg.setAddDate(new Date());
  43. //获取客户端ip,setIpaddr
  44. String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
  45. msg.setIpaddr(clientIpAddr);
  46. //判断是否为空
  47. if("".equals(msg.getFrom()))msg.setFrom("anonymous");
  48. if("".equals(msg.getMail()))msg.setMail("@");
  49. if("".equals(msg.getSite()))msg.setSite("-");
  50. if("".equals(msg.getCont()))msg.setCont("这家伙很懒,什么都没留下");
  51. recordService.insertRecord(msg);
  52. return SUCCESS;
  53. }
  54. /**
  55. * 通过索引查找记录
  56. * @return the field msg
  57. * @throws Exception
  58. */
  59. public String listRecordByIndex() throws Exception{
  60. List<Record> list = recordService.listAllRecord();
  61. this.msg = list.get(this.getIndex());
  62. return SUCCESS;
  63. }
  64. /**
  65. * 删除对应id记录
  66. * @return field status. in order to update view with AJAX
  67. * @throws Exception
  68. */
  69. public String removeRecordById() throws Exception{
  70. String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
  71. Record r = recordService.listRecordById(msg.getId());
  72. if(clientIpAddr.equals(r.getIpaddr())){
  73. recordService.removeRecordById(msg.getId());
  74. return SUCCESS;
  75. }
  76. status = 4;
  77. return SUCCESS;
  78. }
  79. /**
  80. * 获得分页数
  81. * @return pageSize using field page
  82. * @throws Exception
  83. */
  84. public String getPageSize() throws Exception{
  85. page = recordService.getPage();
  86. return SUCCESS;
  87. }
  88. }</SPAN>
public class CrudMsgAction extends ActionSupport{
	private Record msg;
	private int index;
	private RecordService recordService;
	private List<Record> records;
	private int status = 0;
	private int page = 0;
	
	@JSON(serialize=false)
	public RecordService getRecordService() {
		return recordService;
	}
//other getter and setter
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * 返回所有记录的JSON数据
	 * @return list . All of the record.
	 * @throws Exception
	 */	
	public String listAllRecord() throws Exception{
		List<Record> list = recordService.listAllRecord();
//		List list = Arrays.asList(allRecord);
//		List<Record> list2 = (List<Record>)list;

		//		Record rec = (Record)list.get(0);
		records = list;
		return SUCCESS;
	}
	
	public String listAllRecordByPage() throws Exception{
		List<Record> list = recordService.listAllRecord(page);
		records = list;
		return SUCCESS;
	}
	

	/**
	 * 插入记录
	 * @return update the view with AJAX when struts2 action return
	 * @throws Exception
	 */
	public String insertRecord() throws Exception{
		//插入留言日期设置
		msg.setAddDate(new Date());
		//获取客户端ip,setIpaddr
		String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
		msg.setIpaddr(clientIpAddr);
		//判断是否为空
		if("".equals(msg.getFrom()))msg.setFrom("anonymous");
		if("".equals(msg.getMail()))msg.setMail("@");
		if("".equals(msg.getSite()))msg.setSite("-");
		if("".equals(msg.getCont()))msg.setCont("这家伙很懒,什么都没留下");
		
		recordService.insertRecord(msg);
		return SUCCESS;
	}
	/**
	 * 通过索引查找记录
	 * @return the field msg
	 * @throws Exception
	 */
	public String listRecordByIndex() throws Exception{
		List<Record> list = recordService.listAllRecord();
		this.msg = list.get(this.getIndex());
		
		return SUCCESS;
	}
	/**
	 * 删除对应id记录
	 * @return field status. in order to update view with AJAX
	 * @throws Exception
	 */
	public String removeRecordById() throws Exception{
		String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
		Record r = recordService.listRecordById(msg.getId());
		if(clientIpAddr.equals(r.getIpaddr())){
			recordService.removeRecordById(msg.getId());
			return SUCCESS;
		}
		status = 4;
		return SUCCESS;
	}
	
	/**
	 * 获得分页数
	 * @return pageSize using field page
	 * @throws Exception
	 */
	public String getPageSize() throws Exception{
		page = recordService.getPage();
		return SUCCESS;
	}
}

 

在上面代码中,使用了JSON注释@JSON(serialize=false),
除此之外,JSON注释还支持如下几个域:
name:指定Action属性被序列化成JSON对象的属性名。
serialize:设置是否序列化该属性
deserialize:设置是否反序列化该属性。
format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。

 

Xml代码 复制代码

  1. <SPAN style="FONT-SIZE: small"><?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. <constant name="struts.objectFactory" value="spring"/>
  7. <package name="json" extends="json-default">
  8. <action name="ajaxRequest" class="com.jun.demos.struts2json.HelloWorld">
  9. <result type="json" />
  10. </action>
  11. <action name="listIndexRecord" class="com.jun.demos.book.action.CrudMsgAction">
  12. <result type="json" />
  13. </action>
  14. <action name="listAllRecord" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecord">
  15. <result type="json" />
  16. </action>
  17. <action name="listAllRecordByPage" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecordByPage">
  18. <result type="json" />
  19. </action>
  20. <action name="insertRecord" class="com.jun.demos.book.action.CrudMsgAction" method="insertRecord">
  21. <result type="json" />
  22. </action>
  23. <action name="removeRecordById" class="com.jun.demos.book.action.CrudMsgAction" method="removeRecordById">
  24. <result type="json" />
  25. </action>
  26. <action name="getPageIndex" class="com.jun.demos.book.action.CrudMsgAction" method="getPageSize">
  27. <result type="json" />
  28. </action>
  29. </package>
  30. </struts></SPAN>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.objectFactory" value="spring"/>
	<package name="json" extends="json-default">
		<action name="ajaxRequest" class="com.jun.demos.struts2json.HelloWorld">
			<result type="json" />
		</action>
		<action name="listIndexRecord" class="com.jun.demos.book.action.CrudMsgAction">
			<result type="json" />
		</action>
		<action name="listAllRecord" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecord">
			<result type="json" />
		</action>
		<action name="listAllRecordByPage" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecordByPage">
			<result type="json" />
		</action>
		<action name="insertRecord" class="com.jun.demos.book.action.CrudMsgAction" method="insertRecord">
			<result type="json" />
		</action>
		<action name="removeRecordById" class="com.jun.demos.book.action.CrudMsgAction" method="removeRecordById">
			<result type="json" />
		</action>
		<action name="getPageIndex" class="com.jun.demos.book.action.CrudMsgAction" method="getPageSize">
			<result type="json" />
		</action>
		
	</package>
</struts>

 配置该Action与配置普通Action存在小小的区别。

包继承了json-default包,而不再继承默认的default包,这是因为只有在该包下才有json类型的Result。
result可以使用<param name="excludeProperties">page,index</param>
排除Action中这些都不返回的属性.

结合action中属性getter方法注解@JSON(serialize=false)灵活配置

异常解决:

 

Xml代码 复制代码

  1. Nested in javax.servlet.ServletException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: java.lang.reflect.InvocationTargetException:
  2. com.google.apphosting.utils.jetty.JettyLogger warn
Nested in javax.servlet.ServletException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: com.googlecode.jsonplugin.JSONException: java.lang.reflect.InvocationTargetException:

com.google.apphosting.utils.jetty.JettyLogger warn

 

这里下面有4-5页的异常信息,就不贴出来了

 

解决方法:

出现这个问题是某属性通过串行化json数据异常,

因为使用的spring注入属性recordService,也就是提供了getter和setter,

而sturts-plugin是通过getterXxx把Xxx属性串行化输出JSON到客户端,

所以解决这个异常方法就是在不需要串行化的属性的getter前加上annotation,

就是@JSON(Serialize=false)

 

代码如:

   

   

Java代码 复制代码

  1. @JSON(serialize=false)
  2. public RecordService getRecordService() {
  3. return recordService;
  4. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。