三级联动查询全国省市区(xml与数据库)

提供有china.xml和china.sql文件,实现全国省市区的三级联动效果

一、xml实现

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JLabel;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultComboBoxModel;

@SuppressWarnings("serial")
public class ChinaJFrame extends JFrame {

private JPanel contentPane;
    private List<String> cityList=null;
    private List<String> provinceList=null;
    private List<String> countyList=null;
    @SuppressWarnings("rawtypes")
    private JComboBox provinceComboBox, cityComboBox, countyComboBox;
    SAXReader reader = new SAXReader();
    Document document = null;
    List<String> list=null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChinaJFrame frame = new ChinaJFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     *
     * @throws DocumentException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ChinaJFrame() throws DocumentException {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

provinceComboBox = new JComboBox();
        provinceComboBox.setModel(new DefaultComboBoxModel(new String[] { "省份" }));
        provinceComboBox.setBounds(33, 106, 108, 21);
        
        cityComboBox = new JComboBox();
        cityComboBox.setBounds(171, 106, 108, 21);
        cityComboBox.setModel(new DefaultComboBoxModel(new String[] { "地级市" }));
        
        countyComboBox = new JComboBox();
        countyComboBox.setBounds(302, 106, 108, 21);
        countyComboBox.setModel(new DefaultComboBoxModel(new String[] { "市、县级市" }));
        
        
        provinceList = getProvince("province");
        for (String s : provinceList) {
            provinceComboBox.addItem(s);
        }
        
        provinceComboBox.addItemListener(new ItemListener() {

@Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    int ProvinceIndex = provinceComboBox.getSelectedIndex();
                    cityList = getCity(ProvinceIndex);    
                    cityComboBox.removeAllItems();
                    for (String s : cityList) {
                        cityComboBox.addItem(s);
                    }
                }
            }
        });
        
        cityComboBox.addItemListener(new ItemListener() {
            
            @Override
            public void itemStateChanged(ItemEvent e) {
                
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityComboBox=(JComboBox) e.getSource();
                    String name2=(String) cityComboBox.getSelectedItem();
                    countyList=getCounty(name2);
                    
                    countyComboBox.removeAllItems();
                    for(String cl:countyList){
                        countyComboBox.addItem(cl);
                    }
                }
                
            }
        });
        
        JLabel lblNewLabel = new JLabel(
                "\u5168\u56FD\u57CE\u5E02\u4E09\u7EA7\u8054\u52A8");
        lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 25, 160, 48);

contentPane.add(provinceComboBox);
        contentPane.add(cityComboBox);
        contentPane.add(countyComboBox);
        contentPane.add(lblNewLabel);
    }

@SuppressWarnings("unchecked")
    public List<String> getProvince(String name) {
        list = new ArrayList<String>();
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        for(Iterator<Element> i = root.elementIterator(name); i.hasNext();) {
            Element node = i.next();
            List<Attribute> attrs = node.attributes();
            if (attrs != null) {
                for (Attribute attr : attrs) {
                    list.add(attr.getValue());
                }
            }
        }
        return list;
    }

@SuppressWarnings("unchecked")
    public List<String> getCity(int index) {
        list = new ArrayList<String>();
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        List<Element> elements1 = elements.get(index-1).elements();
        for (int i=0; i < elements1.size(); i++) {
            List<Attribute> attrs = elements1.get(i).attributes();
            if (attrs != null) {
                for (Attribute attr : attrs) {
                    list.add(attr.getValue());
                }
            }
        }
        return list;

}

