省市区三级联动

1、加载省份数据

1.1、方式一:Js+数组

test.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/input.css" />
<title>js+数组</title>
<!--css,js-->
<style type="text/css">
#box {
    width: 640px;
    height: 100px;
    margin: 100px auto;
}
</style>
</head>
<body>


    <div id="box">
        <span class="tip">省份:</span><select name="" id="province">
            <option>--请选择省份---</option>
        </select> <span class="tip">城市:</span><select name="" id="city">
            <option>--请选择省份---</option>
        </select> <span class="tip">区域:</span><select name="" id="area">
            <option>--请选择省份---</option>
        </select>
    </div>

    <!-- 引入jquery官方类库 -->
    <script src="js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        // 省份数组
        var provinceArr = [ {
            "id" : 110000,
            "name" : "北京市"
        }, {
            "id" : 120000,
            "name" : "天津市"
        }, {
            "id" : 130000,
            "name" : "河北省"
        }, {
            "id" : 140000,
            "name" : "山西省"
        }, {
            "id" : 150000,
            "name" : "内蒙古自治区"
        }, {
            "id" : 210000,
            "name" : "辽宁省"
        }, {
            "id" : 220000,
            "name" : "吉林省"
        }, {
            "id" : 230000,
            "name" : "黑龙江省"
        }, {
            "id" : 310000,
            "name" : "上海市"
        }, {
            "id" : 320000,
            "name" : "江苏省"
        }, {
            "id" : 330000,
            "name" : "浙江省"
        }, {
            "id" : 340000,
            "name" : "安徽省"
        }, {
            "id" : 350000,
            "name" : "福建省"
        }, {
            "id" : 360000,
            "name" : "江西省"
        }, {
            "id" : 370000,
            "name" : "山东省"
        }, {
            "id" : 410000,
            "name" : "河南省"
        }, {
            "id" : 420000,
            "name" : "湖北省"
        }, {
            "id" : 430000,
            "name" : "湖南省"
        }, {
            "id" : 440000,
            "name" : "广东省"
        }, {
            "id" : 450000,
            "name" : "广西壮族自治区"
        }, {
            "id" : 460000,
            "name" : "海南省"
        }, {
            "id" : 500000,
            "name" : "重庆市"
        }, {
            "id" : 510000,
            "name" : "四川省"
        }, {
            "id" : 520000,
            "name" : "贵州省"
        }, {
            "id" : 530000,
            "name" : "云南省"
        }, {
            "id" : 540000,
            "name" : "西藏自治区"
        }, {
            "id" : 610000,
            "name" : "陕西省"
        }, {
            "id" : 620000,
            "name" : "甘肃省"
        }, {
            "id" : 630000,
            "name" : "青海省"
        }, {
            "id" : 640000,
            "name" : "宁夏回族自治区"
        }, {
            "id" : 650000,
            "name" : "新疆维吾尔自治区"
        }, {
            "id" : 710000,
            "name" : "台湾省"
        }, {
            "id" : 810000,
            "name" : "香港特别行政区"
        }, {
            "id" : 820000,
            "name" : "澳门特别行政区"
        } ];

        // 第一种方式:Js+数组,
        // 循环当前数组

        var html = "";
        for (var i = 0, len = provinceArr.length; i < len; i++) {
            html += "<option value='"+provinceArr[i].id+"'>"
                    + provinceArr[i].name + "</option>";
        }
        $("#province").html(html);
    </script>

</body>
</html>

页面效果:

省市区三级联动_第1张图片

1.2、方式二:jquery+json

test.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/input.css" />
<title>js+json</title>
<!--css,js-->
<style type="text/css">
#box {
    width: 640px;
    height: 100px;
    margin: 100px auto;
}
</style>
</head>
<body>


    <div id="box">
        <span class="tip">省份:</span><select name="" id="province">
            <option>--请选择省份---</option>
        </select> <span class="tip">城市:</span><select name="" id="city">
            <option>--请选择省份---</option>
        </select> <span class="tip">区域:</span><select name="" id="area">
            <option>--请选择省份---</option>
        </select>
    </div>

    <!-- 引入jquery官方类库 -->
    <script src="js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        // 第二种方式:ajax+json
        var html = "";
        $.get("http://localhost/TLbs/pca/province.json", function(data) {
            // alert(data);
            for (var i = 0, len = data.length; i < len; i++) {
                html += "<option value='"+data[i].id+"'>" + data[i].name
                        + "</option>";
            }
            $("#province").html(html);
        });
    </script>

</body>
</html>

页面效果:

省市区三级联动_第2张图片

2、实现联动效果

2.1、利用Servlet处理数据

cityServlet.java

package com.matrix.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import com.matrix.dao.CityDao;

public class CityServlet extends HttpServlet {

