当前位置: 代码迷 >> Ajax >> Ajax + Struts 兑现省市联动详解
  详细解决方案

Ajax + Struts 兑现省市联动详解

热度:126   发布时间:2016-05-11 09:10:49.0
Ajax + Struts 实现省市联动详解

想实现一个省市联动菜单,断断续续研究了好长时间,现在终于通过自己的努力实现了.
过程详解:
准备工作:
一个XML文件:

xml 代码
  1. <!---->xml?version="1.0"?encoding="GBK"?>??
  2. <china>??
  3. ????<province?name="直辖市">??
  4. ????????<city>北京city>??
  5. ????????<city>上海city>??
  6. ????????<city>天津city>??
  7. ????????<city>重庆city>??
  8. ????province>??
  9. ????<province?name="广东">??
  10. ????????<city>广州city>??
  11. ????????<city>珠海city>??
  12. ????????<city>深圳city>??
  13. ????????<city>东莞city>??
  14. ????province>??
  15. ????<province?name="广西">??
  16. ????????<city>桂林city>??
  17. ????????<city>柳州city>??
  18. ????????<city>北海city>??
  19. ????????<city>南宁city>??
  20. ????province>??
  21. ????<province?name="海南">??
  22. ????????<city>海口city>??
  23. ????????<city>三亚city>??
  24. ????province>??
  25. ????<province?name="湖北">??
  26. ????????<city>武汉city>??
  27. ????????<city>鄂州city>??
  28. ????????<city>荆州city>??
  29. ????????<city>十堰city>??
  30. ????province>??
  31. ????<province?name="湖南">??
  32. ????????<city>长沙city>??
  33. ????????<city>岳阳city>??
  34. ????????<city>常德city>??
  35. ????????<city>张家界city>??
  36. ????province>??
  37. ????<province?name="浙江">??
  38. ????????<city>杭州city>??
  39. ????????<city>绍兴city>??
  40. ????????<city>宁波city>??
  41. ????????<city>台州city>??
  42. ????province>??
  43. ????<province?name="辽宁">??
  44. ????????<city>沈阳city>??
  45. ????????<city>大连city>??
  46. ????????<city>抚顺city>??
  47. ????????<city>铁岭city>??
  48. ????province>??
  49. china>??

用一个Java类来解析这个XML文件,我用的是JDOM,实现的功能为能够获取所有省份,和传入省份的集合(用于Jsp页面显示),可以获取相应的城市集合.

java 代码
  1. import?java.io.FileNotFoundException; ??
  2. import?java.io.IOException; ??
  3. import?java.util.ArrayList; ??
  4. import?java.util.List; ??
  5. import?org.jdom.Document; ??
  6. import?org.jdom.Element; ??
  7. import?org.jdom.JDOMException; ??
  8. import?org.jdom.input.SAXBuilder; ??
  9. public?class?ReadXml?{ ??
  10. ????private?Element?root?=?null; ??
  11. ???????? ??
  12. ????public?ReadXml()?throws?FileNotFoundException,?JDOMException,?IOException?{ ??
  13. ????????super(); ??
  14. ????????SAXBuilder?sb?=?new?SAXBuilder();//解析器对象 ??
  15. ????????Document?doc?=?sb.build(this.getClass().getResourceAsStream("/city.xml"));//绑定文件 ??
  16. ????????root?=?doc.getRootElement();//获取根元素 ??
  17. ????} ??
  18. ???? ??
  19. ????public?List?getProvince(){??//获取省份?????? ??
  20. ????????ArrayList?provinceList?=?new?ArrayList(); ??
  21. ????????List?tempList?=?root.getChildren();//获取所有省份节点 ??
  22. ????????for(int?i=0;?i
  23. ????????????Element?province=(Element)tempList.get(i);//子节点转型 ??
  24. ????????????provinceList.add(province.getAttributeValue("name"));//获取省份节点属性内容 ??
  25. ????????} ??
  26. ????????return?provinceList;???????? ??
  27. ????} ??
  28. ???? ??
  29. ????public?List?getCity(String?province){ ??
  30. ????????ArrayList?cityList?=?new?ArrayList(); ??
  31. ????????List?provincetemplist?=?root.getChildren();//省份集合 ??
  32. ????????for(int?i=0;?i
  33. ????????????Element?provinceElement?=?(Element)provincetemplist.get(i); ??
  34. ????????????if((provinceElement.getAttributeValue("name")).equals(province)){//如果属性为传进来的名称 ??
  35. ????????????????List?cityTempList?=?provinceElement.getChildren();//获取子节点集合 ??
  36. ????????????????for(int?j=0;?j//循环 ??
  37. ????????????????????Element?cityElement?=?(Element)cityTempList.get(j);//当前城市节点 ??
  38. ????????????????????cityList.add(cityElement.getTextTrim());//增加城市到集合??????????????????? ??
  39. ????????????????} ??
  40. ????????????} ??
  41. ????????} ??
  42. ????????return?cityList; ??
  43. ????} ??
  44. }??
