ajax + servlet 实现三级联动

create table province
(
   pid int,   #省编号  主键
   pname varchar(20) #省名称
);

insert into province(pid,pname) values(1,'吉林省');
insert into province(pid,pname) values(2,'辽宁省');
insert into province(pid,pname) values(3,'山东省');

#--省下的城市
create table city
(
   cid int,   #城市编号
   cname varchar(20),  #城市名称
   pid int     #省的编号 对应province表的主键
);

insert into city(cid,cname,pid) values(1,'长春',1);
insert into city(cid,cname,pid) values(2,'四平',1);
insert into city(cid,cname,pid) values(3,'吉林市',1);

insert into city(cid,cname,pid) values(4,'沈阳',2);
insert into city(cid,cname,pid) values(5,'大连',2);
insert into city(cid,cname,pid) values(6,'鞍山',2);

insert into city(cid,cname,pid) values(7,'济南',3);
insert into city(cid,cname,pid) values(8,'威海',3);
insert into city(cid,cname,pid) values(9,'烟台',3);


#--城市下的县
create table county  #县
(
   tid int,   #县的编号
   tname varchar(20), #县的名称
   cid int      #城市编号    对应city表的主键
);

insert into county(tid,tname,cid) values(1,'九台',1);
insert into county(tid,tname,cid) values(2,'农安',1);

insert into county(tid,tname,cid) values(3,'梨树',2);
insert into county(tid,tname,cid) values(4,'公主岭',2);

insert into county(tid,tname,cid) values(5,'永吉',3);

