原理说明
1. 准备工作
1.创建表 [城市信息表] [行政区信息表]
create table city(
cid int,
cname varchar(200),
pid int
);
create table qu(
qid int,
qname varchar(200),
cid int
);
2.制造测试数据
insert into city values(1,'北京市',1);
insert into city values(2,'廊坊市',1);
insert into city values(3,'沈阳市',2);
insert into city values(4,'大连市',2);
insert into qu values(1,'海淀区',1);
insert into qu values(2,'廊坊区',2);
insert into qu values(3,'皇姑区',3);
insert into qu values(4,'甘井子区',4);
2. 省市级联
1. index.jsp 添加findCity,用于将用户选择【省编号】通过代理对象发送到服务器端,
并接受结果,填充城市下拉列表
2. CityFindServlet:
1. 获得【省编号】
2. JDBC获得当前省拥有的所有的城市信息
3. 将【城市信息】交给【代理对象】
3.如何将JAVA中高级类型数据交给代理对象进行编译
1.所有的编程语言,都拥有8中基本数据类型:
编程语言都需要在内存中运行,运行期间涉及的数据特征就必须符合内存条的要求。
所有内存厂商,都只支持8中基本数据类型
2.不同编程语言的基本数据类型,彼此之间是可以直接相互编译
3.由于不同编程语言描述各自高级类型时,使用描述方式是不同的,因此 不同编程语言之间高级类型是无法直接编译
4.javascript如何描述一个对象:
JSON形式 var cityObj ={cid:"1",cname:"北京",pid:"1"}
5. java如何描述一个对象
City city = new City();
city.cid =1;
city.cname="北京"
6. 为了能够让【代理对象】正确编译高级类型 在服务器端,将JAVA修饰对象格式转变为JSON形式格式
4.0 如何实现真正三表级联
1.上述的两个功能中,都是读取当前下拉表中选中<option>来获得隶属于当前数据的内容
2.浏览器加载下拉列表时,默认情况将下拉列表中第一个<option>作为默认选中项。
浏览器将当前<option value>自动赋值给当前的下拉列表
环境:
jar包:
- mysql-connector-java-5.1.25.jar
- json-lib-2.3-jdk15.jar
- commons-collections-3.2.2.jar
- commons-beanutils-1.3.jar
- commons-lang-1.0.1.jar
- ezmorph-1.0.2.jar
- commons-logging-1.2.jar
下载地址:https://mvnrepository.com
搭建环境
- eclipse
- jdk1.8
- tomacat8.5
- Dynamic Web Module 3.1
代码(Java web):
附github地址:
1.index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
var xmlhttp = null;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function findCity() {
var pid = document.getElementById("province").value;
if (pid == 0) {
alert("请选择具体的省");
return;
}
//以下是post方式
xmlhttp.open("post", "CityFindServlet", true); // 1.初始化【代理对象】
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //使用post方式必须有这句话
xmlhttp.send("pid=" + pid); // 2.通知【代理对象】发送请求 ,使用post方式
//以下是get方式
//xmlhttp.open("get", "CityFindServlet?pid="+pid, true);
//xmlhttp.send();
xmlhttp.onreadystatechange = function() { // 3.实时监控【代理对象】工作状态,决定何时读取服务器端返回的数据
if (xmlhttp.readyState == 4) {
// 4...........................................获得服务器端的数据
var jsonData = xmlhttp.responseText; //json形式的字符串 "[{},{}]"
// alert("jsonData "+jsonData);
// 将JSON形式字符串,转换成一个真正的JSON形式对象
var jsonObj = eval("{" + jsonData + "}");//[cid:xx,cname:xx;cid:xx,cname:xx]
// alert("jsonObj "+jsonObj);
//将返回的数据,填充到城市下拉列表--------------start
document.getElementById("city").options.length = 0; //1.将当前城市下拉列表原有的<option>销毁掉
for (var i = 0; i < jsonObj.length; i++) { //2.将新的数据,生成<option>,并填充到下拉列表
var optionObj = new Option(jsonObj[i].cname, jsonObj[i].cid);
document.getElementById("city").options.add(optionObj);
}
//将返回的数据,填充到城市下拉列表--------------end
//此时城市下拉列表中,已经有了value,就将这个value发送到服务器端,获得当前城市拥有的行政区
findQu();
}
}
} //根据城市编号,查询对应行政区
function findQu() {
var cid = document.getElementById("city").value;
if (cid == 0) {
alert("请选择具体的城市");
return;
}
//以下是post方式
xmlhttp.open("post", "QuFindServlet", true); // 1.初始化【代理对象】
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //使用post方式必须有这句话
xmlhttp.send("cid=" + cid); // 2.通知【代理对象】发送请求 ,使用post方式
//以下是get方式
//xmlhttp.open("get", "QuFindServlet?cid="+cid, true);
//xmlhttp.send();
xmlhttp.onreadystatechange = function() { // 3.实时监控【代理对象】工作状态,决定何时读取服务器端返回的数据
if (xmlhttp.readyState == 4) {
// 4...........................................获得服务器端的数据
var jsonData = xmlhttp.responseText; //json形式的字符串 "[{},{}]"
//alert("jsonData "+jsonData); // 将JSON形式字符串,转换成一个真正的JSON形式对象
// eval()
var jsonObj = eval("{" + jsonData + "}");//[qid:xx,1name:xx;qid:xx,qname:xx]
// alert("jsonObj "+jsonObj);
//将返回的数据,填充到城市下拉列表--------------start
document.getElementById("qu").options.length = 0; //1.将当前城市下拉列表原有的<option>销毁掉
for (var i = 0; i < jsonObj.length; i++) { //2.将新的数据,生成<option>,并填充到下拉列表
var optionObj = new Option(jsonObj[i].qname, jsonObj[i].qid);
document.getElementById("qu").options.add(optionObj);
}
//将返回的数据,填充到城市下拉列表--------------end
}
}
}
</script>
<body>
省
<select id="province" onchange="findCity()">
<option value="0">请选择</option>
<option value="1">河北省</option>
<option value="2">辽宁省</option>
</select>
<br>城市
<select id="city" onchange="findQu()">
<option value="0">请选择</option>
</select>
<br>行政区
<select id="qu">
<option value="0">请选择</option>
</select>
</body>
</html>
2.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true">
<display-name>demo</display-name>
<servlet>
<servlet-name>CityFindServlet</servlet-name>
<servlet-class>src.com.aircode.action.CityFindServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>QuFindServlet</servlet-name>
<servlet-class>src.com.aircode.action.QuFindServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CityFindServlet</servlet-name>
<url-pattern>/CityFindServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>QuFindServlet</servlet-name>
<url-pattern>/QuFindServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.City
package src.com.aircode.entity;
public class City {
private int cid;
private String cname;
private int pid;
public City() {
super();
}
public City(int cid, String cname, int pid) {
super();
this.cid = cid;
this.cname = cname;
this.pid = pid;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
4.Qu
package src.com.aircode.entity;
public class Qu {
private int qid;
private String qname;
private int cid;
public Qu() {
super();
}
public Qu(int qid, String qname, int cid) {
super();
this.qid = qid;
this.qname = qname;
this.cid = cid;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getQname() {
return qname;
}
public void setQname(String qname) {
this.qname = qname;
}
public int getQid() {
return qid;
}
public void setQid(int qid) {
this.qid = qid;
}
}
5.CityFindServlet
package src.com.aircode.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
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 net.sf.json.JSONArray;
import src.com.aircode.entity.City;
/**
* Servlet implementation class CityFindServlet
*/
@WebServlet("/CityFindServlet")
public class CityFindServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CityFindServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String pid = request.getParameter("pid");
String sql = "select * from city where pid=?";
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<City> cityList = new ArrayList<City>();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aa", "root", "124365");
ps = con.prepareStatement(sql);
ps.setInt(1, Integer.valueOf(pid));
rs = ps.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
while (rs.next()) {
City city = new City();
city.setCid(rs.getInt("cid"));
city.setCname(rs.getString("cname"));
city.setPid(rs.getInt("pid"));
cityList.add(city);
}
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray jsonData = JSONArray.fromObject(cityList);
System.out.println(jsonData);
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonData);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
6.QuFindServlet
package src.com.aircode.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
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 net.sf.json.JSONArray;
import src.com.aircode.entity.City;
import src.com.aircode.entity.Qu;
/**
* Servlet implementation class QuFindServlet
*/
@WebServlet("/QuFindServlet")
public class QuFindServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public QuFindServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String pid = request.getParameter("cid");
String sql = "select * from qu where cid=?";
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Qu> quList = new ArrayList<Qu>();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aa", "root", "124365");
ps = con.prepareStatement(sql);
ps.setInt(1, Integer.valueOf(pid));
rs = ps.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
while (rs.next()) {
Qu qu = new Qu();
qu.setQid(rs.getInt("qid"));
qu.setQname(rs.getString("qname"));
qu.setCid(rs.getInt("cid"));
quList.add(qu);
}
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray jsonData = JSONArray.fromObject(quList);
System.out.println(jsonData);
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonData);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
作者:挑战者666888
链接:https://www.jianshu.com/p/ddce781935b3
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。