准备工作完毕,建一个Struts工程
写一个Action,用来获取省份集合
java 代码
  1. public?class?GetProvinceAction?extends?Action?{ ??
  2. ???? ??
  3. ????public?ActionForward?execute(ActionMapping?mapping,?ActionForm?form, ??
  4. ????????????HttpServletRequest?request,?HttpServletResponse?response)?throws?FileNotFoundException,?JDOMException,?IOException?{ ??
  5. ????????ReadXml?rx?=?new?ReadXml(); ??
  6. ????????List?provinces?=?rx.getProvince();//获取省份 ??
  7. ????????request.setAttribute("provinces",?provinces);//放入request中 ??
  8. ????????return?mapping.findForward("success"); ??
  9. ????} ??
  10. }??

先通过此Action,然后再显示首页,这样省的下拉框里就有值了.
我先把Struts-Config.XML文件贴出来

xml 代码
  1. <form-beans>??
  2. ????<form-bean?name="selectForm"?type="com.selectdemo.struts.form.SelectForm"?/>??
  3. form-beans>??
  4. <action-mappings>??????? ??
  5. ????<!---->??
  6. ????<action?path="/getProvince"?type="com.selectdemo.struts.action.GetProvinceAction">??
  7. ????????<forward?name="success"?path="/select.jsp"/>??
  8. ????action>??
  9. ????<!---->??
  10. ????<action?path="/select"?scope="request"?input="/select.jsp"?name="selectForm"? ??
  11. ????????type="com.selectdemo.struts.action.SelectAction">??
  12. ????<forward?name="success"?path="/getProvince.do"?/>??
  13. action>??

然后是显示的JSP页面

xml 代码
  1. <[email protected]language="java"?pageEncoding="UTF-8"%>??
  2. <[email protected]uri="http://jakarta.apache.org/struts/tags-bean"??prefix="bean"%>??
  3. <[email protected]uri="http://jakarta.apache.org/struts/tags-html"??prefix="html"%>??
  4. <[email protected]uri="http://jakarta.apache.org/struts/tags-logic"?prefix="logic"%>??
  5. ??
  6. <html:html>??
  7. <head>??
  8. ????<meta?http-equiv="pragma"?content="no-cache">??
  9. ????<meta?http-equiv="cache-control"?content="no-cache">??
  10. ????<title>Insert?title?heretitle>??
  11. head>??
  12. <script?type="text/javascript">??
  13. var?xmlHttp; ??
  14. //?创建xmlHttp; ??
  15. function?createXMLHttpRequest(){ ??
  16. ????if(window.ActiveXObject){ ??
  17. ????????xmlHttp?=?new?ActiveXObject("Microsoft.XMLHTTP"); ??
  18. ????}else?if(window.XMLHttpRequest){ ??
  19. ????????xmlHttp?=?new?XMLHttpRequest(); ??
  20. ????} ??
  21. } ??
  22. ??
  23. //?删除城市选项 ??
  24. function?clearCityList(){ ??
  25. ????var?citys?=?document.getElementById("city"); ??
  26. ????while(citys.childNodes.length?>?0){ ??
  27. ????????citys.removeChild(citys.childNodes[0]); ??
  28. ????} ??
  29. } ??
  30. ??
  31. //选项省份时 ??
  32. function?selectProvince(){ ??
  33. ????var?province?=?document.getElementById("province").value;//获取省份值 ??
  34. ???? ??
  35. ????if(province?==?""){?//如果为空,则清空城市选项 ??
  36. ????????clearCityList(); ??
  37. ????????var?citySelect?=?document.getElementById("city");?//获取城市select组件 ??
  38. ????????var?option?=?document.createElement("option"); ??
  39. ????????option.appendChild(document.createTextNode("请选择城市")); ??
  40. ????????citySelect.appendChild(option); ??
  41. ????????return?;?//返回 ??
  42. ????} ??
  43. ????//服务器处理地址,是一个Servlet ??
  44. ????var?url?=?"http://localhost:8080/SelelctDemo/servlet/Linkage?province="?+?encodeURIComponent(province)?+?"&ts="?+?new?Date().getTime(); ??
  45. ????createXMLHttpRequest();//创建xmlHttp对象; ??
  46. ????xmlHttp.onreadystatechange?=?handleStateChange;?//回调函数 ??
  47. ????xmlHttp.open("GET",url,true); ??
  48. ????xmlHttp.send(null); ??
  49. } ??
  50. ??
  51. //回调函数 ??
  52. function?handleStateChange(){ ??
  53. ????if(xmlHttp.readyState?==?4){ ??
  54. ????????if(xmlHttp.status?==?200){ ??
  55. ????????????updateCitysList(); ??
  56. ????????} ??
  57. ????} ??
  58. } ??
  59. ??
  60. //页面更新城市集合函数 ??
  61. function?updateCitysList(){ ??
  62. ????clearCityList();//首先删除先前的城市选项 ??
  63. ????var?citySelect?=?document.getElementById("city");?//获取城市select组件 ??
  64. ????var?results?=?xmlHttp.responseXML.getElementsByTagName("city");//获取Ajax返回的结果,city为返回的XML里的节点 ??
  65. ????var?option?=?null; ??
  66. ????for(var?i=0;?i<results.length;?i++){???????? ??
  67. ????????option?=?document.createElement("option"); ??
  68. ????????option.appendChild(document.createTextNode(results[i].firstChild.nodeValue)); ??
  69. ????????citySelect.appendChild(option); ??
  70. ????} ??
  71. }??????? ??
  72. script>??
  73. <body>??
  74. ????<html:form?action="/select"?method="post">??
  75. ????????<logic:present?name="provinces"?scope="request">??
  76. ????????????<html:select?property="province"?styleId="province"?onchange="selectProvince();">??
  77. ????????????????<html:option?value="">请选择省份html:option>??
  78. ????????????????<html:options?name="provinces"?labelName="provinces"?/>??
  79. ????????????html:select>??
  80. ??
  81. ????????????<html:select?property="city"?styleId="city"?style="width:90px">??
  82. ????????????????<html:option?value="">请选择城市html:option>??
  83. ????????????html:select>??
  84. ????????logic:present>??
  85. ????????<html:submit>html:submit>??
  86. ????html:form>??
  87. ????<br/>省份: ??
  88. ????<logic:present?name="province"?scope="request">??
  89. ????????<bean:write?name="province"?scope="request"/>??
  90. ????logic:present>??
  91. ????<br/>城市: ??
  92. ????<logic:present?name="city"?scope="request">??
  93. ????????<bean:write?name="city"?scope="request"/>??
  94. ????logic:present>??
  95. body>??
  96. html:html>??
  97. ??

