一、实现目标
首先会有一个存放中国行政区域数据的一个txt文件,用java读取并解析出来,并在页面上通过下拉框的形式展示出来。实现效果如下图,当选择完省份后,在选择该省份下的城市,然后在选择该城市下的县区这样逐级显示:
二、代码实现:
1. 先创建一个javaBean,用来存放基本数据;
public class Area {
private String code ;//行政编码
private String name;//名称
private int level;//行政级别 0:省/直辖市 1:地级市 2:县级市
private String parentCode;//上一级的行政区划代码 public Area() {
super();
} public Area(String code, String name, int level, String parentCode) {
super();
this.code = code;
this.name = name;
this.level = level;
this.parentCode = parentCode;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getLevel() {
return level;
} public void setLevel(int level) {
this.level = level;
} public String getParentCode() {
return parentCode;
} public void setParentCode(String parentCode) {
this.parentCode = parentCode;
} public String toString(){
return "行政编码:"+this.getCode()+"\t名称:"+this.getName()+"\t行政级别:"+
this.getLevel()+"\t上一级的行政区划代码:" +this.getParentCode();
}
}
2. 然后创建一个读取txt资源文件的工具类;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.***.Area; public class ReadAreaUtil { public List<Area> provinceList = new ArrayList<Area>();
public List<Area> townList = new ArrayList<Area>();
public List<Area> countyList = new ArrayList<Area>(); public Map<String,List<Area>> getAreaData(String path){
ReadAllArea(path);
Map<String,List<Area>> result = new HashMap<String,List<Area>>();
result.put("provinceList", provinceList);
result.put("townList", townList);
result.put("countyList", countyList.subList(1, countyList.size())); //去掉表头 return result ;
} public void ReadAllArea(String path){
String line = null;
BufferedReader reader = null;
File file = new File(path); String cityCode="";
String countyCode="";
try {
FileReader in = new FileReader(file);
reader = new BufferedReader(in);
//读取文件的每一行
while((line = reader.readLine())!=null){
String[] data = cutString(line); //处理读取的文件记录
if(isProvince(data[0])){
cityCode = data[0];
Area area = new Area(data[0], data[1], 0, "0");
provinceList.add(area);
}else if(isTown(data[0])){
countyCode =data[0];
Area area = new Area(data[0], data[1], 1, cityCode);
townList.add(area);
}else{
Area area = new Area(data[0], data[1], 2, countyCode);
countyList.add(area);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} //字符分割
public String[] cutString(String line){
String code="";
String name="";
code = line.substring(0, 6);
String lastStr = line.substring(7, line.length());
name = lastStr.substring(0, lastStr.indexOf("\t"));
String[] result = new String []{code,name};
return result;
} //判断是否省或者直辖市
public boolean isProvince(String code){
String last = code.substring(2);
if("0000".equalsIgnoreCase(last)){
return true;
}
return false;
}
//判断是否地级市
public boolean isTown(String code){
String last = code.substring(4);
if("00".equalsIgnoreCase(last)){
return true;
}
return false;
} }
3. 改项目使用了struts2,在action的方法中调用即可:
//读txt数据...
String path = ServletActionContext.getServletContext().getRealPath("/2015Area.txt");
Map<String,List<Area>> area = new ReadAreaUtil().getAreaData(path);
List<Area> provinceList = area.get("provinceList");
ServletActionContext.getRequest().setAttribute("prlist", provinceList);
4. JSP页面上的html,第一个select是直接遍历的,但是后面两个就要根据前面select选中的来动态显示了,这里需要用到jQuery的Ajax;
<div id="areaDiv" >
<a >省份:
<select id="sel_province" name="" >
<option value="-1" >-请选择-</option>
<c:forEach var="pro" items="${prlist }">
<option value="${pro.code }" >${pro.name }</option>
</c:forEach>
</select>
</a>
<a class="wsy_f14">城市/区:
<select id="sel_town" name="" >
<option value="-1" >-----</option>
</select>
</a>
<a class="wsy_f14">县级:
<select id="sel_county" name="" >
<option value="-1" >-----</option>
</select>
</a>
</div>
jQuery 代码,select标签变化时触发函数并发送post请求数据;
$(document).ready(function(){
$('#sel_province').change(function(){
var code = $(this).children('option:selected').val();//selected的值
$.post("${basePath}ajax/filterArea.action",
{
parentCode:code,
areaType:1//0省,1市,2县
},
function(data){
$("#sel_town").html(data);
});
}); $('#sel_town').change(function(){
var code = $(this).children('option:selected').val();//selected的值
$.post("${basePath}ajax/filterArea.action",
{
parentCode:code,
areaType:2//0省,1市,2县
},
function(data){
$("#sel_county").html(data);
});
});
});
5. struts如何处理Ajax请求,专门写一个action用于处理ajax请求;
strut.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="ajax" namespace="/ajax" extends="json-default">
<action name="filterArea" method="filterArea" class="com.llw.action.AjaxFilter"></action>
</package>
</struts>
action:
public class AjaxFilter extends ActionSupport { //行政区域过滤
private String parentCode ;
private int areaType ;
public String getParentCode() {
return parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
public int getAreaType() {
return areaType;
}
public void setAreaType(int areaType) {
this.areaType = areaType;
} public void filterArea(){
String htmlStr = "<option value=\"-1\">-请选择-</option>" ; String path = ServletActionContext.getServletContext().getRealPath("/2015Area.txt");
Map<String,List<Area>> area = new ReadAreaUtil().getAreaData(path);
List<Area> areaList = null ;
if(areaType==1){ //0省,1市,2县
areaList = area.get("townList");
}else if(areaType==2){
areaList = area.get("countyList");
}
if(areaList!=null && areaList.size()>0 && parentCode!=null){
for(Area a : areaList){
if(parentCode.equals(a.getParentCode())){
htmlStr += "<option value=\""+a.getCode()+"\">"+a.getName()+"</option>" ;
}
}
} // System.out.println("xxxxx"+htmlStr);
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.print(htmlStr);
writer.flush();
writer.close();
} }
三、总结:以上基本完成了需要的效果,用java读取txt资源文件,并封装到List里面,上面代码中把不同级别的数据放到不同的list里了,也可以放到同一个list里面,这个根据自己需要可以去修改;然后是通过Ajax方式动态逐级显示select展示的内容;并演示了strut中如何处理ajax请求。上面展示了其中一种strut处理ajax请求的方式,还有另外一中方式,跟普通action的原理类似,就是通过action里定义的成员变量,JS里的回调函数访问这些成员变量;
这里贴一下第二种方式的使用例子:
strut.xml:
<action name="testAjax" class="com.crm.action.Ajaxcustomer" method="sayHello">
<result type="json" name="success"></result>
</action> action:
public class AjaxFilter extends ActionSupport {
private int type;
private String phone;
private Map<String,Object> map ;
//…get/set方法这里省略 public String sayHello(){
map = new HashMap<String, Object>();
map.put("aaa", "abc"); return SUCCESS;
}
} JS:
function test(){
$.post("ajax/testAjax.action",//请求目标
{
type:1,
phone:$("#phone").val() },
function(data) {//回调函数
alert(data.map.aaa);
$("#lia1").html(data.map.paramNum);//设置页面标签值
});
}
四、说明:以上java读取txt资源文件的方法来自网络整理修改,后面的内容是项目中实际应用,现记以温之;