一、ajax根据省份id小程序开发定制查询省份名称
1. 需求
- 小程序开发定制用户在文本框架输入省份的编号id,小程序开发定制在其他文本框显示省份名称
- 小程序开发定制项目环境准备
- 数据库:javaweb
- 据库表:
小程序开发定制省份信息表pro
SET FOREIGN_KEY_CHECKS=0 ;DROP TABLE IF EXISTS `pro`;CREATE TABLE `pro`( `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 `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','江西','赣','南昌');
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
城市信息表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') ;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
2.Idea环境准备
3.JDBC工具类
resources包:
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/javawebuser=rootpassword=123456
- 1
- 2
- 3
- 4
类:
package com.javaweb.ajax.utils;import java.sql.*;import java.util.ResourceBundle;/** * JDBC工具类 */public class DBUtil { //静态变量,类加载时执行 //属性资源文件绑定 private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc1"); //根据属性配置文件key获取value private static String driver = bundle.getString("driver"); private static String url = bundle.getString("url"); private static String user = bundle.getString("user"); private static String password = bundle.getString("password"); static {//注册驱动,只需要注册一次就够了,放在静态代码块中,DBUtil类加载时执行 try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取数据库连接对象 * @return conn 连接对象 * @throws SQLException */ public static Connection getConnection()throws SQLException{ Connection conn = DriverManager.getConnection(url,user,password); return conn; } /** * 释放资源 * @param conn 连接对象 * @param ps 数据库操作对象 * @param rs 结果集对象 */ public static void close(Connection conn, Statement ps, ResultSet rs){ if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
4.index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html> <head> <title>ajax根据省份id获取名称</title> <script type="text/javascript"> function search(){ //发起ajax请求,传递参数给服务器,服务器返回数据 //1.创建异步对象 var xmlHttp = new XMLHttpRequest(); //2.绑定事件 xmlHttp.onreadystatechange = function () { // alert(xmlHttp.readyState) if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { // alert(xmlHttp.responseText); //更新页面,就是更新dom对象 document.getElementById("proname").value = xmlHttp.responseText; } }; //3.初始异步对象 var proid = document.getElementById("proid").value; xmlHttp.open("get","queryProvince?proid="+proid,true); //4.发送请求 xmlHttp.send(); } </script> </head> <body> <p>ajax根据省份id获取名称</p> <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> </body></html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
5.web.jsp
<servlet> <servlet-name>QueryProvince</servlet-name> <servlet-class>com.javaweb.ajax.controller.QueryProvinceServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryProvince</servlet-name> <url-pattern>/queryProvince</url-pattern> </servlet-mapping>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
6.ProvinceDao类
package com.javaweb.ajax.dao;import com.javaweb.ajax.utils.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;//使用jdbc访问数据库public class ProvinceDao { //根据id获取名称 public String queryProvinceNameById(Integer provinceId){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = ""; String name = ""; try { conn = DBUtil.getConnection(); sql = "select name from pro where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, provinceId); //执行sql rs = ps.executeQuery(); if(rs.next()){ name = rs.getString("name"); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(conn,ps,rs); } return name; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
7.QueryProvinceServlet类
package com.javaweb.ajax.controller;import com.javaweb.ajax.dao.ProvinceDao;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;public class QueryProvinceServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.out.println("响应ajax的请求"); //处理get请求 String proid = request.getParameter("proid"); System.out.println("proid:" + proid); String name = "默认是无数据"; //访问dao,查询数据库 if(proid != null && !"".equals(proid.trim())){ //创建dao对象,调用方法 ProvinceDao dao = new ProvinceDao(); name = dao.queryProvinceNameById(Integer.valueOf(proid)); } //使用HttpServletResponse输出数据 response.setContentType("text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.println(name); pw.flush(); pw.close(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
8.执行结果
二、ajax请求使用json格式的数据
1.环境准备
2.关于json用到的三个jar包
链接: https://pan.baidu.com/s/1Eo2AGLy0uQTeSOxPVcEbfg?pwd=fpuk
提取码: fpuk
3.实体类pojo:Province
package com.javaweb.ajax.pojo;public class Province { private Integer id; private String name; private String jiancheng; private String shenghui; public Province() { } public Province(Integer id, String name, String jiancheng, String shenghui) { this.id = id; this.name = name; this.jiancheng = jiancheng; this.shenghui = shenghui; } @Override public String toString() { return "Province{" + "id=" + id + ", name='" + name + '\'' + ", jiancheng='" + jiancheng + '\'' + ", shenghui=" + shenghui + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } 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; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
4.在ProvinceDao中添加以下代码
//根据id获取一个完整的Province对象 public Province queryProvinceById(Integer provinceId){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = ""; Province province = null; try { conn = DBUtil.getConnection(); sql = "select id,name,jiancheng,shenghui from pro where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, provinceId); //执行sql rs = ps.executeQuery(); if(rs.next()){ province = new Province(); province.setId(rs.getInt("id")); province.setName(rs.getString("name")); province.setJiancheng(rs.getString("jiancheng")); province.setShenghui(rs.getString("shenghui")); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.close(conn,ps,rs); } return province; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
5.QueryJsonServlet类
package com.javaweb.ajax.controller;import com.fasterxml.jackson.databind.ObjectMapper;import com.javaweb.ajax.dao.ProvinceDao;import com.javaweb.ajax.pojo.Province;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;public class QueryJsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //默认值,{} :表示json格式的数据 String json = "{}"; //获取请求参数,省份id String proid = request.getParameter("proid"); //判断proid有值时调用dao查询数据 if(proid != null && proid.trim().length() > 0){ ProvinceDao dao = new ProvinceDao(); Province p = dao.queryProvinceById(Integer.valueOf(proid)); //需要使用jackson 把 Province对象转为 json ObjectMapper om = new ObjectMapper(); json = om.writeValueAsString(p); } //把数据的数据,通过网络传给ajax中的异步对象,响应结果数据 //指定服务器端(servlet)返回给浏览器的是json格式的数据 response.setContentType("application/json;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.println(json);//输出数据 pw.flush(); pw.close(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
6.web.xml
<servlet> <servlet-name>QueryJsonServlet</servlet-name> <servlet-class>com.javaweb.ajax.controller.QueryJsonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryJsonServlet</servlet-name> <url-pattern>/queryjson</url-pattern> </servlet-mapping>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
7.myajax.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>使用json格式的数据</title> <script type="text/javascript"> function doSearch(){ //1.创建异步对象 var xmlHttp = new XMLHttpRequest(); //2.绑定事件 xmlHttp.onreadystatechange = function (){ if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var data = xmlHttp.responseText; //eval是执行括号中的代码,把json字符串转为json对象 var jsonobj = eval("(" + data + ")"); //更新dom对象 // alert("data==="+data) // callback(jsonobj); document.getElementById("proname").value = jsonobj.name; document.getElementById("projiancheng").value = jsonobj.jiancheng; document.getElementById("proshenghui").value = jsonobj.shenghui; } } //3.初始异步对象的请求参数 var proid = document.getElementById("proid").value; xmlHttp.open("get","queryjson?proid=" + proid,true); //4.发送请求 xmlHttp.send(); } //定义函数,处理服务器端返回的数据 /*function callback(json){ document.getElementById("proname").value = jsonobj.name; document.getElementById("projiancheng").value = jsonobj.jiancheng; document.getElementById("proshenghui").value = jsonobj.shenghui; }*/ </script></head><body> <p>ajax请求使用json格式的数据</p> <table> <tr> <td>省份编号:</td> <td><input type="text" id="proid"> <input type="button" value="搜索" onclick="doSearch()"> </td> </tr> <tr> <td>省份名称:</td> <td><input type="text" id="proname"></td> </tr> <tr> <td>省份简称:</td> <td><input type="text" id="projiancheng"></td> </tr> <tr> <td>省会名称:</td> <td><input type="text" id="proshenghui"></td> </tr> </table></body></html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61