Java0 Basics_ day18_ Front end and back end integration of Java Web_ Ajax

Keywords: Java Back-end

Tags: JavaScript front end, HttpServlet back end, XML JSON mediation

 

1. Introduction to Ajax

Ajax is an asynchronous combination of JS and XML, which can be understood as a new method. It integrates the front-end JavaScript, HTML, CSS, DOM programming and the back-end httpservlet Tomcat and Mysql databases. JS is used to create asynchronous objects and send requests instead of browsers, while Servlet is used to operate the database and return data. The two are unified by XML or json.

[note] most of them are JS and JSON, because JSON is lightweight, small and easy to parse.

2.Ajax four steps

Step 1: create the asynchronous object XMLHttpRequest → XHR in the front end

var xmlHttp = new XMLHttpRequest();

Step 2: register web page status change events

xmlHttp.onreadystatement = function(){

    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        //Process the returned result and reflect it on the DOM object; xmlhttp.responseText is generally required;
    }
}

Step 3: splice string, URL setting and open connection

var name = document.getElementById("name").value;
var tizhong = document.getElementById("tizhong").value;
var shengao = document.getElementById("shengao").value;
 //Splice URL format
var param = "name="+name+"&"+"tizhong="+tizhong+"&"+"shengao="+shengao;
xmlhttp.open("get","bimajaxurl?"+param,true);//Send as URL

Step 4: send data

 xmlhttp.send();

[interactive process] user input http://localhost:8080/jj/ , and then automatically go to index.html and index.jsp under the site. The latter displays the input box for user input, then obtains the input information through index.jsp, constructs Ajax asynchronous objects through four steps, and splices them into URL strings for data access; The back-end Servlet obtains several fields from the URL sent, and then returns the data after calculation, which is displayed on the front-end page.

[technology involved] index.jsp → four steps → URL → getParameter → background calculation → response.getWriter().print() → foreground acquisition → asynchronous object. responseText → update DOM

3.Ajax project → return the query result of the province according to the number

Raw materials: create a table with mysql and query from the table

DROP TABLE IF EXISTS `province`;
CREATE TABLE `province` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL COMMENT 'Province name',
  `jiancheng` varchar(255) DEFAULT NULL COMMENT 'abbreviation',
  `shenghui` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;


INSERT INTO `province` VALUES ('1', 'Hebei', 'Hope', 'Shijiazhuang');
INSERT INTO `province` VALUES ('2', 'Shanxi', 'Jin', 'Taiyuan City');
INSERT INTO `province` VALUES ('3', 'Inner Mongolia', 'Meng', 'Hohhot	');
INSERT INTO `province` VALUES ('4', 'Liaoning', 'Liao', 'Shenyang');
INSERT INTO `province` VALUES ('5', 'Jiangsu', 'Soviet', 'Nanjing');
INSERT INTO `province` VALUES ('6', 'Zhejiang', 'Zhejiang', 'Hangzhou');
INSERT INTO `province` VALUES ('7', 'Anhui', 'Wan', 'Hefei');
INSERT INTO `province` VALUES ('8', 'Fujian', 'Min', 'Fuzhou');
INSERT INTO `province` VALUES ('9', 'Jiangxi', 'short name for Jiangxi province', 'Nanchang');

The table data is shown in the figure below:

Idea: omitted

code:

//index.jsp file
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Provinces and cities</title>
</head>
<script type="text/javascript">//Asynchronous objects send requests instead of browsers
function serachPro(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      document.getElementById("mydata").innerHTML = "The provinces are:"+xmlhttp.responseText;
    }
  }
  var number = document.getElementById("number").value;
  var param = "number="+number;
  xmlhttp.open("get","dianji?"+param,true);//Send as URL
  xmlhttp.send();
}
</script>
<body>
<p>Write numbers and print provinces</p>
<div>
  Please enter a number:<input type="text" id="number"/><br/>
  <input type="button" value="Click my province to query" onclick="serachPro()"/>
</div>
<div id="mydata">...Querying province data...</div>
</body>
</html>
//web.xml file
<?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>sf</servlet-name>
        <servlet-class>noprovince</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sf</servlet-name>
        <url-pattern>/dianji</url-pattern>
    </servlet-mapping>


</web-app>
//main program
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;
import java.sql.*;

