`
wjjbfq
  • 浏览: 80491 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Struts2,AJAX,json-plugin使用

阅读更多

代码请参照http://acheron.javaeye.com/admin/blogs/402499

 

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.        
  29.        
  30.         function getrecordbypage(page){   
  31.         $.ajax({   
  32.             type: "POST",   
  33.             url:"listAllRecordByPage.action",   
  34.             dataType:"json",   
  35.             data:{"page":page},   
  36.             success:function(json){   
  37.                 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>";   
  38.                 for(i=0;i<json.records.length;i++){   
  39.                     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>"  
  40.                     strs=strs+str   
  41.                 }   
  42.                 strs=strs+"</table>"  
  43.                 $("#showallrecord").html(strs);   
  44.             },   
  45.             error:function(){   
  46.                 alert("error");   
  47.             }   
  48.         });   
  49.            
  50.     };</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.        
  9.     @JSON(serialize=false)   
  10.     public RecordService getRecordService() {   
  11.         return recordService;   
  12.     }   
  13. //other getter and setter   
  14.     @Override  
  15.     public String execute() throws Exception {   
  16.         return SUCCESS;   
  17.     }   
  18.        
  19.     /**  
  20.      * 返回所有记录的JSON数据  
  21.      * @return list . All of the record.  
  22.      * @throws Exception  
  23.      */    
  24.     public String listAllRecord() throws Exception{   
  25.         List<Record> list = recordService.listAllRecord();   
  26. //      List list = Arrays.asList(allRecord);   
  27. //      List<Record> list2 = (List<Record>)list;   
  28.   
  29.         //      Record rec = (Record)list.get(0);   
  30.         records = list;   
  31.         return SUCCESS;   
  32.     }   
  33.        
  34.     public String listAllRecordByPage() throws Exception{   
  35.         List<Record> list = recordService.listAllRecord(page);   
  36.         records = list;   
  37.         return SUCCESS;   
  38.     }   
  39.        
  40.   
  41.     /**  
  42.      * 插入记录  
  43.      * @return update the view with AJAX when struts2 action return  
  44.      * @throws Exception  
  45.      */  
  46.     public String insertRecord() throws Exception{   
  47.         //插入留言日期设置   
  48.         msg.setAddDate(new Date());   
  49.         //获取客户端ip,setIpaddr   
  50.         String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();   
  51.         msg.setIpaddr(clientIpAddr);   
  52.         //判断是否为空   
  53.         if("".equals(msg.getFrom()))msg.setFrom("anonymous");   
  54.         if("".equals(msg.getMail()))msg.setMail("@");   
  55.         if("".equals(msg.getSite()))msg.setSite("-");   
  56.         if("".equals(msg.getCont()))msg.setCont("这家伙很懒,什么都没留下");   
  57.            
  58.         recordService.insertRecord(msg);   
  59.         return SUCCESS;   
  60.     }   
  61.     /**  
  62.      * 通过索引查找记录  
  63.      * @return the field msg  
  64.      * @throws Exception  
  65.      */  
  66.     public String listRecordByIndex() throws Exception{   
  67.         List<Record> list = recordService.listAllRecord();   
  68.         this.msg = list.get(this.getIndex());   
  69.            
  70.         return SUCCESS;   
  71.     }   
  72.     /**  
  73.      * 删除对应id记录  
  74.      * @return field status. in order to update view with AJAX  
  75.      * @throws Exception  
  76.      */  
  77.     public String removeRecordById() throws Exception{   
  78.         String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();   
  79.         Record r = recordService.listRecordById(msg.getId());   
  80.         if(clientIpAddr.equals(r.getIpaddr())){   
  81.             recordService.removeRecordById(msg.getId());   
  82.             return SUCCESS;   
  83.         }   
  84.         status = 4;   
  85.         return SUCCESS;   
  86.     }   
  87.        
  88.     /**  
  89.      * 获得分页数  
  90.      * @return pageSize using field page  
  91.      * @throws Exception  
  92.      */  
  93.     public String getPageSize() throws Exception{   
  94.         page = recordService.getPage();   
  95.         return SUCCESS;   
  96.     }   
  97. }</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.   
  6. <struts>  
  7. <constant name="struts.objectFactory" value="spring"/>  
  8.     <package name="json" extends="json-default">  
  9.         <action name="ajaxRequest" class="com.jun.demos.struts2json.HelloWorld">  
  10.             <result type="json" />  
  11.         </action>  
  12.         <action name="listIndexRecord" class="com.jun.demos.book.action.CrudMsgAction">  
  13.             <result type="json" />  
  14.         </action>  
  15.         <action name="listAllRecord" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecord">  
  16.             <result type="json" />  
  17.         </action>  
  18.         <action name="listAllRecordByPage" class="com.jun.demos.book.action.CrudMsgAction" method="listAllRecordByPage">  
  19.             <result type="json" />  
  20.         </action>  
  21.         <action name="insertRecord" class="com.jun.demos.book.action.CrudMsgAction" method="insertRecord">  
  22.             <result type="json" />  
  23.         </action>  
  24.         <action name="removeRecordById" class="com.jun.demos.book.action.CrudMsgAction" method="removeRecordById">  
  25.             <result type="json" />  
  26.         </action>  
  27.         <action name="getPageIndex" class="com.jun.demos.book.action.CrudMsgAction" method="getPageSize">  
  28.             <result type="json" />  
  29.         </action>  
  30.            
  31.     </package>  
  32. </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.JSONExceptioncom.googlecode.jsonplugin.JSONExceptioncom.googlecode.jsonplugin.JSONExceptioncom.googlecode.jsonplugin.JSONExceptioncom.googlecode.jsonplugin.JSONExceptioncom.googlecode.jsonplugin.JSONException: java.lang.reflect.InvocationTargetException:   
  2.   
  3. 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,也就是提供了gettersetter

sturts-plugin是通过getterXxxXxx属性串行化输出JSON到客户端,

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

就是@JSON(Serialize=false)

 

代码如:

   

   

Java代码 复制代码
  1. @JSON(serialize=false)   
  2.   
  3.     public RecordService getRecordService() {   
  4.   
  5.        return recordService;   
  6.   
  7.     }  
@JSON(serialize=false)

    public RecordService getRecordService() {

       return recordService;

    }

 

 

分享到:
评论

相关推荐

    struts2-json-plugin-2.2.3.jar

    ajax结合Struts2要用到的jar包

    struts2-json-plugin-2.3.4.jar

    这是我目前发现的最高版本2012年08月06日

    struts2-json-plugin-2.3.15.1.jar

    struts2-core-2.xx 升级为struts2-core-2.3.15.1.jar后 jsonplugin-0.32.jar需要升级为 struts2-core-2.3.15.1.jar,不然在使用ajax时候报错 java.lang.NullPointerException at org.apache.jsp.web.error_jsp._jsp...

    ajax-struts2需要的3个包

    json.js+json-lib-2.1.jar+struts2-json-plugin-2.1.8.1.jar3个ajax需要的包 ,打包发送.

    struts2.3.15.3+json+maven

    这是一个使用maven创建struts2的,并且使用ajax访问后台,后台返回json的例子。struts2的版本是2.3.15.3

    struts2+juery+ajax+json+进度条显示

    在原来的项目中集成juery的ajax功能,返回json串,结果报了一大堆版本冲突以及jar包缺失的问题,在网上查了老半天资料终于...struts2-spring-plugin-2.1.6.jar json-lib-2.1.jar jsonplugin-0.34.jar xwork-2.1.2.jar

    structs实现ajax所需的jar包:jackson.zip

    实现jackson所需要的jar开发包, commons-beanutils-1.7.0.jar, commons-collections-3.2.jar, commons-lang3-3.2.jar, ezmorph-1.0.3.jar, jackson-core-0.67.0.12.jar, ...struts2-json-plugin-2.3.8.jar

    json.rar_Java 8_ajax json jar_json jar

    J2EE开发时,ajax通信使用Json格式,json.jar是将服务器端内容打包成所需的json格式的工具包;另一个struts2-json-plugin-2.1.8.1.jar是struts框架下直接将json数据转换为JavaScript内容的工具

    SSH等jar包

    │ struts2-json-plugin-2.1.8.1.jar │ struts2-json-plugin-2.1.8.jar │ xwork-core-2.1.6.jar │ ├─upload │ commons-fileupload-1.2.1.jar │ commons-io-1.4.jar │ └─xml dom4j-1.6.1.jar jaxen-1.1...

    Struts2+Spring+Hibernate+Ehcache+AJAX+JQuery+Oracle 框架集成用户登录注册Demo工程

    3.Ajax无刷新异步调用Struts2,返回Json数据,以用户注册为例。 4.在服务端分页查询功能,优点:实时性:跳页才查询。数据量小:只加载当前页的记录进行显示。 5.单数据源配置(兼容Tomcat和Weblogic)。 6.Hibernate...

    json所需的全部jar包(共7个-亲测可用)

    json所需的全部jar包,一共7个,亲测直接放到web下面的lib里面即可使用。资源内jar包分别是: json-lib-2.3-jdk15.jar commons-beanutils-1.8.0.jar commons-collections-3.1.jar ...struts2-json-plugin-2.3.15.3.jar

    Struts 2的JSON插件

    Struts 2并没有开发新的AJAX框架,而是使用时下Java EE平台中比较流行的AJAX框架——Dojo和DWR。 最近在Musachy Barroso等同志的无私奉献下,开发了Struts 2的JSON插件(Plugin),极大地方便了我们输出JSON结果...

    struts2.0_Ajax

    在当今——Web 2.0概念铺天盖地的Internet环境下,简易的AJAX集成对于一个... &lt;br&gt;最近在Musachy Barroso等同志的无私奉献下,开发了Struts 2的JSON插件(Plugin),极大地方便了我们输出JSON结果(Result)。

    struts2+Hibernate+jauery+Ajax+Json+mysql例子

    struts2+Hibernate+jquery+Ajax+Json+mysql例子 一个部门和员工信息管理的例子,页面上的所有数据全部采用动态加载,增删改查操用全部在一个页面上实现,没有页面跳转。前台页面和后台服务器交互采用json格试传输。 ...

    jquery之ajaxfileupload异步上传插件(附工程代码)

    点我下载工程代码 由于项目需求,在处理文件... 所需环境: jquery.js ajaxfileupload.js struts2所依赖的jar包 及struts2-json-plugin-2.1.8.1.jar 编写文件上传的Action 代码如下: package com.ajaxfile.action; imp

    struts2_spring3_hibernate3_1.1

    使用技术说明: 1.使用struts2+spring3+hibernate3整合实现用户CRUD功能。 2.使用多种配置方式 A.... ... B.使用properties文件配置数据源 ... 3.ajax后台验证,使用json-plugin。 C.添加登录状态验证。

    jquery ajaxfileupload异步上传插件

    及struts2-json-plugin-2.1.8.1.jar 编写文件上传的Action package com.ajaxfile.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.ap

Global site tag (gtag.js) - Google Analytics