博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
三、在JSP页面对LIST对象级联显示
阅读量:4097 次
发布时间:2019-05-25

本文共 7084 字,大约阅读时间需要 23 分钟。

        在项目中

        有需求对后台传过来的List 对象,在jsp进行级联操作,写了几种实现的方式,

现保存实现步骤如下,以便日后使用。

=================================================

         //    省list    省里有cities    city里有areas

        省 (id,name,cities) 市 (id,name,areas) 区(id,name) 

========

一 、 异步获取:

=========================

JSP:

*所在地区:
 
js:
 
action:
public String loadCity() throws Exception	{		HttpServletRequest request = ServletActionContext.getRequest();		String provinceId = request.getParameter("provinceId");		Province province = provinceService.getById(Integer.valueOf(provinceId));		Set
citySet = province.getCities(); //把citySet集合转成Json传给页面 //只取得City的id和name属性 SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); Set
set = filter.getIncludes(); set.add("id"); set.add("name"); writeHtml(JSONArray.toJSONString(citySet,filter)); return null; } public String loadArea() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String cityId = request.getParameter("cityId"); City city = cityService.getById(Integer.valueOf(cityId)); Set
areaSet = city.getAreas(); //把areaSet集合传给页面 //只选取Area的name和id和code属性 SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); Set
set = filter.getIncludes(); set.add("id"); set.add("name"); writeHtml(JSONArray.toJSONString(areaSet,filter)); return null; } //返回strData结果给页面 protected void writeHtml(String strData) throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/json;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.write(strData); out.flush(); out.close(); }
 

========

二 、 遍历Action的属性provinceList 获取:

=========================

 jsp:在隐藏域保存遍历list
 js:
$(function(){	$("#provinceList").change(function (){		var value = $(this).val();          $("#cityList").html("");          $("input[name^='province_"+value+"']").each(function(){              var val = $(this).val();              $("#cityList").append("");          });        $("#areaList").html(""); 	});	$("#cityList").change(function (){		var value = $(this).val();  		$("#areaList").html("");           $("input[name^='city_"+value+"']").each(function(){              var val = $(this).val();              $("#areaList").append("");          });	});});
 
 

========

三 、 Action中将provinceList 转成JSON字符串传给页面保存:

=========================

 jsp:
<%-- 直接在js里保存后台传来JSON的字符串 页面无需保存
--%>
 js:将后台传来的字符串保存到js对象中
