Struts2,AJAX,json-plugin使用
2009-09-02 17:41
381 查看
代码请参照
http://acheron.javaeye.com/admin/blogs/402499
JSON
官方文档
http://www.json.org/json-zh.html
jQuery
官方文档
http://docs.jquery.com/Main_Page
Js代码
<span style=
"font-size: small;"
>
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"
);
}
});
};</span>
注意dataType:"json"这个参数一定不能少,否则不能正确识别
一下是Struts action代码
Java代码
<span style=
"font-size: small;"
>
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;
}
}</span>
在上面代码中,使用了JSON注释@JSON(serialize=false),
除此之外,JSON注释还支持如下几个域:
name:指定Action属性被序列化成JSON对象的属性名。
serialize:设置是否序列化该属性
deserialize:设置是否反序列化该属性。
format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。
Xml代码
<
span
style
=
"font-size: small;"
>
<?
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
>
</
span
>
配置该Action与配置普通Action存在小小的区别。
包继承了json-default包,而不再继承默认的default包,这是因为只有在该包下才有json类型的Result。
result可以使用
<param name="excludeProperties">page,index</param>
排除
Action
中
这些都不返回的属性.
结合action中属性getter方法注解@JSON(serialize=false)灵活配置
异常解决:
Xml代码
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代码
@JSON
(serialize=
false
)
public
RecordService getRecordService() {
return
recordService;
}
http://acheron.javaeye.com/admin/blogs/402499
JSON
官方文档
http://www.json.org/json-zh.html
jQuery
官方文档
http://docs.jquery.com/Main_Page
Js代码
<span style=
"font-size: small;"
>
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"
);
}
});
};</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代码
<span style=
"font-size: small;"
>
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;
}
}</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代码
<
span
style
=
"font-size: small;"
>
<?
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
>
</
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代码
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
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代码
@JSON
(serialize=
false
)
public
RecordService getRecordService() {
return
recordService;
}
相关文章推荐
- J2EE下使用AJAX(五) jsonplugin -- struts2下的AJAX插件
- J2EE下使用AJAX(五) jsonplugin -- struts2下的AJAX插件
- J2EE下使用AJAX:jsonplugin -- struts2下的AJAX插件
- Struts2下使用jsonplugin及jquery完成ajax功能
- struts2发送ajax的几个问题(不使用struts2-json-plugin的情况下)
- Struts2下使用jsonplugin及jquery完成ajax功能
- Struts2 ajax json使用介绍
- 使用struts2 的jsonplugin插件与opensessioninview和hibernate延迟加载时遇到的问题
- Struts2,Spring,Struts2 JSON-plugin,JQueryAJAX on GAE
- struts2之使用JSON插件实现Ajax(处理枚举类型)
- 关于使用struts2-json-plugin 插件,Json返回List对象数据为空解决方案
- Struts2 ajax json使用介绍
- 使用 Struts2 JSON plugin ( Struts2 + jQuery )
- struts2中使用json格式ajax与后端action交互
- Struts2引用的jar包版本为2.0.9的,该版本没有json包,如何使用ajax返回json数据到页面
- 【SSH三大框架】Struts2基础第八篇:Struts2用AJAX实现JSON插件的使用
- struts2之使用JSON插件实现Ajax(在struts.xml中处理要序列化的属性)
- Struts2-json-plugin 的使用(翻译自官方文档)
- struts2 + ajax + json的结合使用,实例讲解
- Struts2-Json-Plugin 的使用(翻译自官方文档)