【第22期】观点:IT 行业加班,到底有没有价值?

MVC + jQuery 三级联动

原创 2015年07月07日 23:24:58


数据库:
-- MySQL dump 10.10
--
-- Host: localhost Database: test
-- ------------------------------------------------------
-- Server version 5.0.18-nt
 
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 
--
-- Table structure for table `city`
--
 
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(11) NOT NULL,
`name` varchar(20) default NULL,
`pid` int(11) default NULL,
PRIMARY KEY (`id`),
KEY `pid_fk` (`pid`),
CONSTRAINT `pid_fk` FOREIGN KEY (`pid`) REFERENCES `province` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
--
-- Dumping data for table `city`
--
 
 
/*!40000 ALTER TABLE `city` DISABLE KEYS */;
LOCK TABLES `city` WRITE;
INSERT INTO `city` VALUES (1,'东城区',1),(2,'西城区',1),(3,'海淀区',1),(4,'朝阳区',1),(5,'丰台区',1),(6,'石景山区',1),(7,'济南市',2),(8,'青岛市',2),(9,'淄博市',2),(10,'枣庄市',2),(11,'东营市',2),(12,'烟台市',2),(13,'武汉市',3),(14,'黄石市',3),(15,'十堰市',3),(16,'荆州市',3);
UNLOCK TABLES;
/*!40000 ALTER TABLE `city` ENABLE KEYS */;
 
--
-- Table structure for table `county`
--
 
