網站功能:
- 網頁打開的時候,自動加載省份資訊,用戶通過選擇不同的省份串列值,對應的城市資訊也隨之變化,
網站結構:

網站預覽:

建表陳述句:
CREATE TABLE `pro` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`jiancheng` varchar(255) DEFAULT NULL,
`shenghui` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `pro` VALUES ('1','河北','冀','石家莊');
INSERT INTO `pro` VALUES ('2','山西','晉','太原市');
INSERT INTO `pro` VALUES ('3','內蒙古','蒙','呼和浩特市');
INSERT INTO `pro` VALUES ('4','遼寧','遼','沈陽');
INSERT INTO `pro` VALUES ('5','江蘇','蘇','南京');
INSERT INTO `pro` VALUES ('6','浙江','浙','杭州');
INSERT INTO `pro` VALUES ('7','安徽','皖','合肥');
INSERT INTO `pro` VALUES ('8','福建','閩','福州');
INSERT INTO `pro` VALUES ('9','江西','贛','南昌');
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`provinceid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `city` VALUES ('1', '石家莊市', '1');
INSERT INTO `city` VALUES ('2', '秦皇島', '1');
INSERT INTO `city` VALUES ('3', '保定市', '1');
INSERT INTO `city` VALUES ('4', '張家口', '1');
INSERT INTO `city` VALUES ('5', '南昌市', '9');
INSERT INTO `city` VALUES ('6', '九江市', '9');
INSERT INTO `city` VALUES ('7', '宜春市', '9');
INSERT INTO `city` VALUES ('8', '福州市', '8');
INSERT INTO `city` VALUES ('9', '廈門市', '8');
INSERT INTO `city` VALUES ('10', '泉州市', '8');
INSERT INTO `city` VALUES ('11', '龍巖市', '8');
INSERT INTO `city` VALUES ('12', '太原', '2');
INSERT INTO `city` VALUES ('13', '大同', '2');
INSERT INTO `city` VALUES ('14', '呼和浩特', '3');
INSERT INTO `city` VALUES ('15', '包頭', '3');
INSERT INTO `city` VALUES ('16', '呼倫貝爾', '3');
index.jsp(網站歡迎資源檔案):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>省市級聯查詢</title>
<script type="text/javascript" src="https://www.cnblogs.com/Burning-youth/p/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
//自定義函式,用于加載省份資料
function getData() {
$.ajax({
url: "queryProvince",
dataType: "json",
success: function (resp) {
//洗掉舊的省份select子物件
$("#province").empty();
//保留“--請選擇--”子物件
$("#province").append("<option value=''>" + "--請選擇--" + "</option>");
//將省份名稱打到省份select上
$.each(resp, function (i, n) {
$("#province").append("<option value='" + n.provinceId + "'>" + n.provinceName + "</option>");
});
}
});
}
//自定義函式,用于處理服務端回傳的資料
function callBack(resp) {
//清空舊的省份串列子物件
$("#city").empty();
$.each(resp,function (i, n) {
$("#city").append("<option value '" + n.cityId + "'>" + n.cityName + "</option>");
});
}
$(function () {
//加載省份資訊
getData();
//省份串列選中值改變時,呼叫的方法:
$("#province").change(function () {
//獲取已被選中的串列值
var id = $("#province>option:selected").val();
//以 get 方式向服務端發送請求
$.get("queryCity", {provinceId: id}, callBack, "json");
});
})
</script>
</head>
<body>
<p>省市級聯查詢,使用 Ajax,jQuery</p>
<table border="1px">
<tr>
<td>省份:</td>
<td>
<select id="province">
<option value="">--請選擇--</option>
</select>
</td>
</tr>
<tr>
<td>城市:</td>
<td>
<select id="city">
<option value="">--請選擇--</option>
</select>
</td>
</tr>
</table>
</body>
</html>
com.burnyouth.util.JdbcUtil(JDBC工具類):
package com.burnyouth.util;
import java.sql.*;
public class JdbcUtil {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private JdbcUtil() {
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/burning_youth"
, "root", "888");
}
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
com.burnyouth.entity.Province(省份物體類):
package com.burnyouth.entity;
public class Province {
private Integer provinceId;
private String provinceName;
public Province() {
}
public Integer getProvinceId() {
return provinceId;
}
public void setProvinceId(Integer provinceId) {
this.provinceId = provinceId;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
}
com.burnyouth.entity.City(城市物體類):
package com.burnyouth.entity;
public class Province {
private Integer provinceId;
private String provinceName;
private String jianCheng;
private String shengHui;
public Province() {
}
public Province(Integer provinceId, String provinceName, String jianCheng, String shengHui) {
this.provinceId = provinceId;
this.provinceName = provinceName;
this.jianCheng = jianCheng;
this.shengHui = shengHui;
}
public Integer getProvinceId() {
return provinceId;
}
public void setProvinceId(Integer provinceId) {
this.provinceId = provinceId;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getJianCheng() {
return jianCheng;
}
public void setJianCheng(String jianCheng) {
this.jianCheng = jianCheng;
}
public String getShengHui() {
return shengHui;
}
public void setShengHui(String shengHui) {
this.shengHui = shengHui;
}
}
com.burnyouth.dao.QueryProvinceDao(連接資料庫,進行查詢操作并回傳資料):
package com.burnyouth.dao;
import com.burnyouth.entity.City;
import com.burnyouth.entity.Province;
import com.burnyouth.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class QueryProvinceDao {
//查詢資料中所有省份
public List<Province> queryProvince(){
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
List<Province> provinces = new ArrayList<>();
try {
connection = JdbcUtil.getConnection();
//按照id升序輸出
String sql = "select * from pro order by id";
ps = connection.prepareStatement(sql);
resultSet = ps.executeQuery();
while (resultSet.next()) {
Province province = new Province();
province.setProvinceId(resultSet.getInt("id"));
province.setProvinceName(resultSet.getString("name"));
provinces.add(province);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.close(connection,ps,resultSet);
}
return provinces;
}
//查詢省份對應的所有城市
public List<City> queryCity(Integer provinceId){
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
City city = null;
List<City> citys = new ArrayList<>();
try {
connection = JdbcUtil.getConnection();
String sql = "select * from city where provinceid=?";
ps = connection.prepareStatement(sql);
ps.setInt(1,provinceId);
resultSet = ps.executeQuery();
while (resultSet.next()) {
city = new City();
city.setCityId(resultSet.getInt("id"));
city.setCityName(resultSet.getString("name"));
citys.add(city);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.close(connection,ps,resultSet);
}
return citys;
}
}
xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>QueryProvinceServlet</servlet-name>
<servlet-class>com.burnyouth.controller.QueryProvinceServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>QueryCityServlet</servlet-name>
<servlet-class>com.burnyouth.controller.QueryCityServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>QueryProvinceServlet</servlet-name>
<url-pattern>/queryProvince</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>QueryCityServlet</servlet-name>
<url-pattern>/queryCity</url-pattern>
</servlet-mapping>
<!--設定一下歡迎資源檔案-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
com.burnyouth.controller.QueryProvinceServlet(回傳 json 格式的省份資訊):
package com.burnyouth.controller;
import com.burnyouth.dao.QueryProvinceDao;
import com.burnyouth.entity.Province;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class QueryProvinceServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json = "";
QueryProvinceDao dao = new QueryProvinceDao();
List<Province> provinces = new ArrayList<>();
PrintWriter out = null;
provinces = dao.queryProvince();
//將list轉為json格式的字串
if (provinces != null) {
//呼叫Jackson工具庫,實作List ---> json
ObjectMapper objectMapper = new ObjectMapper();
json = objectMapper.writeValueAsString(provinces);
}
//使客戶端瀏覽器使用正確的編輯器解讀資料
response.setContentType("application/json;charset=utf-8");
out = response.getWriter();
//輸出json資料
out.write(json);
out.flush();
out.close();
}
}
com.burnyouth.controller.QueryCityServlet(根據客戶端發送過來的省份 id ,回傳對應的城市資訊【json 格式】):
package com.burnyouth.controller;
import com.burnyouth.dao.QueryProvinceDao;
import com.burnyouth.entity.City;
import com.burnyouth.entity.Province;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class QueryCityServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json = "";
//獲取省份id
String provinceId = request.getParameter("provinceId");
QueryProvinceDao dao = new QueryProvinceDao();
List<City> cities = new ArrayList<>();
PrintWriter out = null;
cities = dao.queryCity(Integer.valueOf(provinceId));
//將list轉為json格式的字串
if (provinceId != null && !"".equals(provinceId.trim())) {
//呼叫Jackson工具庫,實作List ---> json
ObjectMapper objectMapper = new ObjectMapper();
json = objectMapper.writeValueAsString(cities);
}
response.setContentType("application/json;charset=utf-8");
out = response.getWriter();
//輸出json資料
out.write(json);
out.flush();
out.close();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454615.html
標籤:Java
上一篇:IO(位元組流的讀寫操作)