@SuppressWarnings("unchecked")
    public List<String> getCounty(String name2){
        list = new ArrayList<String>();
        
        try {
            document = reader.read(new File("src/china.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        ////province[@name=‘北京市‘]
        List<Node> nodes = document.selectNodes("//city[@name=‘" + name2 + "‘]//county//@name");
        for (Node node : nodes) {
            list.add(node.getText());
        }
        return list;

}
}

二、数据库实现

(1)数据库连接的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 指定名称的配置 -->
    <named-config name="oa">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/china</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="maxPoolSize">100</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="acquireIncrement">5</property>
    </named-config>
    <!-- 缺省的配置 -->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/china</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="maxPoolSize">100</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="acquireIncrement">5</property>
    </default-config>
</c3p0-config>

(2)实体Bean

public class Province {//省
    private Integer id;
    private String name;

}

public class City {//市
    private Integer id;
    private String name;
    private Integer p_id;

}

public class County {//区
    private Integer id;
    private String name;
    private Integer c_id;

}

(3)数据库操作接口定义和实现

public interface ChinaDao<T> {
    List<T> getObjects();
    List<T> getCityObjectsById(Integer id);
    List<T> getCountyObjectsById(Integer id);
    City getIdByName(String name);
}

public class ChinaDaoImpl<T> implements ChinaDao<T>{
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(DBConn.getDataSourse());
    private List<T> entities=null;

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getObjects() {
        String sql="select id, name from province";
        entities=jdbcTemplate.query(sql, new RowMapper(){

@Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                Province province=new Province();
                province.setId(rs.getInt("id"));
                province.setName(rs.getString("name"));
                return province;
            }
            
        });
        return entities;
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getCityObjectsById(Integer id) {
        String sql="select id, name ,p_id from city where p_id=?";
        entities=jdbcTemplate.query(sql, new Object[]{id},new RowMapper(){
            @Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                City city=new City();
                city.setId(rs.getInt("id"));
                city.setName(rs.getString("name"));
                city.setP_id(rs.getInt("p_id"));
                return city;
            }
            
        });
        return entities;
    }

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List<T> getCountyObjectsById(Integer id) {
        String sql="select id, name ,c_id from county where c_id=?";
        entities=jdbcTemplate.query(sql, new Object[]{id},new RowMapper(){

@Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                County county=new County();
                county.setId(rs.getInt("id"));
                county.setName(rs.getString("name"));
                county.setC_id(rs.getInt("c_id"));
                return county;
            }
            
        });
        return entities;
    }

@SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public City getIdByName(String name) {
        String sql="select id, name ,p_id from city where name=?";
        City entity=jdbcTemplate.queryForObject(sql, new Object[]{name},new RowMapper(){
            @Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                City city=new City();
                city.setId(rs.getInt("id"));
                city.setName(rs.getString("name"));
                city.setP_id(rs.getInt("p_id"));
                return city;
            }    
        });
        return entity;
    }
}

(4)具体实现

public class ChinaJFrame extends JFrame {
    private ChinaDao chinaDao=new ChinaDaoImpl();
    private JPanel contentPane;
    private List<String> cityList=null;
    private List<String> provinceList=null;
    private List<String> countyList=null;
    @SuppressWarnings("rawtypes")
    private JComboBox provinceComboBox, cityComboBox, countyComboBox;
    SAXReader reader = new SAXReader();
    Document document = null;
    List<String> list=null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChinaJFrame frame = new ChinaJFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     *
     * @throws DocumentException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public ChinaJFrame() throws DocumentException {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

provinceComboBox = new JComboBox();
        provinceComboBox.setModel(new DefaultComboBoxModel(new String[] { "省份" }));
        provinceComboBox.setBounds(33, 106, 108, 21);
        
        cityComboBox = new JComboBox();
        cityComboBox.setBounds(171, 106, 108, 21);
        cityComboBox.setModel(new DefaultComboBoxModel(new String[] { "地级市" }));
        
        countyComboBox = new JComboBox();
        countyComboBox.setBounds(302, 106, 108, 21);
        countyComboBox.setModel(new DefaultComboBoxModel(new String[] { "市、县级市" }));
        
        List<Province> provinces=chinaDao.getObjects();
        provinceList = new ArrayList<String>();
        for(Province p:provinces){
            provinceList.add(p.getName());
        }
        for (String s : provinceList) {
            provinceComboBox.addItem(s);
        }
        
        provinceComboBox.addItemListener(new ItemListener() {

@Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityList=new ArrayList<String>();
                    int ProvinceIndex = provinceComboBox.getSelectedIndex();
                    
                    List<City> cities=chinaDao.getCityObjectsById(ProvinceIndex);
                    for(City city:cities){
                        cityList.add(city.getName());
                    }
                    
                    cityComboBox.removeAllItems();
                    for (String s : cityList) {
                        cityComboBox.addItem(s);
                    }
                }
            }
        });
        
        cityComboBox.addItemListener(new ItemListener() {
            
            @Override
            public void itemStateChanged(ItemEvent e) {        
                if(e.getStateChange() == ItemEvent.SELECTED){
                    cityComboBox=(JComboBox) e.getSource();
                    String name=(String) cityComboBox.getSelectedItem();
                    countyList=new ArrayList<String>();
                    int CityIndex = chinaDao.getIdByName(name).getId();
                    List<County> counties=chinaDao.getCountyObjectsById(CityIndex);
                    
                    for(County county:counties){
                        countyList.add(county.getName());
                    }
                    countyComboBox.removeAllItems();
                    for(String cl:countyList){
                        countyComboBox.addItem(cl);
                    }
                }
                
            }
        });
        
        JLabel lblNewLabel = new JLabel(
                "\u5168\u56FD\u57CE\u5E02\u4E09\u7EA7\u8054\u52A8");
        lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 25, 160, 48);

