Struts2 整合jQuery实现Ajax功能(2)
1.1.1 Action利用struts2-json-plugin-X.X.X.jar响应Json格式信息:
1. 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. }
Action代码(做了简化)
1. 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.
14. /**
15. * 返回全部记录的JSON数据
16. * @return list . All of the record.
17. * @throws Exception
18. */
19. public String listAllRecord() throws Exception{
20. List<Record> list = recordService.listAllRecord();
21. records = list;
22. return SUCCESS;
23. }
24.
25. public String listAllRecordByPage() throws Exception{
26. List<Record> list = recordService.listAllRecord(page);
27. records = list;
28. return SUCCESS;
29. }
30.
31. /**
32. * 插入记录
33. * @return update the view with AJAX when struts2 action return
34. * @throws Exception
35. */
36. public String listRecordByIndex() throws Exception{
37. List<Record> list = recordService.listAllRecord();
38. this.msg = list.get( this .getIndex());
39.
40. return SUCCESS;
41. }
42. /**
43. * 删除相应id记录
44. * @return field status. in order to update view with AJAX
45. * @throws Exception
46. */
47. public String removeRecordById() throws Exception{
48. String clientIpAddr = ServletActionContext.getRequest().getRemoteAddr();
49. Record r = recordService.listRecordById(msg.getId());
50. if(clientIpAddr.equals(r.getIpaddr())){
51. recordService.removeRecordById(msg.getId());
52. return SUCCESS;
53. }
54. status = 4;
55. return SUCCESS;
56. }
57.
58. /** 获得分页数 */
59. public String getPageSize() throws Exception{
60. page = recordService.getPage();
61. return SUCCESS;
62. }
63. }
上面代码中,使用了 @JSON(serialize=false),
除此之外,@JSON还支持例如以下几个域:
name:指定Action属性被序列化成JSON对象的属性名。
serialize:设置是否序列化该属性
deserialize:设置是否反序列化该属性。
format:设置用于格式化输出、解析日期表单域的格式。比如"yyyy-MM-dd'T'HH:mm:ss"
1. < package name = "json" extends = "json-default" >
2. <action name = "ajaxRequest" class ="com.jun.demos.struts2json.HelloWorld" >
3. <result type = "json" />
4. </action >
5. <action name = "listIndexRecord" class ="com.jun.demos.book.action.CrudMsgAction" >
6. <result type = "json" />
7. </action >
8. <action name = "listAllRecord" class ="com.jun.demos.book.action.CrudMsgAction" method ="listAllRecord" >
9. <result type = "json" />
10. </action >
11. <action name = "removeRecordById" class ="CrudMsgAction" method = "removeRecordById" >
12. <result type = "json" />
13. </action >
14. <action name = "getPageIndex" class = " CrudMsgAction" method = "getPageSize" >
15. <result type = "json" />
16. </action >
17. </package >
配置该Action与配置普通Action存在小小的差别。
包继承了json-default包,而不再继承默认的default包,这是由于仅仅有在该包下才有json类型的Result。
Result能够使用 <param name="excludeProperties">page,index</param>排除Action 中这些都不返回的属性.
我们仅仅要输出person对象的name属性值,配置例如以下
1. <result type="json">
2. <param name="root">person.name</param>
3. </result>
excludeNullProperties參数:表示是否去掉空值, 默认值是false
4. <result type="json">
5. <param name="excludeNullProperties">true</param>
6. </result>
ignoreHierarchy參数:表示是否忽略等级,也就是继承关系,比方:TestAction继承于BaseAction,那么TestAction中返回的json字符串默认是不会包括父类BaseAction的属性值,ignoreHierarchy值默觉得true
7. <result type="json">
8. <param name="ignoreHierarchy">false</param>
9. </result>
includeProperties參数:输出结果中须要包括的属性值,这里正則表達式和属性名匹配,能够用“,”切割填充多个正則表達式。 如:输出person的全部属性
10. <result type="json">
11. <param name="includeProperties">person.*, person/.name</param>
12. </result>
比如:
<!-- 购房合同管理 namespace保证action的路径与jQuery兼容-->
<package
name="yushou_hetong"
extends="json-default"namespace="/pages/hetong">
<actionname="hetongAdd"class="hetongAddAction">
<result
name="list">/pages/hetong/qylist.jsp</result>
<!-- <resultname="add">/pages/hetong/add.jsp</result>
改用纯Html+jQuery-->
<result
name="add">/pages/hetong/add.html</result>
<result
name="Query">/pages/hetong/query.html</result>
<result
name="xiangmu">/pages/hetong/add/xiangmu.jsp</result>
<result
name="loupan">/pages/hetong/add/loupan.jsp</result>
<result
name="house">/pages/hetong/add/house.jsp</result>
<result
name="houseList">/pages/hetong/add/houseList.jsp</result>
<result
name="fukuan">/pages/hetong/add/fukuan.jsp</result>
<result
name= "success"
type="json"
>
<param
name="ignoreHierarchy">false</param>
<param
name="includeProperties">errmsg</param>
</result>
</action>
</package>
二级联动标签
在struts2
标签s:doubleselect二级联动标签的基础上实现事件:第二级onchange时调用struts2 action,在action中查询一个名称,然后返回回来,此信息显示在页面上(这仅仅是给用户一个提示信息,不影响表单是否能提交)
须要加事件的二级联动jsp代码
1. <td class="alignLeft" width="22%"> 所属业务/项目名称: </td>
2. <td valign="top" class="alignLeft" width="20%">
3. <s:doubleselect name="changeApplyFormBO.operationId" list="operationList" listKey="id"
4. listValue="operationName" doubleList="operationSubProductList"
5. doubleListKey="id" doubleListValue="prudName" doubleName="changeApplyFormBO.productId"
6. headerKey="" headerValue="--- Please Select ---" />
7. <span id="company" style="color:red"></span>
8. </td>
我们须要在“项目名称”被改变的事件下调用函数,在生成的静态页面中查得它的id是cbApplySubmit_changeApplyFormBO_productId
说明一下,这里生成的id有一点规律,貌似。cbApplySubmit是本页面form表单的action,而changeApplyFormBO.productId是“项目名称”的name
以下给出定制下拉菜单事件的js
1. <script>
2.
3. $(function(){
4. var obj=document.getElementById("cbApplySubmit_changeApplyFormBO_productId");
5. obj.onchange=function(){
6. var prodId=obj.value;
7. var url="${contextPath}/assets/businessChange/ajaxGetCompany.do";
8. var jsonProd={productId:prodId}; //JSON对象
9. var prodStr=JSON.stringify(jsonProd); //将JSON对象转变成JSON格式的字符串
10. $.post(url,{json:prodStr},callback,"json");
11. }
12. function callback(json){
13. $("#company").html(json.msg);
14. }
15. });
16.
17. </script>
这里,无论是从浏览器端(JS,Ajax,Jquery等)发送给server端,还是从server端(Struts的Action,Servlet等)发送回client,发送的都是JSON格式的字符串
解释例如以下:
1. var jsonProd={productId:prodId};
这句是组装JSON对象,这里非常easy,key是productId,value是页面选择的项目名称的id
1. //将JSON对象转变成JSON格式的字符串
2. var prodStr=JSON.stringify(jsonProd);
通过JavaScript内置对象JSON的stringify方法,将JSON对象转换成字符串。由于,我们传送给server端的要是JSON格式的字符串。
1. $.post(url,{json:prodStr},callback,"json");
这一句,jquery用POST方法向server端发送数据,url是我们要调用的action全路径,而{json:prodStr}是我们要发送的数据(data),{json:prodStr},事实上也是一个JSON对象,Key:value的形式,注意,我们把prodStr这个json串发过去,在Action那里接收时,要接收“json”这个变量,这个变量的值就是我们发送的prodStr字符串。
回调函数(callback)是指server端成功返回时,在JS端运行的函数。最后一个參数“json”是返回数据类型的一种,另外,还有”text”、“xml”等
function callback(json){
1. $("#company").html(json.msg);
2. }
3. });
company是span的id,请看最上面二级联动标签处。这个函数用来显示action中组装的json对象的value值
struts2 action类
1. import org.json.JSONObject;
2.
3. public class CBApplyAction extends ActionSupport {
4. private IProductMng productMng;
5. private String json;
6. /**
7. * 通过选择的项目名称,给出提示事业部名称的提示信息
8. *
9. * @return
10. * @throws Exception
11. */
12. public void ajaxGetCompany() throws Exception {
13. JSONObject jsonObj = new JSONObject(json); // 将JSON格式的字符串构造成JSON对象
14.
15. String productId = jsonObj.getString("productId"); // 获取JSON对象中的productId属性的值
16.
17. ProductBO prod = productMng.loadProduct(Integer.parseInt(productId));
18. Integer companyId = prod.getCompanyId();
19. CompanyBO comp = productMng.loadCompany(companyId);
20. String companyName = "事业部为:" + comp.getName();
21. json = "{msg:'" + companyName + "'}"; //构造JSON格式的字符串
22. sendMsg(json); //发送JSON格式的字符串回JS端
23. }
24.
25. public void sendMsg(String content) throws IOException{
26. HttpServletResponse response = ServletActionContext.getResponse();
27. response.setCharacterEncoding("UTF-8");
28. response.getWriter().write(content);
29. }
30.
31. public String getJson() {
32. return json;
33. }
34.
35. public void setJson(String json) {
36. this.json = json;
37. }
38.
39. public void setProductMng(IProductMng productMng) {
40. this.productMng = productMng;
41. }
42. }
JSONObject是我从json的站点http://www.json.org/java/index.html上下载了一些java文件,然后将这些.java文件打成一个jar包json.jar,放在项目lib里面
ajaxGetCompany方法没有像struts2 别的方法那样有返回值String,这里设的是void,因我们不须要不论什么跳转.
这里有个须要注意的,json= "{msg:'" + companyName + "'}"; companyName外面应该有引號括起来
struts2 配置文件
1. <action name="ajaxGetCompany" class="CBApplyAction"
2. method="ajaxGetCompany">
3. </action>
没有result
Struts2 整合jQuery实现Ajax功能(2)的更多相关文章
- Struts2 整合jQuery实现Ajax功能(1)
技术领域非常多东西流行,自然有流行的道理.这几天用了jQuery,深感有些人真是聪明绝顶,能将那么多技术融合的如此完美. 首先明白个概念: jQuery是什么:是使用javascript语言开发的,用 ...
- 模仿JQuery封装ajax功能
需求分析 因为有时候想提高性能,只需要一个ajax函数,不想引入较大的jq文件,尝试过axios,可是get方法不支持多层嵌套的json,post方式后台接收方式似乎要变..也许是我不太会用吧..其实 ...
- Struts2 使用jQuery实现Ajax
在jQuery中将Ajax相关的操作进行封装,使用时只需在合适的地方调用Ajax相关的方法即可,相比而言,使用jQuery实现Ajax更加简洁,方便 1.$.Ajax()可以通过发送Http请求加载远 ...
- Spring+Hibernate+Struts2整合之实现登录功能
前端代码: <form id="loginForm" action="${ pageContext.request.contextPath }/user_login ...
- 从零开始学习jQuery (六) AJAX快餐
一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案, 即使你会使用jQuery也能在阅读中发现些许秘籍. 本篇文章讲解如何使用jQuery方便快捷的实现A ...
- Jquery和Ajax的关系!
Jquery是一种JavaScript框架,而Ajax(Asynchronous JavaScript and XML)是异步JavaScript和XML. Jquery是JavaScript的框架, ...
- 份-城市,基于jQuery的AJAX二级联动,用Struts2整合AJAX【非数据库版】
package loaderman.provincecity; import java.io.IOException; import java.util.LinkedHashSet; import j ...
- Struts2处理(jQuery)Ajax请求
1. Ajax Ajax(Asynchronous JavaScript and XML,异步JavaScript和XML)时一种创建交互式网页应用的网页开发技术,它并不是一项新的技术,其产生 ...
- 3、尚硅谷_SSM高级整合_使用ajax操作实现增加员工的功能
20.尚硅谷_SSM高级整合_新增_创建员工新增的模态框.avi 1.接下来当我们点击增加按钮的时候会弹出一个员工信息的对话框 知识点1:当点击新增的时候会弹出一个bootstrap的一个模态对话框 ...
随机推荐
- FPGA 时序问题
近期 做一个项目------4个 1080p(1920 x 1080) 合成 一个 4K(3840 x 2160,297M)的接口板.当 1080p 进去, 1080p出来的时候,视频正常 播放出来. ...
- phonegap+emberjs+python手机店发展,html5实现本地车类别~
商城开发项目,现在需要做出APP,无奈出场前android但不是很精通.最后选择phonegap实现app. 由于之前办理购物车分为登陆和登陆后两种情况,登录前必须充分利用本地存储.而基于phoneg ...
- 对比Windows 8模拟器(Simulator)和Windows Phone仿真器(Emulator)
原文:对比Windows 8模拟器(Simulator)和Windows Phone仿真器(Emulator) 从事移动应用开发,经常会用到模拟器(Simulator)和仿真器(Emulator),本 ...
- 浅谈web网站架构演变过程(转)
前言 我们以javaweb为例,来搭建一个简单的电商系统,看看这个系统可以如何一步步演变. 该系统具备的功能: 用户模块:用户注册和管理 商品模块:商品展示和管理 交易模块:创建交易和管理 阶 ...
- 求n阶勒让德多项式
Time Limit: 1 Sec Memory Limit: 128 MB Submit: 161 Solved: 105 [Submit][Status][Web Board] Descrip ...
- Caused by: org.springframework.beans.factory.BeanCreationException
1.错误原因 2014-7-13 17:36:57 org.apache.jasper.compiler.TldLocationsCache tldScanJar 信息: At least one J ...
- 初步swift语言学习笔记6(ARC-自己主动引用计数,内存管理)
笔者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/31824179 转载请注明出处 假设认为文章对你有所帮助.请通过留言 ...
- 从源代码分析modelDriven拦截器和params拦截器和拦截器prepare 和paramsPrepareParamsStack拦截器栈(让你的Struts2代码更简洁——如何培养框架设计能力
源代码文件:Web App Libraries/struts2-core-2.3.15.3.jar/struts-default.xml 拦截器modelDriven: <interceptor ...
- HDU-4628 Pieces 如压力DP
鉴于他的字符串,每一个都能够删除回文子串.子可以是不连续,因此,像更好的模拟压力.求删除整个字符串需要的步骤的最小数量. 最大长度为16,因此不能逐行枚举状态.首先预处理出来全部的的回文子串,然后从第 ...
- Gradle 2.0用户手册——总览(译)(转)
2.1 特性 本章将介绍一系列Gradle的特性. 申明式构建和基于约定的构建 Gradle的核心是基于Groovy呈现了一种丰富的针对特定领域的语言,称之为Domain Specific Langu ...