$(function(){	var provinceJSONString = $("#provinceJSONString").val();//将java的String对象转成js字符对象	var provinceJSON = eval('('+provinceJSONString+')');//转换为json对象 	/**	 * 首次加载页面,填充province列表	 * 加载一级列表	 */	loadOptions(provinceJSON,$("#provinceList"));		function loadOptions(data,item){		$.each(data, function(index,value){				item.append($("").val(index+1).text(value.name));			});	}	/**	 * 加载二级列表	 */	$("#provinceList").change(function (){		var value = $(this).val();          $("#cityList").html("");          loadOptions(provinceJSON[value-1].cities,$("#cityList"));        $("#areaList").html(""); 	});
 
action:将provinceList转成JSON格式的字符串
/** * provinceList转成JSON字符串 * @param _provinceList * @return * @throws Exception */public static String toProvinceJSONString(List
_provinceList) throws Exception{ if (_provinceList == null) return null; Iterator
itrProvince = _provinceList.iterator(); StringBuffer strBuffer = new StringBuffer("["); while(itrProvince.hasNext()) { Province _province = itrProvince.next(); strBuffer.append("{\"id\":\""+_province.getId()+"\",\"name\":\""+_province.getName()+"\",\"cities\":["); Set
Cities = _province.getCities(); Iterator
itrCity = Cities.iterator(); while(itrCity.hasNext()) { City _city = itrCity.next(); strBuffer.append("{\"id\":"+_city.getId()+",\"name\":\""+_city.getName()+"\",\"areas\":["); Set
Areas = _city.getAreas(); Iterator
itrArea = Areas.iterator(); while(itrArea.hasNext()) { Area _area = itrArea.next(); strBuffer.append("{\"id\":\""+_area.getId()+"\",\"name\":\""+_area.getName()+"\"}"); if (itrArea.hasNext()) { strBuffer.append(","); } } strBuffer.append("]}"); if (itrCity.hasNext()) { strBuffer.append(","); } } strBuffer.append("]}"); if (itrProvince.hasNext()) { strBuffer.append(","); } } strBuffer.append("]"); return strBuffer.toString();}
 
------------------------------------------
-------------------------------------------------------------------------------------
更新---》
----------------------------------------
对省市区 JSON 字符串格式做更改:
// 得到全部省份list	static List
allProvince; static String allProvinceJSONString; public static List
getAllProvince() { if (allProvince != null) return allProvince; ProvinceService provinceService = (ProvinceService) ServletToBeanProxy .getBean("ProvinceService"); allProvince = provinceService.getAll(new String[] { "id" }); return allProvince; } public static String getAllProvinceJSONString() { if (allProvinceJSONString != null) return allProvinceJSONString; List
allProvince = getAllProvince(); StringBuffer strBuffer = new StringBuffer("{"); for (Province province : allProvince) { strBuffer.append("\"" + province.getId() + "\":{\"name\":\"" + province.getName() + "\",\"cities\":{"); /*CityService cityService = (CityService) ServletToBeanProxy .getBean("CityService"); List
cities = cityService.getByField("province", province);*/ Set
cities = province.getCities(); for (City city : cities) { strBuffer.append("\"" + city.getId() + "\":{\"name\":\"" + city.getName() + "\",\"areas\":{"); /*AreaService areaService = (AreaService) ServletToBeanProxy .getBean("AreaService"); List
areas = areaService.getByField("city", city);*/ Set
areas = city.getAreas(); for (Area area : areas) strBuffer.append("\"" + area.getId() + "\":{\"name\":\"" + area.getName() + "\"},"); if (areas != null && areas.size() > 0) strBuffer.deleteCharAt(strBuffer.length() - 1); strBuffer.append("}},"); } if (cities != null && cities.size() > 0) strBuffer.deleteCharAt(strBuffer.length() - 1); strBuffer.append("}},"); } if (allProvince != null && allProvince.size() > 0) strBuffer.deleteCharAt(strBuffer.length() - 1); strBuffer.append("}"); allProvinceJSONString = strBuffer.toString(); return allProvinceJSONString; }
jsp页面对后台 传过来的json字符串处理更改:
                        
                   
需要引入json2.js
<%	String path = request.getContextPath();	request.setAttribute("path", path);	String provinceJSONString = CommonService.getAllProvinceJSONString();%>
 

转载地址:http://chlii.baihongyu.com/

你可能感兴趣的文章
ES7的Async/Await
查看>>
每个人都能做的网易云音乐[vue全家桶]
查看>>
Vue2.0全家桶仿腾讯课堂(移动端)
查看>>
React+Redux系列教程
查看>>
19 个 JavaScript 常用的简写技术
查看>>
iOS应用间相互跳转
查看>>
iOS开发 支付之银联支付集成
查看>>
iOS开发支付集成之微信支付
查看>>
浅谈JavaScript--声明提升
查看>>
React非嵌套组件通信
查看>>
Websocket 使用指南
查看>>
浏览器兼容性问题解决方案 · 总结
查看>>
一个很棒的Flutter学习资源列表
查看>>
为什么你应该放弃React老的Context API用新的Context API
查看>>
Koa2初体验
查看>>
Koa 2 初体验(二)
查看>>
Koa2框架原理解析和实现
查看>>
vue源码系列文章good
查看>>
你不知道的Virtual DOM
查看>>
VUE面试题总结
查看>>