下面是按处理Ajax的Servlet

java 代码
  1. import?java.io.IOException; ??
  2. import?java.io.PrintWriter; ??
  3. import?java.util.List; ??
  4. import?javax.servlet.ServletException; ??
  5. import?javax.servlet.http.HttpServlet; ??
  6. import?javax.servlet.http.HttpServletRequest; ??
  7. import?javax.servlet.http.HttpServletResponse; ??
  8. import?org.jdom.JDOMException; ??
  9. import?com.selectdemo.tool.ReadXml; ??
  10. public?class?Linkage?extends?HttpServlet?{ ??
  11. ??
  12. ????public?void?doGet(HttpServletRequest?request,?HttpServletResponse?response) ??
  13. ????????????throws?ServletException,?IOException?{ ??
  14. ????????response.setContentType("text/html;charset=UTF-8"); ??
  15. ????????String?province?=?request.getParameter("province");?//获取参数中的值 ??
  16. ????????System.out.println(province); ??
  17. ????????ReadXml?rx; ??
  18. ????????List?citys?=?null; ??
  19. ????????try?{ ??
  20. ????????????rx?=?new?ReadXml(); ??
  21. ????????????citys?=?rx.getCity(province); ??
  22. ????????}?catch?(JDOMException?e)?{????????? ??
  23. ????????????e.printStackTrace(); ??
  24. ????????}??????? ??
  25. ????????System.out.println(citys.size()); ??
  26. ????????//组装城市选项 ??
  27. ????????StringBuffer?results?=?new?StringBuffer("<citys>"); ??
  28. ????????for(int?i=0;?i<citys.size();?i++){ ??
  29. ????????????results.append("<city>"); ??
  30. ????????????results.append(citys.get(i)); ??
  31. ????????????results.append("</city>"); ??
  32. ????????} ??
  33. ????????results.append("</citys>"); ??
  34. ????????response.setContentType("text/xml;"); ??
  35. ????????PrintWriter?pw?=?response.getWriter();?? ??
  36. ????????System.out.println(results.toString()); ??
  37. ????????pw.print(results.toString()); ??
  38. ????????pw.flush(); ??
  39. ????????pw.close(); ??
  40. ????} ??
  41. ????public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response) ??
  42. ????????????throws?ServletException,?IOException?{ ??
  43. ????????doGet(request,?response); ??
  44. ????} ??
  45. }??