public class noprovince extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String name = request.getParameter("number");
        response.setContentType("text/html;charset=utf-8");
        Connection col = null;
        PreparedStatement ps = null;  //Becomes a precompiled Statemnet object
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            col = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123456");
            String sql = "select name from province where id =? ";
            ps = col.prepareStatement(sql);
            ps.setString(1, request.getParameter("number"));
            rs = ps.executeQuery();

           PrintWriter pw =  response.getWriter();
            while(rs.next()){
//                System.out.println(rs.getString(1));
                pw.print(rs.getString(1));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch(SQLException e ){
            e.printStackTrace();
        }finally {
            if (rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (col !=null) {
                try {
                    col.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

Summary: the front end of the project adopts JS and Ajax objects, and then sends the data to the Servlet object in the background in URL. After querying the JDBC database, the results are returned to the front end, and then the display is updated asynchronously.

4.Ajax and Json front and back ends

The third point above returns a single value. How can it be returned in the json format most commonly used in actual development?

Taking the above example as an example, the user enters the number value and requires json as a bridge to return to the corresponding text box. The effect is as follows:

Idea: the general process is similar to 3. Splice the URL in id form, and then return the json string, as shown in the following figure:

  Specific code:

Step 1: the servlet creates a new province class and formats the records queried in mysql as a province object;

public class provinceTable {
    //Create the entity class corresponding to the entity table
    private  int id;//Set the id to Integer type;
    private  String name;
    private  String jiancheng;
    private  String shenghui;

    public provinceTable(int id, String name, String jiancheng, String shenghui) {
        this.id = id;
        this.name = name;
        this.jiancheng = jiancheng;
        this.shenghui = shenghui;
    }

    public provinceTable() {
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }


}

Step 2: convert it to JSON object

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class jsontest {
    public static void main(String[] args) throws Exception{
        //Convert jackson to json object;
        //Create the entity class corresponding to the entity table
        provinceTable p = new provinceTable(3,"Hebei","Hope","Shijiazhuang");
        //transformation:
        ObjectMapper om = new ObjectMapper();
        String jsonFromJava = om.writeValueAsString(p);
        System.out.println("The result of the conversion is" + jsonFromJava);
    }
}

[note] the built-in methods of several library files are used here to convert java objects into json objects!

  Step 3: front end packaging

<!--index.jsp-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Provinces and cities</title>
</head>
<script type="text/javascript">//Asynchronous objects send requests instead of browsers
function serachPro(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      // document.getElementById("provin").value = xmlhttp.responseText;
      //Parse json string;
      // document.getElementById("provin_city").value = xmlhttp.responseText;
      // document.getElementById("provinsimple").value = xmlhttp.responseText;
      var data = xmlhttp.responseText;
      //Convert String to json object
      var jsonObj =eval("("+data+")") ;//To get a string in json format, you need to convert it into a json object
      document.getElementById("provin").value = jsonObj["name"];
      document.getElementById("provin_city").value =  jsonObj["shenghui"];
      document.getElementById("provinsimple").value =  jsonObj["jiancheng"];
    }
  }
  var number = document.getElementById("number").value;
  var param = "number="+number;
  xmlhttp.open("get","dianji?"+param,true);//Send as URL
  xmlhttp.send();
  alert("Test asynchrony and synchronization");
}
</script>
<body>
<p>Write numbers and print province information</p>
<div>
  Please enter a number:<input type="text" id="number"/><br/>
  Province Name:<input type="text" id="provin"/><br/>
  Province abbreviation:<input type="text" id="provinsimple"/><br/>
  Capital of the province:<input type="text" id="provin_city"/><br/>

  <input type="button" value="Click me to inquire" onclick="serachPro()"/>

</div>
<div id="mydata">...Querying, please wait...</div>
</body>
</html>

Step 4: register web.xml

<?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>sf</servlet-name>
        <servlet-class>noprovince</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sf</servlet-name>
        <url-pattern>/dianji</url-pattern>
    </servlet-mapping>


</web-app>

Step 5: background Servlet main program

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;
import java.sql.*;

public class noprovince extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String name = request.getParameter("number");
//        response.setContentType("text/html;charset=utf-8");
        //Tell the browser that what I am returning now is data in json format;
        response.setContentType("application/json;charset=utf-8");
        Connection col = null;
        PreparedStatement ps = null;  //Becomes a precompiled Statemnet object
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            col = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123456");
            String sql = "select * from province where id =? ";
            ps = col.prepareStatement(sql);
            ps.setString(1, request.getParameter("number"));
            rs = ps.executeQuery();
            provinceTable pro;
            String jsonFromJava="{}";//The definition here is to ensure that an object in json format can be transmitted back;
           PrintWriter pw =  response.getWriter();
            while(rs.next()){
//                System.out.println(rs.getString(1));
//                pw.print(rs.getString(1));//
                int id = Integer.valueOf(rs.getString("id"));
                String name = rs.getString("name");
                String jiancheng = rs.getString("jiancheng");
                String shenghui = rs.getString("shenghui");

               pro  = new provinceTable(id,name,jiancheng,shenghui);
               //Convert to json object;
                ObjectMapper om = new ObjectMapper();
                 jsonFromJava = om.writeValueAsString(pro);
//                System.out.println("the result after conversion is" + jsonFromJava);
                pw.print(jsonFromJava);//Transfer back string;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch(SQLException e ){
            e.printStackTrace();
        }finally {
            if (rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (col !=null) {
                try {
                    col.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }



    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

Step 6: configure Tomcat server and introduce the above dependent libraries!

5. Summary

5.1 synchronous and asynchronous

In this case, we found that the request of Ajax object is asynchronous, that is, after sending the request, he does not have to wait for the servlet to send back the response information, and can carry out other operations, such as creating a new Ajax object, pop-up window, etc. the key to controlling whether it is asynchronous is the parameters in the open method of Ajax object. If it is true, it is asynchronous, otherwise it is synchronous.

5.2 commissioning

In the process of writing the program, we must write test statements and test step by step to reduce the cost of error adjustment in the later stage, such as adding print statements, adding alert pop-up statements, etc.

Posted by jrinco11 on Sun, 28 Nov 2021 08:21:46 -0800