    /**
     * 开发流程: 
     * 1、新建一个dao对象,定义curd操作
     * 2、进行测试 
     * 3、进行servlet/jsp的对接 、
     * 4、返回 
     * 5、解析
     * 
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // doGet(request, response);
        // 获取传递过来的省份id
        // 省份id
        String pid = request.getParameter("pid");
        // 根据省份id查询城市
        List<HashMap<String, Object>> maps = new CityDao().findCitys(new Long(pid));
        // 获取浏览器的输出流
        PrintWriter out = response.getWriter();
        // 将数据返回给浏览器
        try {
            out.print(JSONUtil.serialize(maps));// json
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 刷新输出流
        out.flush();
        // 关闭输出流
        out.close();
    }

}

CityServlet.java

package com.matrix.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import com.matrix.dao.CityDao;

public class CityServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // doGet(request, response);
        // 获取传递过来的省份id
        // 省份id
        String pid = request.getParameter("pid");
        // 根据省份id查询城市
        List<HashMap<String, Object>> maps = new CityDao().findCitys(new Long(pid));
        // 获取浏览器的输出流
        PrintWriter out = response.getWriter();
        // 将数据返回给浏览器
        try {
            out.print(JSONUtil.serialize(maps));// json
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 刷新输出流
        out.flush();
        // 关闭输出流
        out.close();
    }

}

2.2、注册Servlet

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>TLbs</display-name>

    <!-- 注册Servlet -->
    <servlet>
        <servlet-name>cityServlet</servlet-name>
        <servlet-class>com.matrix.web.CityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cityServlet</servlet-name>
        <url-pattern>/city</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>areaServlet</servlet-name>
        <servlet-class>com.matrix.web.AreaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>areaServlet</servlet-name>
        <url-pattern>/area</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

2.3、编写拦截器进行编码统一处理

CharacterFilter.java

package com.matrix.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一拦截编码数
 * 
 * CharacterFilter<BR>
 * 创建人:Matrix <BR>
 * 时间:2016年2月22日-下午5:13:18 <BR>
 * 
 * @version 1.0.0
 *
 */
public class CharacterFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        // 统一进行编码处理
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 放行
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}

2.4、注册拦截器

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>TLbs</display-name>


    <!-- 注册Servlet -->
    <servlet>
        <servlet-name>cityServlet</servlet-name>
        <servlet-class>com.matrix.web.CityServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cityServlet</servlet-name>
        <url-pattern>/city</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>areaServlet</servlet-name>
        <servlet-class>com.matrix.web.AreaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>areaServlet</servlet-name>
        <url-pattern>/area</url-pattern>
    </servlet-mapping>

    <!-- 注册拦截器 -->
    <filter>
        <filter-name>characterFilter</filter-name>
        <filter-class>com.matrix.core.CharacterFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

2.5、创建CityDao、AreaDao类进行数据库操作

CityDao.java

package com.matrix.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import net.sf.json.util.JSONUtils;

public class CityDao {

    public List<HashMap<String, Object>> findCitys(Long pid) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        List<HashMap<String, Object>> citys = null;
        try {
            String sql = "select id,cityname from t_city where status = ?";
            // 获取连接对象
            connection = ConnectionUtil.getConnection();
            // 处理对象
            statement = connection.prepareStatement(sql);
            statement.setLong(1, pid);
            // 返回结果集
            rs = statement.executeQuery();
            // 遍历结果集
            citys = new ArrayList<>();// jdk7出现了一种菱形泛型
            HashMap<String, Object> city = null;
            while (rs.next()) {
                city = new HashMap<String, Object>();
                city.put("id", rs.getString("id"));
                city.put("name", rs.getString("cityname"));
                citys.add(city);
            }
            return citys;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            ConnectionUtil.closeResultSet(rs, statement, connection);
        }
    }

    public static void main(String[] args) throws JSONException {
        List<HashMap<String, Object>> maps = new CityDao().findCitys(220000L);
        // json字符串转json(json-lib谷歌公司提供json转换的包)
        // System.out.println(maps);
        System.out.println(JSONUtil.serialize(maps));

        // String jsonstring =
        // "[{\"id\":10,\"age\":20},{\"id\":20,\"age\":40}]";
        // List<HashMap<String, Object>> map2 = (List<HashMap<String, Object>>)
        // (List<HashMap<String, Object>>) JSONUtil
        // .deserialize(jsonstring);
        // for (HashMap<String, Object> hashMap : map2) {
        // System.out.println(hashMap.get("id") + "====" + hashMap.get("age"));
        // }

    }
}

AreaDao.java

package com.matrix.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import net.sf.json.util.JSONUtils;

public class AreaDao {