contentPane.add(provinceComboBox);
        contentPane.add(cityComboBox);
        contentPane.add(countyComboBox);
        contentPane.add(lblNewLabel);
    }
}

时间: 2024-08-29 14:36:42

三级联动查询全国省市区(xml与数据库)的相关文章

Ajax案例:三级联动查询员工的信息(三张表进行内连接)

需求分析: 通过数据库连接池,可以查询到数据库中员工的各种信息,通过点击下拉框的方式实现三级联动,即:没有点击city下拉框,后面两个下拉框中没有值,这样,点击city下拉框,department下拉框中才有值,点击department下拉框后employee下拉框中才有值,才可以进行选择,不可以跨级点击:点击最后一个下拉框可以将员工的id,last_name,email,salary,显示在下面的表格中: 实现上述功能的方法: 1.c3p0数据库连接池,实现数据库的链接:JdbcUtils类,

1、查询数据库以三级联动形式显现

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="

ajax省市区三级联动

jdbc+servlet+ajax开发省市区三级联动 技术点:jdbc操作数据库,ajax提交,字符拦截器,三级联动 特点:局部刷新达到省市区三级联动,举一反三可以做商品分类等 宗旨:从实战中学习 博客讲解是按照两级联动,但下载的资源是三级联动含sql文件. 效果图: 首页核心代码: [html] view plain copy <% List<HashMap<String,Object>> maps = ConnectionUtil.findProvinces(); pag

【修改】纯JS省市区三级联动 支持js默认省市区

---恢复内容开始--- <!DOCTYPE html><html><head><title>修改,QQ JS省市区三级联动 -支持默认省市区</title><!-- 使用QQ的省市区数据 --><!--<script type="text/javascript" src="http://ip.qq.com/js/geo.js"></script>--><

JS省市区三级联动

不需要访问后台服务器端,不使用Ajax,无刷新,纯JS实现的省市区三级联动. 当省市区数据变动是只需调正js即可. 使用方法: <!DOCTYPE html><html><head><title>纯JS省市区联动</title><script type="text/javascript" src="jsAddress.js"></script></head><bod

js实现省市级三级联动

之前做一个小项目时碰到了这个地域选择,三级联动的问题,找了很多源码,最后筛选出了我认为比较实用的代码,分享给大家. 首先,html文件应该有这样的select <select id="province" class="province"></select> <select id="city" class="city"></select> <select id="a

MVC 三级联动

本篇实现中国省市区三级联动,先看最终效果: 初始状态: 当选择第1个Select,第2.3个Select可供选择: 当选择第2个Select,第1个不变.第3个Select可供选择: 当选择第3个Select,第1.2个不变: 下面是代码: 控制器Controllers\HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syste

Vue如何使用vue-area-linkage实现地址三级联动效果

很多时候我们需要使用地址三级联动,即省市区三级联动.网上有很多插件,在此介绍Vue的一款地区联动插件:vue-area-linkage,下面介绍如何使用这个插件实现地址联动效果: 一.安装 // v5之前的版本 npm i --save vue-area-linkage // v5及之后的版本 npm i --save vue-area-linkage area-data or yarn // v5之前的版本 yarn add vue-area-linkage // v5及之后的版本 yarn

javaWeb数据库动态加载全国省市区三级联动

首先声明一下,全国省市区三级联动有很多的插件.没有必要这么麻烦的把省市区存到数据库,然后再获取.这样缺点很明显: 缺点:使用数据库,每次动态ajax获取数据都要操作一次数据库,增加了数据库的负担.不推荐这样做,直接使用插件比较好. 一些Jquery插件比较省时省力,不用来回操作数据库,就能达到你想要的效果,页面修饰就要自己设计咯.而且使用数据库你还要事先把省市区数据存到数据库,耗费精力,及时有一些现成的sql文件可以导入.但是感觉好麻烦有没有,博主算是试了一次. 好了说了很多废话,开始上代码吧: