Use jquery, ajax and sertvlet to realize the linkage of provincial and municipal menus

The effect to be achieved today:

1 Create a dynamic web project in eclipse

2 Use jdbc to connect to the mysql database, you can use sqyog for graphical display, and you can encapsulate some commonly used methods of adding, deleting, modifying and checking

First create a java class and use jdbc to connect to the database

code show as below:

package BaseDAO;
import bean.she;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Base<e> {
    private static String class1 = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/xuexi?characterEncoding=utf8";
    private static String username = "root";
    private static String userpwd = "123456";
    private static Connection conn = null;
    private static Statement stmt = null;
    protected static ResultSet rs = null;

    static {
        try {
            Class. forName(class1);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public void lianjie() throws SQLException {
        conn = DriverManager.getConnection(url, username, userpwd);
        System.out.println("====Connect successfully====");
    }
    public void chuangjian() throws SQLException {
        stmt = conn.createStatement();
        System.out.println("====Chuangjie success====");
    }

    
    //    renew
    public void zhexing(String sql) throws SQLException {
        lianjie();
        chuangjian();
        stmt. executeUpdate(sql);
        System.out.println("=====sql====" + sql);
        qingchu();
    }


    public List<e> chaxun(String sql) throws SQLException {
        lianjie();
        chuangjian();
        rs = stmt. executeQuery(sql);
        System.out.println("================chaxunhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh===============" + sql);
        List<e> list = new ArrayList<e>();
        System.out.println("================chaxun222===========");
        yunxing(list);
        System.out.println("===============yunxing===========");
        qingchu();
        System.out.println("======I have completed the query=====");
        System.out.println("======listsize111111=====" + list.size());
        return list;
    }


    public void qingchu (){
        if (rs!=null) {
            try {
                rs. close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            rs=null;
        }
        if (stmt!=null) {
            try {
                stmt. close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            stmt=null;
        }
        if (conn!=null){
            try {
                conn. close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            conn=null;
        }
    }


    public void yunxing(List<e> list) throws SQLException {

    }
\t
}

And the method of adding, deleting, modifying and checking in the dao layer

package BaseDAO;

import java.sql.SQLException;
import java.util.List;
import bean.she;
public class sheDAO extends Base<she>{
public List<she> fandall() throws SQLException {
    StringBuffer sql = new StringBuffer("SELECT * FROM she");
        return super.chaxun(sql.toString());
    }
    public List<she> fandalltiaojian(StringBuffer sql) throws SQLException {
        return super.chaxun(sql.toString());
    }
    public void yunxing(List<she> list) {
        try {
            while (rs. next()) {
                String sheid = rs. getString("sheid");
                String shename = rs. getString("shename");
                she hh = new she(sheid,shename);
                list. add(hh);
            }
        }
        catch (SQLException e){
            e.printStackTrace();
        }

    }
}

When creating an entity bean

package bean;

public class she {
private String sheid;
private String shename;
public String getSheid() {
return sheid;
}
public void setSheid(String sheid) {
this.sheid = sheid;
}
public String getShename() {
return shename;
}
public void setShename(String shename) {
this.shename = shename;
}
public she(String sheid, String shename) {
super();
this.sheid = sheid;
this.shename = shename;
}
\t
@Override
public String toString() {
return "she [sheid=" + sheid + ", shename=" + shename + "]";
}
\t
}

Note that generics are used between them. base: The e in the base changes as the entity bean that shedao actually inherits and passes in changes.

3Create a service layer, create a practical business layer and logic layer

package sheservice;

import java.sql.SQLException;
import java.util.List;

import BaseDAO.sheDAO;
import bean.she;

public class sheservice {
public List<she> fand1() throws SQLException{
return new sheDAO().fandall();
}
}

Here, because our business is relatively simple, the service layer is just a function

4 Create servlet layer

Create the corresponding servlet for data interaction with the front end:

package sheservlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.she;
import sheservice.sheservice;

/**
 * Servlet implementation class shefandservlet
 */
@WebServlet("/shefandservlet.do")
public class shefandservlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("===============servletchengg================================================================================== ");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
System.out.println("----------");
List<she> list = null;
try {
list = new sheservice().fand1();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("==========================servlet================== ===========" + list. size());
StringBuffer str = new StringBuffer();
System.out.println("======str====" + str.toString());
str.append("[");
System.out.println("======str====" + str.toString());
for(int i = 0 ; i<list. size();i ++ ) {
if(i!=0) {
str.append(",");
}
str.append("{");
str.append(""sheid"");
str.append(":");
str.append(""" + list.get(i).getSheid() + """);
str.append(",");
str.append(""shename"");
str.append(":");
str.append(""" + list.get(i).getShename() + """);
str.append("}");
}
str.append("]");
\t\t
System.out.println("======str====" + str.toString());
response. getWriter(). print(str. toString());
\t\t
}
\t

}

Here, the method of converting the list data into a json string is used, and passed to the front-end jsp through the method of response.getriter().print()

5 create jsp, and introduce jquery, create ajax asynchronous request

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="//i2.wp.com/code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript">
$(function(){
alert("======56677878===");
$.ajax({
type:"get",
         url:"shefandservlet.do",
         dataType:"text",
         data:{"a":1},
         cache: false,
         success: function (data) {
        eval("msg=" + data);
       alert("======56677878===" + msg);
       var str="<option value='-1'>==Please choose province===</option>";
       for(var i =0;i<msg.length;i++){
       str + ="<option value='" + msg[i].sheid + "'>" + msg[i].shename + "</option>";
       }
       alert("======32===" + str)
       $("#s1").html(str);
         }
         
})
$("#s1").on("change",function(){
var sheid=$("#s1").val();
if(sheid!=-1){
$.ajax({
type:"get",
url:"city.do",
cache: false,
dataType:"text",
data:{"sheid":sheid},
success: function(data){
eval("citys=" + data);
alert("======citys123===" + cities);
var str="<option value='-1'>==Please select the city or county===</option>";
for(var i=0;i<citys. length;i + + ){
str + ="<option value='" + citys[i].cityid + "'>" + cities[i].cityname + "</option>";
}
alert("======str123===" + str);
$("#s2").css("display","block");
$("#s2").html(str);
}
});
}else{
$("#s2").css("display","none");
}
\t\t   
})
\t   
})
\t
\t
\t
\t





</script>
<body>
<div id="d1">
<select id="s1">
\t
\t
\t
</select>

<select id="s2" style="display: none;">
\t
\t
\t
</select>






</div>
</body>
</html>

Here I introduce the jquery package online. $.ajax sends a request to the servlet through get, and the servlet calls a method in the service to create a list collection, convert the list collection into a json string, and send it to ajax asynchronously, the asynchronous request parses the obtained json string through eval into arrays. Then splice it into an option statement, then insert it into the select through $(“#s2”).html(str); and load it through the webpage

The same is true for the information of the city, but the id of a province needs to be transmitted to the servlet through the data in ajax, and the servlet finds the information of the city corresponding to the province in the database by accepting the id. It is processed in the callback function passed to ajax in the same way. After inserting into the corresponding select, it will be displayed.

6 Summary

Finally, today’s sharing is here

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHomepageOverview 125,798 people are studying systematically