jquery-210813-01---jquery实现ajax请求案例

jquery-210813-01—jquery实现ajax请求案例


index.jsp(发起ajax请求)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jquery实现ajax请求</title>
    <script src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">

        $(function (){
            $("#btnSearch").click(function (){
                // 获取dom的value值
                var proid = $("#proid").val();

                // 发起ajax请求
                $.ajax({
                    url:"queryJsonServlet",
                    data:{
                        "proid":proid
                    },
                    dataType:"json",
                    success:function (resp){
                        // resp是json对象
                        // alert(resp.name);
                        $("#proname").val(resp.name);
                        $("#projiancheng").val(resp.jiancheng);
                        $("#proshenghui").val(resp.shenghui);
                    }
                })
            });
        })
    </script>
</head>
  <body>
  <p>ajax格式请求使用json格式数据</p>
  <table>
      <tr>
          <td>
              省份编号:
          </td>
          <td>
              <input type="text" id="proid"/>
              <input type="submit" id="btnSearch" value="查找"/>
          </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>

QueryJsonServlet.java(接收浏览器请求,响应请求)

package com.bgy.controller;

import com.bgy.dao.ProviceObjectDao;
import com.bgy.entity.Province;
import com.fasterxml.jackson.databind.ObjectMapper;

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 {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置一个json的默认值 ,即 {}
        String json = "{}";

        // 接收请求参数
        String strProid = request.getParameter("proid");
        System.out.println("我接收到了数据");
        System.out.println("proid:"+strProid);

        // 判断请求参数是否有数据
        if ( strProid != null && strProid.trim().length()>0 ) {
            ProviceObjectDao proviceDao = new ProviceObjectDao();
            Province province = proviceDao.queryProviceNameById(Integer.valueOf(strProid));

            // 使用jackson 把province对象转为json
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(province);
        }

        // 把数据通过网络传给ajax中的异步对象,响应结果
        // 指定服务器(Servlet)返回给浏览的json格式的数据。
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        writer.close();
    }
}

ProviceObjectDao.java(连接数据库,做查询)

package com.bgy.dao;

import com.bgy.entity.Province;

import java.sql.*;

public class ProviceObjectDao {

    // 根据id获取名称
    public Province queryProviceNameById(Integer proviceID){

        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String sql = "";
        String url = "jdbc:mysql://localhost:3306/springdb?&useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "admin";

        Province province = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,username,password);

            sql = "select id,name,jiancheng,shenghui from province where id=?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1,proviceID);

            rs = pst.executeQuery();

            while (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"));
                System.out.println(province);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pst != null) {
                    pst.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }  catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return province;
    }
}

web.xml(servlet映射)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <servlet>
        <servlet-name>QueryJsonServlet</servlet-name>
        <servlet-class>com.bgy.controller.QueryJsonServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QueryJsonServlet</servlet-name>
        <url-pattern>/queryJsonServlet</url-pattern>
    </servlet-mapping>
</web-app>

Province.java(实体类)

package com.bgy.entity;

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;
    }

    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;
    }

    @Override
    public String toString() {
        return "Province{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", jiancheng='" + jiancheng + '\'' +
                ", shenghui='" + shenghui + '\'' +
                '}';
    }
}

数据库表

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值