百木园-与人分享,
就是让自己快乐。

【JavaWeb-Ajax】网站 --- 通过省份 id 获取省份信息(通过Ajax实现局部刷新)

网站实现功能:

  • 通过输入省份编号,应用 Ajax 向服务端(tomcat服务器)发送请求,在服务端从数据库中取出对应信息打回客户端浏览器,局部刷新页面,来获取省份信息(省份名称,省份简称,省份的省会)。

 

网站结构:

【JavaWeb-Ajax】网站 --- 通过省份 id 获取省份信息(通过Ajax实现局部刷新)

 

网站预览:

【JavaWeb-Ajax】网站 --- 通过省份 id 获取省份信息(通过Ajax实现局部刷新)

 

建表语句:

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\',\'江西\',\'赣\',\'南昌\');

 

index.jsp(网站欢迎资源文件):

<%@ page contentType=\"text/html;charset=UTF-8\" language=\"java\" %>
<html>
<head>
    <title>$Title$</title>

    <%--js代码--%>
    <script type=\"text/javascript\">
        //定义函数,用来将json中的“value”(省份名称,简称,省份省会)输出到对应的三个文本框中
        function callBack(josn) {
            document.getElementById(\"provinceName\").value = josn.provinceName;
            document.getElementById(\"provinceJianCheng\").value = josn.jianCheng;
            document.getElementById(\"provinceShengHui\").value = josn.shengHui;
        }

        function search() {
            //1、创建异步对象
            var xmlHttp = new XMLHttpRequest();

            //2、绑定事件
            xmlHttp.onreadystatechange = function () {
                //异步对象把从服务端接受过来的数据处理完 且 网络请求成功 时,执行if内代码
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    //通过 xmlHttp.responseText 属性来获取服务端返回的数据
                    var data = xmlHttp.responseText;
                    //eval函数,可以将字符串转换为json对象(不重要,不用细研究此函数)
                    var josnObj = eval(\"(\" + data + \")\");
                    //调用callBack,将jsonObj中的几个“value”写入到对应文本框中
                    callBack(josnObj);
                }
            };

            //3、初始异步对象的请求参数
            //获取provinceId文本框的值
            var provinceId = document.getElementById(\"provinceId\").value;
            //发送请求(将省份id参数送到服务端)
            xmlHttp.open(\"get\", \"queryProvinceMessage?provinceId=\" + provinceId, true);

            //4、发送请求
            xmlHttp.send();
        }
    </script>
</head>
<body>
<p>通过省份ID来获取省份信息</p>
<table>
    <tr>
        <td>省份编号:</td>
        <td>
            <input type=\"text\" id=\"provinceId\">
            <input type=\"button\" value=\"搜索\" onclick=\"search()\">
        </td>
    </tr>

    <tr>
        <td>省份名称:</td>
        <td><input type=\"text\" id=\"provinceName\"></td>
    </tr>

    <tr>
        <td>省份简称:</td>
        <td><input type=\"text\" id=\"provinceJianCheng\"></td>
    </tr>
    <tr>
        <td>省会名称:</td>
        <td><input type=\"text\" id=\"provinceShengHui\"></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;
    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.ProvinceDao(连接数据库,进行查询操作并返回数据):

package com.burnyouth.dao;

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;

public class ProvinceDao {
    public ProvinceDao() {
    }

    /**
     * 通过省份id来获取省份信息
     * @param provinceId 省份id
     * @return Province对象
     */
    public Province queryProvinceById(Integer provinceId) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        Province province = null;
        try {
            connection = JdbcUtil.getConnection();
            String sql = \"select * from pro where id=?\";
            ps = connection.prepareStatement(sql);
            ps.setInt(1, provinceId);
            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                Integer id = resultSet.getInt(\"id\");
                String provinceName = resultSet.getString(\"name\");
                String jianCheng = resultSet.getString(\"jiancheng\");
                String shengHui = resultSet.getString(\"shenghui\");
                province = new Province(id, provinceName, jianCheng, shengHui);
            }
        } catch (SQLException var10) {
            var10.printStackTrace();
        } finally {
            JdbcUtil.close(connection, ps, resultSet);
        }

        return province;
    }
}

 

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>QueryProvinceMessageServlet</servlet-name>
        <servlet-class>com.burnyouth.controller.QueryProvinceMessageServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>QueryProvinceMessageServlet</servlet-name>
        <url-pattern>/queryProvinceMessage</url-pattern>
    </servlet-mapping>
</web-app>

 

com.burnyouth.controller.QueryProvinceMessageServlet(根据请求参数中的省份id,返回对应的 json 格式的省份信息):

package com.burnyouth.controller;

import com.burnyouth.dao.ProvinceDao;
import com.burnyouth.entity.Province;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class QueryProvinceMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String josn = \"\";
        PrintWriter out = null;
        ProvinceDao dao = new ProvinceDao();
        //获取省份id参数
        String provinceId =  req.getParameter(\"provinceId\");

        //当省份id不为null 且省份id不为空字符串 时,执行if内代码
        if (provinceId != null && provinceId.trim().length() > 0) {
            //通过【dao】连接数据库,获取省份信息,并返回具体的省份类
            Province province = dao.queryProvinceById(Integer.valueOf(provinceId));

            //将字符串转换为json格式的字符串
            ObjectMapper objectMapper = new ObjectMapper();
            josn = objectMapper.writeValueAsString(province);
        }

        //使浏览器以正确的编译器读取返回的信息
        resp.setContentType(\"application/json;charset=utf-8\");
        //获取输出流
        out = resp.getWriter();
        //返回信息
        out.print(josn);
        //刷新通道
        out.flush();
        //关闭通道
        out.close();
    }
}

 

 


来源:https://www.cnblogs.com/Burning-youth/p/16053913.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » 【JavaWeb-Ajax】网站 --- 通过省份 id 获取省份信息(通过Ajax实现局部刷新)

相关推荐

  • 暂无文章