DROP TABLE IF EXISTS `county`;
CREATE TABLE `county` (
`id` int(11) NOT NULL,
`name` varchar(20) default NULL,
`cid` int(11) default NULL,
PRIMARY KEY (`id`),
KEY `cid_fk` (`cid`),
CONSTRAINT `cid_fk` FOREIGN KEY (`cid`) REFERENCES `city` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
--
-- Dumping data for table `county`
--
 
 
/*!40000 ALTER TABLE `county` DISABLE KEYS */;
LOCK TABLES `county` WRITE;
INSERT INTO `county` VALUES (1,'安定门',1),(2,'建国门',1),(3,'朝阳门',1),(4,'东直门',1),(5,'广安门',2),(6,'新街口',2),(7,'金融街',2),(8,'什刹海',2),(9,'上地',3),(10,'清河',3),(11,'东北旺',3),(12,'劲松',4),(13,'呼家楼',4),(14,'三里屯',4),(15,'右安门',5),(16,'太平桥',5),(17,'大红门',5),(18,'南苑',5),(19,'八宝山',6),(20,'老山',6),(21,'八角',6),(22,'苹果园',6),(23,'市中区',7),(24,'历下区',7),(25,'天桥区',7),(26,'槐荫区',7),(27,'历城区',7),(28,'长清区',7),(29,'市南区',8),(30,'市北区',8),(31,'李沧区',8),(32,'崂山区',8),(33,'城阳区',8),(34,'黄岛区',8),(35,'张店区',9),(36,'淄川区',9),(37,'博山区',9),(38,'周村区',9),(39,'临淄区',9),(40,'薛城区',10),(41,'市中区',10),(42,'驿城区',10),(43,'台儿庄区',10),(44,'山亭区',10),(45,'滕州市',10),(46,'东营区',11),(47,'河口区',11),(48,'芝罘区',12),(49,'福山区',12),(50,'牟平区',12),(51,'莱山区',12),(52,'江岸区',13),(53,'江汉区',13),(54,'汉阳区',13),(55,'武昌区',13),(56,'黄石港区',14),(57,'西塞山区',14),(58,'下陆区',14),(59,'铁山区',14),(60,'茅箭区',15),(61,'张湾区',15),(62,'荆州区',16),(63,'沙市区',16),(64,'江陵县',16),(65,'松滋市',16),(66,'公安县',16);
UNLOCK TABLES;
/*!40000 ALTER TABLE `county` ENABLE KEYS */;
 
--
-- Table structure for table `province`
--
 
DROP TABLE IF EXISTS `province`;
CREATE TABLE `province` (
`id` int(11) NOT NULL,
`name` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
--
-- Dumping data for table `province`
--
 
 
/*!40000 ALTER TABLE `province` DISABLE KEYS */;
LOCK TABLES `province` WRITE;
INSERT INTO `province` VALUES (1,'北京'),(2,'山东'),(3,'湖北');
UNLOCK TABLES;
/*!40000 ALTER TABLE `province` ENABLE KEYS */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
 
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
*
use test;
create table province(
id int primary key,
name varchar(100)
);
create table city(
id int primary key,
name varchar(100),
pid int,#省份的id
constraint pid_fk foreign key(pid) references province(id)
);
create table county(
id int primary key,
name varchar(100),
cid int,#cityid
constraint cid_fk foreign key(cid) references city(id)
);


数据源:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=sorry
 
initialSize=10
 
maxActive=50
 
maxIdle=20
 
minIdle=5
 
maxWait=60000
 
 
connectionProperties=useUnicode=true;characterEncoding=utf8
 
defaultAutoCommit=true
 
defaultReadOnly=
 
defaultTransactionIsolation=REPEATABLE_READ


Util:
package cn.itcast.util;
 
import java.io.InputStream;
import java.util.Properties;
 
import javax.sql.DataSource;
 
import org.apache.commons.dbcp.BasicDataSourceFactory;
 
public class DBCPUtil {
private static DataSource ds;
static{
try {
InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties props = new Properties();
props.load(in);
ds = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return ds;
}
}

Bean:
1、city
package cn.itcast.domain;
 
import java.io.Serializable;
 
public class City implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2、county:
package cn.itcast.domain;
 
import java.io.Serializable;
 
public class County implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

3、province:
package cn.itcast.domain;
 
import java.io.Serializable;
 
public class Province implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}




DAO:
       imple:
        1、cityimple
package cn.itcast.dao.impl; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import cn.itcast.dao.CityDao; import cn.itcast.domain.City; import cn.itcast.domain.Province; import cn.itcast.util.DBCPUtil; public class CityDaoImpl implements CityDao { private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource()); @Override public List<City> findCityByProvinceId(int provinceId) { try { return qr.query("select * from city where pid=?", new BeanListHandler<City>(City.class),provinceId); } catch (SQLException e) { throw new RuntimeException(e); } } }
  •                 2、countyimple:
    package cn.itcast.dao.impl;
     
    import java.sql.SQLException;
    import java.util.List;
     
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
     
    import cn.itcast.dao.CityDao;
    import cn.itcast.domain.City;
    import cn.itcast.domain.Province;
    import cn.itcast.util.DBCPUtil;
     
    public class CityDaoImpl implements CityDao {
    private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
    @Override
    public List<City> findCityByProvinceId(int provinceId) {
    try {
    return qr.query("select * from city where pid=?", new BeanListHandler<City>(City.class),provinceId);
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
    }
     
    }
                    3、province:
    package cn.itcast.dao.impl;
     
    import java.sql.SQLException;
    import java.util.List;
     
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
     
    import cn.itcast.dao.ProvinceDao;
    import cn.itcast.domain.Province;
    import cn.itcast.util.DBCPUtil;
     
    public class ProvinceDaoImpl implements ProvinceDao {
    private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
    @Override
    public List<Province> findAllProvince() {
    try {
    return qr.query("select * from province", new BeanListHandler<Province>(Province.class));
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
    }
     
    }

        impletake:
                1、city:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.City;
     
    public interface CityDao {
    List<City> findCityByProvinceId(int provinceId);
    }

                2、county:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.County;
     
    public interface CountyDao {
    List<County> findCountyByCityId(int cityId);
    }

                3、province:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.Province;
     
    public interface ProvinceDao {
    List<Province> findAllProvince();
    }




    Service 业务逻辑层:
        imple:
    package cn.itcast.service.impl;
     
    import java.util.List;
     
    import cn.itcast.dao.CityDao;
    import cn.itcast.dao.CountyDao;
    import cn.itcast.dao.ProvinceDao;
    import cn.itcast.dao.impl.CityDaoImpl;
    import cn.itcast.dao.impl.CountyDaoImpl;
    import cn.itcast.dao.impl.ProvinceDaoImpl;
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
    import cn.itcast.service.BusinessService;
     
    public class BusinessServiceImpl implements BusinessService {
    private ProvinceDao pDao = new ProvinceDaoImpl();
    private CityDao cityDao = new CityDaoImpl();
    private CountyDao countyDao = new CountyDaoImpl();
    @Override
    public List<City> findCityByProvinceId(int provinceId) {
    return cityDao.findCityByProvinceId(provinceId);
    }
     
    @Override
    public List<County> findCountyByCityId(int cityId) {
    return countyDao.findCountyByCityId(cityId);
    }
     
    @Override
    public List<Province> findAllProvince() {
    return pDao.findAllProvince();
    }
     
    }
            impletake:
    package cn.itcast.service;
     
    import java.util.List;
     
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
     
    public interface BusinessService {
    List<City> findCityByProvinceId(int provinceId);
    List<County> findCountyByCityId(int cityId);
    List<Province> findAllProvince();
    }



    Control数据操纵层:
    package cn.itcast.web.controller;
     
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import net.sf.json.JSONArray;
     
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
    import cn.itcast.service.BusinessService;
    import cn.itcast.service.impl.BusinessServiceImpl;
     
    public class ControllerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private BusinessService s = new BusinessServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String operation = request.getParameter("operation");
    if("showAllProvince".equals(operation)){
    showAllProvince(request,response);
    }
    if("showCityByProvince".equals(operation)){
    showCityByProvince(request,response);
    }
    if("showCountyByCity".equals(operation)){
    showCountyByCity(request,response);
    }
    }
    //根据城市的id罗列区县
    private void showCountyByCity(HttpServletRequest request,
    HttpServletResponse response)throws ServletException, IOException {
    String cid = request.getParameter("cid");
    if(cid!=null&&!cid.equals("")){
    List<County> cs = s.findCountyByCityId(Integer.parseInt(cid));
    JSONArray jsonArray = JSONArray.fromObject(cs);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
    }
    //根据省份的id罗列城市
    private void showCityByProvince(HttpServletRequest request,
    HttpServletResponse response)throws ServletException, IOException {
    String pid = request.getParameter("pid");
    if(pid!=null&&!pid.equals("")){
    List<City> cs = s.findCityByProvinceId(Integer.parseInt(pid));
    JSONArray jsonArray = JSONArray.fromObject(cs);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
    }
    //显示所有的省份
    private void showAllProvince(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    List<Province> ps = s.findAllProvince();
    JSONArray jsonArray = JSONArray.fromObject(ps);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
     
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
     
    }



    前台页面:
    <?xml version="1.0" encoding="UTF-8" ?>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.2.js"></script>
    <title>Insert title here</title>
    </head>
    <body style="font-size: 12px">
     
    <select id="province">
    <option value="">请选择</option>
    </select>
    <select id="city">
    <option value="">请选择</option>
    </select>
    <select id="county">
    <option value="">请选择</option>
    </select><br/>
    详细地址:<input type="text"/>
    <script type="text/javascript">
    $().ready(function(){
    //文档加载完毕后,异步请求所有的省份
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showAllProvince&time="+new Date().getTime(),null,function(data,textStatus){
    //返回的数据时JSON字符串
    var provinces = eval("("+data+")");
    //id=province增加<option value="1">山东省</option>
    for(var i=0;i<provinces.length;i++){
    var id = provinces[i].id;
    var name = provinces[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#province").append($optionElement);
    }
    });
    //省份值变化时,引起城市的变化
    $("#province").change(function(){
    //清空城市
    $("#city option[value!='']").remove();
    $("#county option[value!='']").remove();
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showCityByProvince&time="+new Date().getTime(),{pid:$(this).val()},function(data,textStatus){
    var citys = eval("("+data+")");
    for(var i=0;i<citys.length;i++){
    var id = citys[i].id;
    var name = citys[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#city").append($optionElement);
    }
    });
    });
     
    //城市值变化时,引起区县的变化
    $("#city").change(function(){
    //清空区县
    $("#county option[value!='']").remove();
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showCountyByCity&time="+new Date().getTime(),{cid:$(this).val()},function(data,textStatus){
    var countys = eval("("+data+")");
    for(var i=0;i<countys.length;i++){
    var id = countys[i].id;
    var name = countys[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#county").append($optionElement);
    }
    });
    });
    });
    </script>
    </body>
    </html>




     



    相关.jar包:

    web.xml:


     



    数据库:
    -- MySQL dump 10.10
    --
    -- Host: localhost Database: test
    -- ------------------------------------------------------
    -- Server version 5.0.18-nt
     
    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
    /*!40101 SET NAMES utf8 */;
    /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
    /*!40103 SET TIME_ZONE='+00:00' */;
    /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
    /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
     
    --
    -- Table structure for table `city`
    --
     
    DROP TABLE IF EXISTS `city`;
    CREATE TABLE `city` (
    `id` int(11) NOT NULL,
    `name` varchar(20) default NULL,
    `pid` int(11) default NULL,
    PRIMARY KEY (`id`),
    KEY `pid_fk` (`pid`),
    CONSTRAINT `pid_fk` FOREIGN KEY (`pid`) REFERENCES `province` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     
    --
    -- Dumping data for table `city`
    --
     
     
    /*!40000 ALTER TABLE `city` DISABLE KEYS */;
    LOCK TABLES `city` WRITE;
    INSERT INTO `city` VALUES (1,'东城区',1),(2,'西城区',1),(3,'海淀区',1),(4,'朝阳区',1),(5,'丰台区',1),(6,'石景山区',1),(7,'济南市',2),(8,'青岛市',2),(9,'淄博市',2),(10,'枣庄市',2),(11,'东营市',2),(12,'烟台市',2),(13,'武汉市',3),(14,'黄石市',3),(15,'十堰市',3),(16,'荆州市',3);
    UNLOCK TABLES;
    /*!40000 ALTER TABLE `city` ENABLE KEYS */;
     
    --
    -- Table structure for table `county`
    --
     
    DROP TABLE IF EXISTS `county`;
    CREATE TABLE `county` (
    `id` int(11) NOT NULL,
    `name` varchar(20) default NULL,
    `cid` int(11) default NULL,
    PRIMARY KEY (`id`),
    KEY `cid_fk` (`cid`),
    CONSTRAINT `cid_fk` FOREIGN KEY (`cid`) REFERENCES `city` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     
    --
    -- Dumping data for table `county`
    --
     
     
    /*!40000 ALTER TABLE `county` DISABLE KEYS */;
    LOCK TABLES `county` WRITE;
    INSERT INTO `county` VALUES (1,'安定门',1),(2,'建国门',1),(3,'朝阳门',1),(4,'东直门',1),(5,'广安门',2),(6,'新街口',2),(7,'金融街',2),(8,'什刹海',2),(9,'上地',3),(10,'清河',3),(11,'东北旺',3),(12,'劲松',4),(13,'呼家楼',4),(14,'三里屯',4),(15,'右安门',5),(16,'太平桥',5),(17,'大红门',5),(18,'南苑',5),(19,'八宝山',6),(20,'老山',6),(21,'八角',6),(22,'苹果园',6),(23,'市中区',7),(24,'历下区',7),(25,'天桥区',7),(26,'槐荫区',7),(27,'历城区',7),(28,'长清区',7),(29,'市南区',8),(30,'市北区',8),(31,'李沧区',8),(32,'崂山区',8),(33,'城阳区',8),(34,'黄岛区',8),(35,'张店区',9),(36,'淄川区',9),(37,'博山区',9),(38,'周村区',9),(39,'临淄区',9),(40,'薛城区',10),(41,'市中区',10),(42,'驿城区',10),(43,'台儿庄区',10),(44,'山亭区',10),(45,'滕州市',10),(46,'东营区',11),(47,'河口区',11),(48,'芝罘区',12),(49,'福山区',12),(50,'牟平区',12),(51,'莱山区',12),(52,'江岸区',13),(53,'江汉区',13),(54,'汉阳区',13),(55,'武昌区',13),(56,'黄石港区',14),(57,'西塞山区',14),(58,'下陆区',14),(59,'铁山区',14),(60,'茅箭区',15),(61,'张湾区',15),(62,'荆州区',16),(63,'沙市区',16),(64,'江陵县',16),(65,'松滋市',16),(66,'公安县',16);
    UNLOCK TABLES;
    /*!40000 ALTER TABLE `county` ENABLE KEYS */;
     
    --
    -- Table structure for table `province`
    --
     
    DROP TABLE IF EXISTS `province`;
    CREATE TABLE `province` (
    `id` int(11) NOT NULL,
    `name` varchar(20) default NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     
    --
    -- Dumping data for table `province`
    --
     
     
    /*!40000 ALTER TABLE `province` DISABLE KEYS */;
    LOCK TABLES `province` WRITE;
    INSERT INTO `province` VALUES (1,'北京'),(2,'山东'),(3,'湖北');
    UNLOCK TABLES;
    /*!40000 ALTER TABLE `province` ENABLE KEYS */;
    /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
     
    /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
    /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
    /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
    /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
    /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
    /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
    /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
    *
    use test;
    create table province(
    id int primary key,
    name varchar(100)
    );
    create table city(
    id int primary key,
    name varchar(100),
    pid int,#省份的id
    constraint pid_fk foreign key(pid) references province(id)
    );
    create table county(
    id int primary key,
    name varchar(100),
    cid int,#cityid
    constraint cid_fk foreign key(cid) references city(id)
    );


    数据源:
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test
    username=root
    password=sorry
     
    initialSize=10
     
    maxActive=50
     
    maxIdle=20
     
    minIdle=5
     
    maxWait=60000
     
     
    connectionProperties=useUnicode=true;characterEncoding=utf8
     
    defaultAutoCommit=true
     
    defaultReadOnly=
     
    defaultTransactionIsolation=REPEATABLE_READ


    Util:
    package cn.itcast.util;
     
    import java.io.InputStream;
    import java.util.Properties;
     
    import javax.sql.DataSource;
     
    import org.apache.commons.dbcp.BasicDataSourceFactory;
     
    public class DBCPUtil {
    private static DataSource ds;
    static{
    try {
    InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
    Properties props = new Properties();
    props.load(in);
    ds = BasicDataSourceFactory.createDataSource(props);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    public static DataSource getDataSource(){
    return ds;
    }
    }

    Bean:
    1、city
    package cn.itcast.domain;
     
    import java.io.Serializable;
     
    public class City implements Serializable {
    private Integer id;
    private String name;
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }
    2、county:
    package cn.itcast.domain;
     
    import java.io.Serializable;
     
    public class County implements Serializable {
    private Integer id;
    private String name;
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }

    3、province:
    package cn.itcast.domain;
     
    import java.io.Serializable;
     
    public class Province implements Serializable {
    private Integer id;
    private String name;
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }




    DAO:
           imple:
            1、cityimple
    package cn.itcast.dao.impl; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import cn.itcast.dao.CityDao; import cn.itcast.domain.City; import cn.itcast.domain.Province; import cn.itcast.util.DBCPUtil; public class CityDaoImpl implements CityDao { private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource()); @Override public List<City> findCityByProvinceId(int provinceId) { try { return qr.query("select * from city where pid=?", new BeanListHandler<City>(City.class),provinceId); } catch (SQLException e) { throw new RuntimeException(e); } } }
  •                 2、countyimple:
    package cn.itcast.dao.impl;
     
    import java.sql.SQLException;
    import java.util.List;
     
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
     
    import cn.itcast.dao.CityDao;
    import cn.itcast.domain.City;
    import cn.itcast.domain.Province;
    import cn.itcast.util.DBCPUtil;
     
    public class CityDaoImpl implements CityDao {
    private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
    @Override
    public List<City> findCityByProvinceId(int provinceId) {
    try {
    return qr.query("select * from city where pid=?", new BeanListHandler<City>(City.class),provinceId);
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
    }
     
    }
                    3、province:
    package cn.itcast.dao.impl;
     
    import java.sql.SQLException;
    import java.util.List;
     
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
     
    import cn.itcast.dao.ProvinceDao;
    import cn.itcast.domain.Province;
    import cn.itcast.util.DBCPUtil;
     
    public class ProvinceDaoImpl implements ProvinceDao {
    private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
    @Override
    public List<Province> findAllProvince() {
    try {
    return qr.query("select * from province", new BeanListHandler<Province>(Province.class));
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
    }
     
    }

        impletake:
                1、city:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.City;
     
    public interface CityDao {
    List<City> findCityByProvinceId(int provinceId);
    }

                2、county:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.County;
     
    public interface CountyDao {
    List<County> findCountyByCityId(int cityId);
    }

                3、province:
    package cn.itcast.dao;
     
    import java.util.List;
     
    import cn.itcast.domain.Province;
     
    public interface ProvinceDao {
    List<Province> findAllProvince();
    }




    Service 业务逻辑层:
        imple:
    package cn.itcast.service.impl;
     
    import java.util.List;
     
    import cn.itcast.dao.CityDao;
    import cn.itcast.dao.CountyDao;
    import cn.itcast.dao.ProvinceDao;
    import cn.itcast.dao.impl.CityDaoImpl;
    import cn.itcast.dao.impl.CountyDaoImpl;
    import cn.itcast.dao.impl.ProvinceDaoImpl;
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
    import cn.itcast.service.BusinessService;
     
    public class BusinessServiceImpl implements BusinessService {
    private ProvinceDao pDao = new ProvinceDaoImpl();
    private CityDao cityDao = new CityDaoImpl();
    private CountyDao countyDao = new CountyDaoImpl();
    @Override
    public List<City> findCityByProvinceId(int provinceId) {
    return cityDao.findCityByProvinceId(provinceId);
    }
     
    @Override
    public List<County> findCountyByCityId(int cityId) {
    return countyDao.findCountyByCityId(cityId);
    }
     
    @Override
    public List<Province> findAllProvince() {
    return pDao.findAllProvince();
    }
     
    }
            impletake:
    package cn.itcast.service;
     
    import java.util.List;
     
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
     
    public interface BusinessService {
    List<City> findCityByProvinceId(int provinceId);
    List<County> findCountyByCityId(int cityId);
    List<Province> findAllProvince();
    }



    Control数据操纵层:
    package cn.itcast.web.controller;
     
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import net.sf.json.JSONArray;
     
    import cn.itcast.domain.City;
    import cn.itcast.domain.County;
    import cn.itcast.domain.Province;
    import cn.itcast.service.BusinessService;
    import cn.itcast.service.impl.BusinessServiceImpl;
     
    public class ControllerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private BusinessService s = new BusinessServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String operation = request.getParameter("operation");
    if("showAllProvince".equals(operation)){
    showAllProvince(request,response);
    }
    if("showCityByProvince".equals(operation)){
    showCityByProvince(request,response);
    }
    if("showCountyByCity".equals(operation)){
    showCountyByCity(request,response);
    }
    }
    //根据城市的id罗列区县
    private void showCountyByCity(HttpServletRequest request,
    HttpServletResponse response)throws ServletException, IOException {
    String cid = request.getParameter("cid");
    if(cid!=null&&!cid.equals("")){
    List<County> cs = s.findCountyByCityId(Integer.parseInt(cid));
    JSONArray jsonArray = JSONArray.fromObject(cs);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
    }
    //根据省份的id罗列城市
    private void showCityByProvince(HttpServletRequest request,
    HttpServletResponse response)throws ServletException, IOException {
    String pid = request.getParameter("pid");
    if(pid!=null&&!pid.equals("")){
    List<City> cs = s.findCityByProvinceId(Integer.parseInt(pid));
    JSONArray jsonArray = JSONArray.fromObject(cs);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
    }
    //显示所有的省份
    private void showAllProvince(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    List<Province> ps = s.findAllProvince();
    JSONArray jsonArray = JSONArray.fromObject(ps);
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    }
     
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
     
    }



    前台页面:
    <?xml version="1.0" encoding="UTF-8" ?>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.4.2.js"></script>
    <title>Insert title here</title>
    </head>
    <body style="font-size: 12px">
     
    <select id="province">
    <option value="">请选择</option>
    </select>
    <select id="city">
    <option value="">请选择</option>
    </select>
    <select id="county">
    <option value="">请选择</option>
    </select><br/>
    详细地址:<input type="text"/>
    <script type="text/javascript">
    $().ready(function(){
    //文档加载完毕后,异步请求所有的省份
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showAllProvince&time="+new Date().getTime(),null,function(data,textStatus){
    //返回的数据时JSON字符串
    var provinces = eval("("+data+")");
    //id=province增加<option value="1">山东省</option>
    for(var i=0;i<provinces.length;i++){
    var id = provinces[i].id;
    var name = provinces[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#province").append($optionElement);
    }
    });
    //省份值变化时,引起城市的变化
    $("#province").change(function(){
    //清空城市
    $("#city option[value!='']").remove();
    $("#county option[value!='']").remove();
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showCityByProvince&time="+new Date().getTime(),{pid:$(this).val()},function(data,textStatus){
    var citys = eval("("+data+")");
    for(var i=0;i<citys.length;i++){
    var id = citys[i].id;
    var name = citys[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#city").append($optionElement);
    }
    });
    });
     
    //城市值变化时,引起区县的变化
    $("#city").change(function(){
    //清空区县
    $("#county option[value!='']").remove();
    $.post("${pageContext.request.contextPath}/servlet/ControllerServlet?operation=showCountyByCity&time="+new Date().getTime(),{cid:$(this).val()},function(data,textStatus){
    var countys = eval("("+data+")");
    for(var i=0;i<countys.length;i++){
    var id = countys[i].id;
    var name = countys[i].name;
    var $optionElement = $("<option value='"+id+"'>"+name+"</option>");
    $("#county").append($optionElement);
    }
    });
    });
    });
    </script>
    </body>
    </html>




    版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

    相关文章推荐

    ASP.NET MVC + Jquery 实现Ajax下拉框数据三级联动

    这是第一使用Jquery实现城市三级数据联动的实例!之前本人没有使用过Jquery,在WebForm的开发过程中,很多时候用的是ASP.NET Ajax,ajaxPro +JavaScript,从未使...

    基于MVC3下拉列表联动(JQuery)

    上次项目中遇到一个需要多个下拉列表联动的操作,今天有空将实现方式整理以便以后参考。 要达到的效果是,点击一个下拉框,则另一个下拉框的值发生对应变化。如:选择中国,则另个一下拉框里显示中国各个省份。 传...

    程序员升职加薪指南!还缺一个“证”!

    CSDN出品,立即查看!

    ASP.NET MVC + Jquery 实现Ajax下拉框数据三级联动

    View :     $(document).ready(function() {         GetByJquery();         $("#ddlProvince").chan...

    编程思路——c#.net mvc 项目经验:三级联动框

    项目要求: 单击

    MVC4.0搭建的省市县三联动,包含数据库

    才学的MVC哈。 最近有个需要,从数据库读取省市县表的数据,通过MVC4搭建的程序展现出来,网上找了很多资料,都没一个全的,能用的,就自己动手。 一、建立MVC项目:City 二、创建数据模型 C...

    ASP.NET MVC + Jquery 实现Ajax下拉框数据三级联动

    这是第一使用Jquery实现城市三级数据联动的实例!之前本人没有使用过Jquery,在WebForm的开发过程中,很多时候用的是ASP.NET Ajax,ajaxPro +JavaScript,从未使...

    jquery easyui三级联动

    直接上代码: //省市区三级联动 var $province = $('#userAttrArea'); var $city = $('#userAttrCity'); var $County = $('#userAttrCou...
    • zhanwc
    • zhanwc
    • 2013-02-21 18:01
    • 8459

    1.MVC框架复习 2.Ajax加强 3.搜索建议 4,三级联动 5、刷新分页 6、Ajax局部动态更新数据

    MVC框架复习  ·admin.php / index.php   定义常量 APP_NAME admin 和 home 来区分入口。  define('APP_NAME','admin/');...
    • Jye13
    • Jye13
    • 2013-04-02 07:34
    • 1081
    收藏助手
    不良信息举报
    您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
    举报原因:
    原因补充:

    (最多只允许输入30个字)