具体如下:
1)、页面初始化时,首先加载所有的省;
2)、选择省,ajax传送编码至服务器,服务器根据选中的省编码,返回省下所有的市。
这样就能动态实现了省市级联的效果了。
1、在做这个小项目前的准备工作: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)
}
}
<html><head>
<script language="javascript" src="json.txt"></script>
<script type="text/javascript">
//var html=[{c:[{c:[{name:"县",value:"000000"}],name:"市",value:"0000"}],name:"省",value:"00"},{c:[{c:[{name:"北京",value:"010100"},{name:"海淀",value:"010200"},{name:"朝阳",value:"010300"},{name:"顺义",value:"010400"},{name:"怀柔",value:"010500"},{name:"通州",value:"010600"},{name:"昌平",value:"010700"},{name:"延庆",value:"010800"},{name:"丰台",value:"010900"},{name:"石景山",value:"011000"},{name:"大兴",value:"011100"},{name:"房山",value:"011200"},{name:"密云",value:"011300"},{name:"门头沟",value:"011400"},{name:"平谷",value:"011500"},{name:"八达岭",value:"011600"},{name:"佛爷顶",value:"011700"},{name:"汤河口",value:"011800"},{name:"密云上甸子",value:"011900"},{name:"斋堂",value:"012000"},{name:"霞云岭",value:"012100"}],name:"北京",value:"0101"}],name:"北京",value:"01"},{c:[{c:[{name:"上海",value:"020100"},{name:"闵行",value:"020200"},{name:"宝山",value:"020300"},{name:"川沙",value:"020400"},{name:"嘉定",value:"020500"},{name:"南汇",value:"020600"},{name:"金山",value:"020700"},{name:"青浦",value:"020800"},{name:"松江",value:"020900"},{name:"奉贤",value:"021000"},{name:"崇明",value:"021100"},{name:"陈家镇",value:"021200"},{name:"引水船",value:"021300"}],name:"上海",value:"0201"}],name:"上海",value:"02"}]
function init(){
document.write('省:<select onchange="getListOne()" id="province">')
document.write('<option value="">----请选择----</option>')
for(var i=0i<html.lengthi++){
document.write('<option value='+html[i].value+'>'+html[i].name+'</option>')
}
document.write('</select>')
document.write('市:<select onchange="getListTwo()" id="town">')
document.write('<option value="">----请选择----</option></select>')
document.write('县:<select id="county">')
document.write('<option value="">----请选择----</option></select>')
}
function getListOne(){
var value=document.getElementById('province').value
if(document.getElementById('town')!=null){
document.getElementById('town').length=1//清空select,保留第一条
}
if(value!=""){
for(var i=0i<html.lengthi++){
if(html[i].value==value){
for(var j=0j<html[i].c.lengthj++){
var option=document.createElement('option')
option.value=html[i].c[j].value
option.text=html[i].c[j].name
document.getElementById('town').options.add(option)
//document.write('<option value='+html[i].c[j].value+'>'+html[i].c[j].name+'</option>')
}
}
}
}
}
function getListTwo(){
var value=document.getElementById('town').value
if(document.getElementById('county')!=null){
document.getElementById('county').length=1//清空select,保留第一条
}
if(value!=""){
for(var i=0i<html.lengthi++){
for(var j=0j<html[i].c.lengthj++){
if(html[i].c[j].value==value){
for(var k=0k<html[i].c[j].c.lengthk++){
var option=document.createElement('option')
option.value=html[i].c[j].c[k].value
option.text=html[i].c[j].c[k].name
document.getElementById('county').options.add(option)
}
}
}
}
}
}
</script>
</head>
<body onload="init()">
</body>
</html>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)