1.1、分析:
由于省、市、县城(区)这些数据是存储到了MySQL数据库中的,我们要通过后台servlet获取数据库中的数据,然后再通过转发或者重定向的方式将数据呈现到前台页面中。
1.2、需要导入的jar包有:
mysql驱动包:mysql-connector-Java-5.1.7-bin.jar
c3p0数据库连接池:c3p0-0.9.2.1.jar、mysql-connector-java-5.1.7-bin.jar(c3p0依赖包)
前台c标签(需要通过遍历的方式呈现——c:forEach):jstl-1.0.2.jar、standard-1.0.1.jar(jstl依赖包)
将集合或者数组转换成json数据格式(Jackson包):jackson-annotations-2.2.1.jar、jackson-core-2.2.1.jar、jackson-databind-2.2.1.jar
前台页面需要用到jQuery,故还需要导入jquery-1.7.2.js库文件
1.3、该小项目用到的技术:
jdbc的知识、servlet的知识、jquery的知识、Ajax的知识(局部刷新)、标签的知识、EL表达式的知识、JSP的知识
2、开发过程:
2.1、准备数据源
创建一个数据库,命名为thereaction并创建三个表——province(省)、city(市)、county(县/区)
2.2后台开发
创建三个Javabean分别是Province、City、County。(由于太过简单,这里就不粘代码了)
创建Java类和c3p0连接池实现与数据库的连接:DAO.java(实现获取数据库数据的功能)、jdbctools.java(实现获取数据库连接、释放连接的功能)、c3p0-config.xml
jdbctools.java代码如下:
[java] view plain copy
package com.xiaojie.dao
import java.io.IOException
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import javax.sql.DataSource
import com.mchange.v2.c3p0.ComboPooledDataSource
public class Jdbctools {
private static DataSource ds=null
//数据库连接池应只被初始化一次
static{
ds=new ComboPooledDataSource("helloc3p0")
}
//获取数据库连接
public static Connection getConnection() throws ClassNotFoundException, SQLException, IOException{
return ds.getConnection()
}
public static void shifanglianjie(Connection ct, PreparedStatement ps,ResultSet rs) {
if(rs!=null){
try {
rs.close()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
if(ps!=null){
try {
ps.close()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
if(ct!=null){
try {
ct.close()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}
DAO.java的代码如下
[java] view plain copy
package com.xiaojie.dao
import java.io.IOException
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.util.ArrayList
import java.util.List
import com.xiaojie.beans.City
import com.xiaojie.beans.County
import com.xiaojie.beans.Province
public class DAO {
public List<Province>getprovince(String sql ,Object...args) throws ClassNotFoundException, SQLException, IOException{
List<Province>provinces=new ArrayList<Province>()
//准备去查数据库
Connection ct=null
ct=Jdbctools.getConnection()
System.out.println("获取到数据库的连接了")
PreparedStatement ps=null
ResultSet rs=null
ps=ct.prepareStatement(sql)
for(int i=0i<args.lengthi++){
ps.setObject(i+1, args[i])
}
rs=ps.executeQuery()
while(rs.next()){
provinces.add(new Province(rs.getInt("province_id"),rs.getString("province_name")))
}
Jdbctools.shifanglianjie(ct, ps, rs)
return provinces
}
public List<City>getcity(String sql ,Object...args) throws SQLException, ClassNotFoundException, IOException{
List<City>cities=new ArrayList<City>()
//准备去查数据库
Jdbctools jt=new Jdbctools()
Connection ct=null
ct=jt.getConnection()
PreparedStatement ps=null
ResultSet rs=null
ps=ct.prepareStatement(sql)
for(int i=0i<args.lengthi++){
ps.setObject(i+1, args[i])
}
rs=ps.executeQuery()
while(rs.next()){
cities.add(new City(rs.getInt("city_id"),rs.getString("city_name")))
}
jt.shifanglianjie(ct, ps, rs)
return cities
}
public List<County>getcounty(String sql,Object...args ) throws SQLException, ClassNotFoundException, IOException{
List<County>counties=new ArrayList<County>()
//准备去查数据库
Jdbctools jt=new Jdbctools()
Connection ct=null
ct=jt.getConnection()
PreparedStatement ps=null
ResultSet rs=null
ps=ct.prepareStatement(sql)
for(int i=0i<args.lengthi++){
ps.setObject(i+1, args[i])
}
rs=ps.executeQuery()
while(rs.next()){
counties.add(new County(rs.getInt("county_id"),rs.getString("county_name")))
}
jt.shifanglianjie(ct, ps, rs)
return counties
}
}
c3p0-config.xml的代码如下:
[html] view plain copy
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="helloc3p0">
<!-- 连接数据源的基本属性 -->
<property name="user">root</property>
<property name="password"></property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///thereaction</property>
<!-- 若数据库中连接数不足时,一次向数据库服务器申请多少个连接 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">5</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">10</property>
<!-- c3p0数据库连接可以维护的statement的个数 -->
<property name="maxStatements">20</property>
<!-- 每个连接同时可以使用的statement对象的个数 -->
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
创建servlet.java 文件
[java] view plain copy
package com.xiaojie.servlet
import java.io.IOException
import java.lang.reflect.Method
import java.sql.SQLException
import java.util.List
import javax.servlet.ServletException
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.fasterxml.jackson.databind.ObjectMapper
import com.xiaojie.beans.City
import com.xiaojie.beans.County
import com.xiaojie.beans.Province
import com.xiaojie.dao.DAO
/**
* Servlet implementation class ThreeactiondServlet
*/
@WebServlet("/threeactiondServlet")
public class ThreeactiondServlet extends HttpServlet {
private static final long serialVersionUID = 1L
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String methodname=request.getParameter("method")
try {
Method method=getClass().getDeclaredMethod(methodname,HttpServletRequest.class,HttpServletResponse.class)
method.invoke(this, request,response)//调用各自的方法
} catch (Exception e) {
e.printStackTrace()
}
}
private DAO dao=new DAO()
protected void province(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException {
System.out.println("province的servlet进入了")
String sql="select province_id,province_name from province"
List<Province>provinces=dao.getprovince(sql)
request.setAttribute("provinces", provinces)
System.out.println(provinces)
//注意:这里不能用重定向的形式,因为我们好不容易在request请求域中存储了省的信息,目的是在前台页面中能够从请求域中获取到我们存在数据库中的值
//故这里只能用转发的方式
request.getRequestDispatcher("/index2.jsp").forward(request, response)
}
protected void city(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException {
System.out.println("city的servlet进入了")
String province_id=request.getParameter("province_id")
String sql="select city_id,city_name from city where province_id=?"
List<City>cities=dao.getcity(sql,Integer.parseInt(province_id))
ObjectMapper mapper=new ObjectMapper()
String result=mapper.writeValueAsString(cities)
System.out.println(result)
response.setContentType("text/javascript")
response.getWriter().print(result)
}
protected void county(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException {
System.out.println("county的servlet进入了")
String city_id=request.getParameter("city_id")
String sql="select county_id,county_name from county where city_id=?"
List<County>counties=dao.getcounty(sql,Integer.parseInt(city_id))
ObjectMapper mapper=new ObjectMapper()
String result=mapper.writeValueAsString(counties)
System.out.println(result)
response.setContentType("text/javascript")
response.getWriter().print(result)
}
}
给你2种主流的设计方案:1、用树形的形式来设计
表字段ID、PID,其他字段。。。PID是上级的ID,联动的时候查询,只需要查询PID跟当前变动的对应的ID相等就可以
2、用编码的方式
类似身份z的前6位的设计,就是分别是省、市、区。。。。
你查询的时候,直接查询对应的编码一样的就可以
海枫科技
基本思想就是:在JS动态创建select控件的option,通过Ajax获取在PHP从SQL数据库获取的省市区信息,代码有点长,但很多都是类似的,例如JS中省、市、区获取方法类似,PHP中通过参数不同执行不同的select语句。
index.html代码:
<!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>
<title>省市区三级联动</title>
<META http-equiv=Content-Type content="text/html charset=gb2312">
<script src="scripts/thumbnails.js" type="text/javascript"></script>
</head>
thumbnails.js代码:
window.onload = getProvincefunction createRequest() {//Ajax于PHP交互需要对象
try {
request = new XMLHttpRequest()//创建一个新的请求对象
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (failed) {
request = null
}
}
}
return request
}
function sech(id) {//省市改变时触发,select的onchange事件
var aa = document.getElementById(id)
if(id=="sheng"){
getCity(aa.value)//这里aa.value为省的id
}
if(id=="shi")
{
getCounty(aa.value)//这里aa.value为市的id
}
}
function getProvince() {//获取所有省
request = createRequest()
if (request == null) {
alert("Unable to create request")
return
}
var url= "getDetails.php?ID=0"//ID=0时传递至PHP时让其获取所有省
request.open("GET", url, true)
request.onreadystatechange = displayProvince //设置回调函数
request.send(null) //发送请求
}
function getCity(id){//获取省对应的市
request = createRequest()
if (request == null) {
alert("Unable to create request")
return
}
var url= "getDetails.php?ID=" + escape(id)
request.open("GET", url, true)
request.onreadystatechange = displayCity
request.send(null)
}
function getCounty(id){//获取市对应的区
request = createRequest()
if (request == null) {
alert("Unable to create request")
return
}
var url= "getDetails.php?ID=" + escape(id)
request.open("GET", url, true)
request.onreadystatechange = displayCounty
request.send(null)
}
function displayProvince() {//将获取的数据动态增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array
var b=request.responseText//将PHP返回的数据赋值给b
a=b.split(",")//通过","将这一数据保存在数组a中
document.getElementById("sheng").length=1
var obj=document.getElementById("sheng')
for(i=0i
obj.options.add(new Option(a[i],i+1)) //动态生成OPTION加到select中,第一个参数为Text,第二个参数为Value值.
}
}
}
function displayCity() {//将获取的数据动态增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array
var b=request.responseText
a=b.split(",")
document.getElementById("shi").length=1//重新选择
document.getElementById("xian").length=1//重新选择
if(document.getElementById("sheng").value!="province"){
var obj=document.getElementById('shi')
for(i=0i
obj.options.add(new Option(a[i], document.getElementById("sheng").value*100+i+1)) //ocument.getElementById("sheng").value*100+i+1对应的是市的ID。
}
}
}
}
function displayCounty() {//将获取的数据增加至select
if (request.readyState == 4) {
if (request.status == 200) {
var a=new Array
var b=request.responseText
a=b.split(",")
document.getElementById("xian").length=1
if(document.getElementById("sheng").value!="province"&&document.getElementById("shi").value!="city"){
var obj=document.getElementById('xian')
for(i=0i
obj.options.add(new Option(a[i],i+1001))
}
}
}
}
getDetails.php代码:
<?phpheader("Content-Type: text/html charset=gb2312")
$conn = new COM("ADODB.Connection") or die("Cannot start ADO")
$connstr = "Provider=SQLOLEDBPersist Security Info=FalseUser ID=rootPassword=123456Initial Catalog=areaData Source=localhost"
if($_REQUEST['ID']==0){//获得省列表
$conn->Open($connstr) //建立数据库连接
$sqlstr = "select name from Province" //设置查询字符串
$rs = $conn->Execute($sqlstr) //执行查询获得结果
$num_cols = $rs->Fields->Count() //得到数据集列数
$Province=array()
$i=0
while (!$rs->EOF) {
$Province[$i]=$rs->Fields['name']->Value.","
$rs->MoveNext()
$i++
}
foreach($Province as $val)
echo $val
$conn->Close()
$rs = null
$conn = null
}
if($_REQUEST['ID']>0&&$_REQUEST['ID']<35){//获得省对应的市列表
$conn->Open($connstr) //建立数据库连接
$sqlstr = "select name from City where cid=".$_REQUEST['ID'] //设置查询字符串
$rs = $conn->Execute($sqlstr) //执行查询获得结果
$num_cols = $rs->Fields->Count() //得到数据集列数
$City=array()
$i=0
while (!$rs->EOF) {
$City[$i]=$rs->Fields['name']->Value.","
$rs->MoveNext()
$i++
}
foreach($City as $val)
echo $val
$conn->Close()
$rs = null
$conn = null
}
if($_REQUEST['ID']>100){//获得省市对应的县列表
$conn->Open($connstr) //建立数据库连接
$sqlstr = "select name from County where cid=".$_REQUEST['ID'] //设置查询字符串
$rs = $conn->Execute($sqlstr) //执行查询获得结果
$num_cols = $rs->Fields->Count() //得到数据集列数
$County=array()
$i=0
while (!$rs->EOF) {
$County[$i]=$rs->Fields['name']->Value.","
$rs->MoveNext()
$i++
}
foreach($County as $val)
echo $val
$conn->Close()
$rs = null
$conn = null
}
?>
数据库设计,表格Province表,City表,County表。
要求:Province表需要id和name,id建议从1至34,例如北京id为1,广东id为2,以此类推;
City表需要id,name和cid,id为cid*100+1,cid为该市的上级,例如深圳的上级为广东省,cid为2的话,深圳的id就是201,以此类推。
County表需要id,name和cid,因为是三级的关系,id可以随意,建议从10001开始自增。cid为所在上级,例如宝安区的cid为201,龙岗区的cid也为201;
截图:
HTML效果:
完成后效果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)