package cn.itcast.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBManager {
	private static String url;
	private static String username;
	private static String pwd;
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Properties p = new Properties();
		try {
			p.load(DBManager.class.getClassLoader().getResourceAsStream(
					"jdbc.properties"));
			url = p.getProperty("url");
			username = p.getProperty("username");
			pwd = p.getProperty("pwd");

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static Connection getConn() {
		try {
			return DriverManager.getConnection(url, username, pwd);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(stmt!=null) {
				try {
					stmt.close();
					stmt = null;
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					if(rs!=null) {
						try {
							rs.close();
							rs = null;
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}

url=jdbc:mysql://localhost:3306/ajax?useUnicode=true&characterEncoding=utf8
username=root
pwd=

上边是:/src/jdbc.properties 数据库配置文件


cn.itcast.web: 控制层

package cn.itcast.web;

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.bean.Province;
import cn.itcast.service.ProvinceService;

public class ProvinceServlet extends HttpServlet {

	private ProvinceService ps = new ProvinceService();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		List<Province> list = ps.findProvinceList();
		
		JSONArray jsonArray = JSONArray.fromObject(list);
		out.write(jsonArray.toString());
		out.flush();
		out.close();
	}

}


package cn.itcast.web;

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.bean.City;
import cn.itcast.service.CityService;

public class CityServlet extends HttpServlet {

	private CityService cs = new CityService();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		
		int pid = Integer.parseInt(request.getParameter("pid"));
		List<City> list = cs.findCityList(pid);
		
		PrintWriter out = response.getWriter();
		JSONArray ja = JSONArray.fromObject(list);
		out.write(ja.toString());
		out.flush();
		out.close();
	}

	
}


package cn.itcast.web;

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.bean.City;
import cn.itcast.bean.County;
import cn.itcast.service.CountyService;

public class CountyServlet extends HttpServlet {

	private CountyService cs = new CountyService();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		
		int cid = Integer.parseInt(request.getParameter("cid"));
		List<County> list = cs.findCountyList(cid);
		
		PrintWriter out = response.getWriter();
		
		JSONArray ja = JSONArray.fromObject(list);
		out.write(ja.toString());
		
		out.flush();
		out.close();
	}


}

cn.itcast.dao:服务层

package cn.itcast.service;

import java.util.List;

import cn.itcast.bean.Province;
import cn.itcast.dao.ProvinceDao;

public class ProvinceService {
	private ProvinceDao dao = null;
	public List<Province> findProvinceList() {
		dao = new ProvinceDao();
		return dao.findProvinceList();
	}
}

package cn.itcast.service;

import java.util.List;

import cn.itcast.bean.City;
import cn.itcast.dao.CityDao;

public class CityService {
	private CityDao dao = null;
	public List<City> findCityList(int pid) {
		dao = new CityDao();
		return dao.findCityList(pid);
	}

}

package cn.itcast.service;

import java.util.List;

import cn.itcast.bean.City;
import cn.itcast.bean.County;
import cn.itcast.dao.CityDao;
import cn.itcast.dao.CountyDao;

public class CountyService {
	private CountyDao dao = null;
	public List<County> findCountyList(int cid) {
		dao = new CountyDao();
		return dao.findCountyList(cid);
	}

}


cn.itcast.dao:数据访问层

package cn.itcast.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.PreparedStatement;

import cn.itcast.bean.Province;
import cn.itcast.util.DBManager;

public class ProvinceDao {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	private List<Province> list = new ArrayList<Province>();
	
	public List<Province> findProvinceList() {
		conn = DBManager.getConn();
		String sql = "select pid,pname from province";
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				Province p = new Province();
				p.setPid(rs.getInt(1));
				p.setPname(rs.getString(2));
				list.add(p);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBManager.close(conn, pstmt, rs);
		}
		return list;
	}

}

package cn.itcast.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.PreparedStatement;

import cn.itcast.bean.City;
import cn.itcast.bean.Province;
import cn.itcast.util.DBManager;

public class CityDao {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	private List<City> list = new ArrayList<City>();
	
	
	public List<City> findCityList(int pid) {
		
		conn = DBManager.getConn();
		String sql = "select cid,cname from city where pid="+pid;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				City c = new City();
				c.setCid(rs.getInt(1));
				c.setCname(rs.getString(2));
				list.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBManager.close(conn, pstmt, rs);
		}
		return list;
	}

}

package cn.itcast.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.PreparedStatement;

import cn.itcast.bean.City;
import cn.itcast.bean.County;
import cn.itcast.bean.Province;
import cn.itcast.util.DBManager;

public class CountyDao {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	private List<County> list = new ArrayList<County>();
	
	
	public List<County> findCountyList(int cid) {
		
		conn = DBManager.getConn();
		String sql = "select tid,tname from county where cid="+cid;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				County c = new County();
				c.setTid(rs.getInt(1));
				c.setTname(rs.getString(2));
				list.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBManager.close(conn, pstmt, rs);
		}
		return list;
	}

}

cn.itcast.bean: 模型层

package cn.itcast.bean;

public class Province {
	private Integer pid;
	private String pname;
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
}

package cn.itcast.bean;

public class City {
	private Integer cid;
	private String cname;
	private Integer pid;
	public Integer getCid() {
		return cid;
	}
	public void setCid(Integer cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
}

package cn.itcast.bean;

public class County {
	private Integer tid;
	private String tname;
	private Integer cid;
	public Integer getTid() {
		return tid;
	}
	public void setTid(Integer tid) {
		this.tid = tid;
	}
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	public Integer getCid() {
		return cid;
	}
	public void setCid(Integer cid) {
		this.cid = cid;
	}
}


html页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>test01.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<script language="JavaScript" src="./js/jquery-1.4.2.js"></script>
  </head>
  <body>
     <select id="province" name="province">
       <option value="">请选择....</option>
     </select>
	 <select id="city" name="city">
	 	<option value="">请选择.....</option>
	 </select>
	 <select id="county" name="county">
	 	<option value="">请选择.....</option>
	 </select>
  </body>
   <script language="JavaScript">
   	/*
	function ajaxFunction() {
		var xmlHttp;
		
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e) {
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					
				}
			}
		}
		return xmlHttp;
	};
	*/
	$().ready(function() {
		$.post("./provinceServlet",function(data,textStatus){
			var jsondata = eval("("+data+")");
			//遍历json对象
			$(jsondata).each(function(index,domEle){
				var $option = $("<option/>");
				$option.attr("value",this.pid);
				$option.text(this.pname);
				$("#province").append($option);
			});
		});
		//传递省pid,拿到对应的city
		$("#province").change(function(){
			$("#city option[value!='']").remove();
			$("#county option[value!='']").remove();
			
			var param = {"pid":$(this).val()};
			$.post("./cityServlet",param,function(data,textStatus){
				
				alert(data);
				
				var jsonObj = eval("("+data+")");
				$(jsonObj).each(function(){
					var $option = $("<option/>");
					$option.attr("value",this.cid);
					$option.text(this.cname);
					$("#city").append($option);
				});
			});
		});
		
		//传递市cid,拿到对应的county
		$("#city").change(function(){
			$("#county option[value!='']").remove();
			
			//alert(this.value);
			var param = {"cid":$(this).val()};
			$.post("./countyServlet",param,function(data,textStatus){
				//alert(data);
				var jsondata = eval("("+data+")");
				$(jsondata).each(function(index,domEle){
					var $option = $("<option/>");
					$option.attr("value",this.tid);
					$option.text(this.tname);
					$("#county").append($option);
				});
			});
		});
	})
 
  </script>
  	

</html>

用到了jquery, myeclipse---->WebRoot----->js--->jquery-1.4.2.js


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值