Web前端-Ajax-02-根据省份id查询省份名称实例
1.需求
用户在文本框输入省份的编号id,在其他文本框中显示省份名称。
2.准备工作
2.1创建数据库与数据表
2.1.1创建数据库【db_ajax】
create database db_ajax;
2.1.2创建省份信息表【province】
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `province`;
CREATE TABLE `province` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL COMMENT ‘省份名称‘,
`jiancheng` varchar(255) DEFAULT NULL COMMENT ‘简称‘,
`shenghui` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
INSERT INTO `province` VALUES (‘1‘, ‘河北‘, ‘冀‘, ‘石家庄‘);
INSERT INTO `province` VALUES (‘2‘, ‘山西‘, ‘晋‘, ‘太原市‘);
INSERT INTO `province` VALUES (‘3‘, ‘内蒙古‘, ‘蒙‘, ‘呼和浩特市 ‘);
INSERT INTO `province` VALUES (‘4‘, ‘辽宁‘, ‘辽‘, ‘沈阳‘);
INSERT INTO `province` VALUES (‘5‘, ‘江苏‘, ‘苏‘, ‘南京‘);
INSERT INTO `province` VALUES (‘6‘, ‘浙江‘, ‘浙‘, ‘杭州‘);
INSERT INTO `province` VALUES (‘7‘, ‘安徽‘, ‘皖‘, ‘合肥‘);
INSERT INTO `province` VALUES (‘8‘, ‘福建‘, ‘闽‘, ‘福州‘);
INSERT INTO `province` VALUES (‘9‘, ‘江西‘, ‘赣‘, ‘南昌‘);
2.1.3创建城市信息表【city】
SET FOREIGN_KEY_CHECKS=0;
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`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
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‘);
2.2创建Web工程
1.创建新的Module,选择Java Enterprise--->Web Application--->next
2.为Module命名
3.在/web/WEB-INF目录下新建lib文件夹,将数据库驱动等jar包放进去
4.将lib目录下的jar包都添加到工程Library里
2.3封装JDBC工具类
配置文件:jdbc.properties
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_ajax
user=root
password=123456
工具类:JdbcUtil.java
package com.tsccg.util;
import java.sql.*;
import java.util.ResourceBundle;
/**
* @Author: TSCCG
* @Date: 2021/08/28 19:42
* 封装工具类
*/
public class JdbcUtil {
private static Connection conn = null;
private static PreparedStatement ps = null;
private static Statement stmt = null;
private static String url = null;
private static String user = null;
private static String password = null;
/**
* 静态代码块,用于注册驱动及初始化各种参数
*/
static {
try {
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driverName = bundle.getString("driverName");
url = bundle.getString("url");
user = bundle.getString("user");
password = bundle.getString("password");
//注册驱动
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return 返回Connection对象
*/
public static Connection getConn() {
try {
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
/**
* 获取预编译的数据库操作对象
* @param sql sql语句
* @return 返回PreparedStatement对象
*/
public static PreparedStatement getPs(String sql) {
try {
ps = getConn().prepareStatement(sql);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return ps;
}
/**
* 获取数据库操作对象
* @return 返回Statement对象
*/
public static Statement getStmt() {
try {
stmt = getConn().createStatement();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return stmt;
}
/**
* 关闭所有
* @param rs 查询结果集对象
*/
public static void closeAll(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
3.创建用户交互页面
在自动创建的index.jsp中编写代码。
- 编写基本页面
- 使用Ajax,调用异步对象向服务器发起请求,携带参数,申请访问SearchServlet
- 当响应数据发送回异步对象时,异步对象将响应数据赋给省份名称标签对象的value
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询省份名称</title>
</head>
<script type="text/javascript">
function search() {
//1.创建异步对象
var xmlHttp = new XMLHttpRequest();
//2.绑定onreadystatechange事件
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
document.getElementById("proName").value = xmlHttp.responseText;
}
}
//3.初始化异步对象
var proId = document.getElementById("proId").value;
var param = "proId=" + proId;
xmlHttp.open("get","search?" + param,true);
//4.发送请求
xmlHttp.send();
}
</script>
<body>
<center>
<table>
<tr>
<td>省份编号:</td>
<td>
<input type="text" id="proId">
<input type="button" value="查询" onclick="search()">
</td>
</tr>
<tr>
<td>省份名称:</td>
<td>
<input type="text" id="proName">
</td>
</tr>
</table>
</center>
</body>
</html>
4.创建Servlet用于处理请求
SearchServlet
1.调用请求对象获取请求头中的请求参数【省份id】
2.调用Dao类将sql查询命令推送到数据库服务器,返回查询结果
3.调用响应对象将查询结果写入响应体,推送回异步对象
package com.tsccg.controller;
import com.tsccg.dao.ProDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Author: TSCCG
* @Date: 2021/08/28 23:31
*/
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用请求对象获取请求头中的请求参数【省份id】
Integer proId = Integer.parseInt(request.getParameter("proId"));
//2.调用Dao类将sql查询命令推送到数据库服务器,返回查询结果
ProDao dao = new ProDao();
String proName = dao.search(proId);
//3.调用响应对象将查询结果写入响应体,推送回异步对象
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(proName);//将查询结果写入响应体
out.flush();//清除缓存
out.close();//关闭输出流
}
}
5.编写Dao类【ProDao】
用于将sql查询命令推送给数据库服务器,返回查询结果。
package com.tsccg.dao;
import com.tsccg.util.JdbcUtil;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @Author: TSCCG
* @Date: 2021/08/28 21:24
*/
public class ProDao {
/**
* 通过省份id获取省份名称
* @param id 省份id
* @return 省份名称
*/
public String search(Integer id) {
String name = null;
ResultSet rs = null;
String sql = "select name from province where id = ?";
PreparedStatement ps = JdbcUtil.getPs(sql);
try {
ps.setInt(1,id);
rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString("name");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtil.closeAll(rs);
}
return name;
}
}
6.测试
发布网站,开启服务器。