Servlet处理完后,返回到JSP页面,会传给JSP页面一个XML文档,以字符串的形式传过去的,JSP页面解析这个String,从而增加城市选项的下拉列表

点击submit后,用一个Action接收,看值传进来没有

java 代码
  1. import?javax.servlet.http.HttpServletRequest; ??
  2. import?javax.servlet.http.HttpServletResponse; ??
  3. import?org.apache.struts.action.Action; ??
  4. import?org.apache.struts.action.ActionForm; ??
  5. import?org.apache.struts.action.ActionForward; ??
  6. import?org.apache.struts.action.ActionMapping; ??
  7. import?com.selectdemo.struts.form.SelectForm; ??
  8. ??
  9. public?class?SelectAction?extends?Action?{ ??
  10. ??
  11. ????public?ActionForward?execute(ActionMapping?mapping,?ActionForm?form, ??
  12. ????????????HttpServletRequest?request,?HttpServletResponse?response)?{ ??
  13. ????????response.setContentType("text/html;charset=UTF-8"); ??
  14. ????????SelectForm?sf?=?(SelectForm)form; ??
  15. ????????String?province?=?sf.getProvince(); ??
  16. ????????System.out.println(province); ??
  17. ????????String?city?=?sf.getCity(); ??
  18. ????????System.out.println(city); ??
  19. ????????request.setAttribute("province",?province); ??
  20. ????????request.setAttribute("city",?city); ??
  21. ????????return?mapping.findForward("success"); ??
  22. ????} ??
  23. }??

这里,你会发现,传进来的值会是乱码,解决乱码我写了一个MyActionServlet

java 代码
  1. import?org.apache.struts.action.ActionServlet; ??
  2. import?javax.servlet.http.HttpServletRequest; ??
  3. import?javax.servlet.http.HttpServletResponse; ??
  4. ?? ??
  5. public?class?MyActionServlet?extends?org.apache.struts.action.ActionServlet ??
  6. { ??
  7. ????protected?void?process(HttpServletRequest?request,?HttpServletResponse?response) ??
  8. ????????throws?java.io.IOException,?javax.servlet.ServletException ??
  9. ????{ ??
  10. ????????request.setCharacterEncoding("UTF-8"); ??
  11. ????????super.process(request,?response); ??
  12. ????} ??
  13. }??

?

好了,到这里后,就大功告成了.

1 楼 lightround 2007-08-05  
To:zhanghaidang

看了你的代码,能不能交流一下,我目前在用Ajax,想体验一下Ajax的好处,请不吝赐教

谢谢
2 楼 laowang_27hotmail.com 2007-08-06  
你确定把整个都贴出来了?
3 楼 zhanghengfirst 2008-03-30  
没贴全吧,,
4 楼 迷失的人 2008-04-01  
我想问问,有必要用到struts吗?直接用AJAX还不行,你这个只是双组合,如果是三组合、四组合呢,还用struts吗?直接用AJAX吧,将你的xml文件加载到客户端处理就行了。这只是我个人认为而已。
5 楼 迷失的人 2008-04-01  
还有提醒一下楼主,请将js代码封装成类的形式吧,这样对人对自己都有好出的。
6 楼 kellersoon 2008-04-01  
少web.xml  servlet用改後的 MyActionServlet

不錯!學習啦
不過我覺得沒必要用struts
個人看法
7 楼 ice123456 2008-04-01  
引用
for(int i=0; i
            Element provinceElement = (Element)provincetemplist.get(i);  
            if((provinceElement.getAttributeValue("name")).equals(province)){//如果属性为传进来的名称  
                List cityTempList = provinceElement.getChildren();//获取子节点集合  
                 for(int j=0; j//循环  
                    Element cityElement = (Element)cityTempList.get(j);//当前城市节点  
                    cityList.add(cityElement.getTextTrim());//增加城市到集合                     
                }  
            }  
        }   

如果你第一个值就查找出来,这不是在浪费资源???
直接用js读,不是更快??
  相关解决方案
本站暂不开放注册!
内测阶段只得通过邀请码进行注册!
 
  • 最近登录:Wed Mar 29 01:50:12 CST 2017
  • 最近登录:Wed Mar 29 01:50:12 CST 2017
  • 最近登录:Wed Mar 29 01:50:12 CST 2017
  • 最近登录:Wed Mar 29 01:50:12 CST 2017
  • 最近登录:Wed Mar 29 01:50:12 CST 2017