    /**
     * 
     * 描述:根据城市查找区域<BR>
     * 方法名:findAreas<BR>
     * 创建人:Matrix <BR>
     * 时间:2016年2月23日-上午12:30:48 <BR>
     * 
     * @param pid
     * @return List<HashMap<String,Object>><BR>
     * @exception <BR>
     * @see
     * @since 1.0.0
     */
    public List<HashMap<String, Object>> findAreas(Long cid) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        List<HashMap<String, Object>> areas = null;
        try {
            String sql = "select id,area from t_area where city_id = ?";
            // 获取连接对象
            connection = ConnectionUtil.getConnection();
            // 处理对象
            statement = connection.prepareStatement(sql);
            statement.setLong(1, cid);
            // 返回结果集
            rs = statement.executeQuery();
            // 遍历结果集
            areas = new ArrayList<>();// jdk7出现了一种菱形泛型
            HashMap<String, Object> area = null;
            while (rs.next()) {
                area = new HashMap<String, Object>();
                area.put("id", rs.getString("id"));
                area.put("name", rs.getString("area"));
                areas.add(area);
            }
            return areas;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            ConnectionUtil.closeResultSet(rs, statement, connection);
        }
    }

    public static void main(String[] args) throws JSONException {
        List<HashMap<String, Object>> maps = new AreaDao().findAreas(110100L);
        System.out.println(JSONUtil.serialize(maps));
    }
}

2.6、展示页面

test.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/input.css" />
<title>js+json</title>
<!--css,js-->
<style type="text/css">
#box {
    width: 640px;
    height: 100px;
    margin: 100px auto;
}
</style>
</head>
<body>


    <div id="box">
        <span class="tip">省份:</span><select name="" id="province"
            onchange="changeCity(this.value);">
            <option>--请选择省份---</option>
        </select> <span class="tip">城市:</span><select name="" id="city"
            onchange="changeArea(this.value);">
            <option>--请选择城市---</option>
        </select> <span class="tip">区域:</span><select name="" id="area">
            <option>--请选择区域---</option>
        </select>
    </div>

    <!-- 引入jquery官方类库 -->
    <script src="js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        // 第二种方式:ajax+json

        function loadProvince() {
            var html = "<option>--请选择省份---</option>";
            $.get("http://localhost/TLbs/pca/province.json", function(data) {
                // alert(data);
                for (var i = 0, len = data.length; i < len; i++) {
                    html += "<option value='"+data[i].id+"'>" + data[i].name
                            + "</option>";
                }
                $("#province").html(html);
            });
        }

        loadProvince();

        // onchange事件:元素发生改变的时候才触发
        // 省份改变城市
        function changeCity(pid) {
            // alert(pid);
            // http://localhost/TLbs/city?pid=220000
            if (pid == "") {
                return;
            }
            $.ajax({
                type : "post",
                url : "http://localhost/TLbs/city",
                data : {
                    pid : pid
                },
                success : function(data) {
                    // alert(data);
                    // console.log(pid + "对应的城市;===============" + data);
                    // alert(typeof data);输出string类型

                    // java -- jsonstring -- list#map 通过JSONUtil工具  jsonUtil.serialze 序列化
                    // java -- list#map -- jsonstring 通过JSONUtil工具  jsonUtil.desearialze 反序列化

                    // 第一种方式:ie678不支持
                    var json = JSON.parse(data);
                    //  alert(typeof json);
                    // js中---jsonstring----json---JSON.parse(jsonstring) 浏览器内置
                    // js中 ---json------jsonstring-------JSON.stringify(json) 浏览器内置

                    // 第二种方式:都支持ie678
                    var json = eval("(" + data + ")");
                    // alert(json);
                    var html = "<option>--请选择城市---</option>";
                    for (var i = 0, len = json.length; i < len; i++) {
                        html += "<option value='"+json[i].id+"'>"
                                + json[i].name + "</option>";
                    }
                    $("#city").html(html);
                }
            });
        }

        // 城市改变区域
        function changeArea(cid) {
            // alert(pid);
            // http://localhost/TLbs/area?cid=110100
            if (cid == "") {
                return;
            }
            $.ajax({
                type : "post",
                url : "http://localhost/TLbs/area",
                data : {
                    cid : cid
                },
                success : function(data) {
                    // 第二种方式:都支持ie678
                    var json = eval("(" + data + ")");
                    var html = "<option>--请选择区域---</option>";
                    for (var i = 0, len = json.length; i < len; i++) {
                        html += "<option value='"+json[i].id+"'>"
                                + json[i].name + "</option>";
                    }
                    $("#area").html(html);
                }
            });
        }

        // json和json2都是一个意思
        // var json = {
        //  id : 1
        // };
        // var json2 = {
        //  "id" : 1
        // };
    </script>

</body>
</html>

运行效果:

省市区三级联动_第3张图片

你可能感兴趣的:(省市区三级联动)