Note: JAVA_Web phase - AJAX

Posted by falcons on Mon, 20 Dec 2021 06:43:33 +0100

1, Introduction

1.1 what is JSON

JSON (JavaScript object notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (JS specification formulated by W3C) and uses text format completely independent of programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

1.2 JSON syntax

  • [] represents an array

  • {} represents an object

  • '' indicates a value of type property name or string

  • : indicates the spacer between the attribute and the value

  • , representing the spacer of multiple attributes or the spacer of multiple elements

2, JSON parsing [ key ]

String to parse: parses the string into a Java object

//Object nested array nested object
String json1="{'id':1,'name':'JAVAEE-1703','stus':[{'id':101,'name':'Liu Yi','age':16}]}";
//array
String json2="['Beijing','Tianjin','Hangzhou']";
  • Initial class:
    • Student.java
    • Grade.java
public class Student {
    private int id;
    private String name;
    private int age;
    //get and set methods are omitted here
}
public class Grade {
    private int id;
    private String name;
    private ArrayList<Student> stus;
    //get and set methods are omitted here
}

2.1 FastJSON parsing

  • Fastjson is a Java library that can convert Java objects to JSON format. Of course, it can also convert JSON strings to Java objects
  • toJSONString() and parseObject() methods are provided to convert Java objects to JSON:
    • The toJSONString method is called to convert the object into a JSON string
    • The parseObject method, in turn, converts the JSON string to an object
public class FASTJson {
    //analysis
    @Test
    public void test1() {
        // Object nested array nested object
        String json1 = "{'id':1,'name':'JAVAEE-1703','stus':[{'id':101,'name':'Liu Ming','age':16}]}";
        // array
        String json2 = "['Beijing','Tianjin','Hangzhou']";
        //1,
        //Static method
        Grade grade=JSON.parseObject(json1, Grade.class);
        //2,
        List<String> list=JSON.parseArray(json2, String.class);
        
    }
}

toJSONString method: converts an object to a JSON string

public class FASTJson {
//generate
    @Test
    public void test2(){
        ArrayList<Student> list=new ArrayList<>();
        for(int i=1;i<3;i++){
            list.add(new Student(101+i, "Code", 20+i));
        }
        Grade grade=new Grade(100001,"Zhang San", list);
        String json=JSON.toJSONString(grade);
        System.out.println(json);
    }
}
2.1. 1 an attribute in an entity class does not want to be converted to a JSON string
1,Class implementation Serializable Interface
2,Annotate attributes
   @JSONField(serialziable=false)

2.2 Jackson analysis

  • Jackson is a framework that can serialize Java objects into JSON strings and deserialize JSON strings into Java objects;
  • Implemented by methods readValue and writeValue;
//1, String to object, collection
        ObjectMapper mapper=new ObjectMapper();
        //Single object string -- Collection
        Grade grade=mapper.readValue(json1, Grade.class);
      	//Collection string -- Collection
        List<Goods> xxx=mapper.readValue(jaskonStr, ArrayList.class);
        System.out.println(grade);
        //2,
        ArrayList<String> list=mapper.readValue(json2, 
                new TypeReference<ArrayList<String>>() {
        });
    }
//2, Convert object to JSON format string
        String json=mapper.writeValueAsString(grade);
    }
}
2.2. 1 an attribute in an entity class does not want to be converted to a JSON string
1,Class implementation Serializable Interface
2,Annotate attributes
   @JSONIgnore

2.3 browser converts JSON string to JSON object

  • JSON.stringify()
var json={name:'zs',age:34};  //object
var str=JSON.stringify(json); //Object to string

2.4 converting browser to json object

JSON.parse()

3, Ajax usage [key points]

3.1 what is AJAX?

  • AJAX is a technology that can update some web pages without reloading the whole web page.
  • AJAX = Asynchronous JavaScript and XML.
  • AJAX is a technology for creating fast dynamic web pages.
  • AJAX can make web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page.
  • Traditional web pages (without AJAX) must reload the whole web page if they need to update the content.

3.2 conversion of JSON objects in HTML pages

JSON Object to string: JSON.stringify(object)
String conversion JSON Object: JSON.parse((string)

3.2 create XMLHttpRequest object

All modern browsers support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).

var xmlhttp=new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) used ActiveX objects.

var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

For the sake of appropriateness, we should determine which version the browser supports and encapsulate the method of creating XMLHttpRequest object.

function createXMLHttpRequest() {
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("MicrosoftXMLHttp");
    }
    return xhr;
}

3.3 readyState

  • The onreadystatechange event is triggered whenever the readyState changes.

  • In the onreadystatechange event, we specify the task to be performed when the server response is ready to be processed.

  • The readyState property holds the status information of XMLHttpRequest.

  • When readyState equals 4 and the status is 200, the response is ready:

  • Here are three important properties of the XMLHttpRequest object:

attributedescribe
onreadystatechangeStore the function (or function name) and call it whenever the readyState property changes.
readyStateThe status of XMLHttpRequest is stored. Changes from 0 to 4. 0: request uninitialized 1: server connection established 2: request received 3: request processing 4: request completed and response ready
statusExample: 200: "OK"; 404: page not found
Response codedescribe
100The customer must continue to make requests
101The client requires the server to convert the HTTP protocol version according to the request
200Successful trade
201Prompt for the URL of the new file
202Accepted and processed, but not completed
203The returned information is uncertain or incomplete
204The request was received, but the returned information is empty
205After the server completes the request, the user agent must reset the currently browsed file
206The server has completed the GET request of some users
300The requested resources are available in multiple locations
301Delete request data
302The requested data was found at another address
303Suggest that customers visit other URL s or access methods
304The client has performed a GET, but the file has not changed
305The requested resource must be obtained from the address specified by the server
306The code used in the previous version of HTTP is no longer used in the current version
307Declare the temporary deletion of the requested resource
400Wrong request, such as syntax error
401Request for authorization failed
402Retain valid ChargeTo header response
403Request not allowed
404No files, queries, or URLs were found
405The method defined by the user in the request line field is not allowed
406According to the Accept request sent by the user, the requested resource is inaccessible
407Similar to 401, the user must first be authorized on the proxy server
408The client did not complete the request within the time specified by the user
409The request cannot be completed for the current resource state
410This resource no longer exists on the server and there is no further reference address
411The server rejected the user-defined content length attribute request
412One or more request header fields are in error in the current request
413The requested resource is larger than the size allowed by the server
414The requested resource URL is longer than the length allowed by the server
415The requested resource does not support the requested item format
416The request contains the range request header field. There is no range indication value within the current request resource range, and the request does not contain the if range request header field
417The server does not meet the expectation specified in the Expect header field of the request. If it is a proxy server, the next level server may not meet the request
500The server generated an internal error
501The requested function is not supported by the server
502The server is temporarily unavailable, sometimes to prevent system overload
503Server overload or suspension of maintenance
504When the gateway is overloaded, the server uses another gateway or service to respond to the user, and the waiting time is set to be long
505The server does not support or reject the HTTP version specified in the request header

3.4 the request data type is JSON

 var user = '{"username": "Liu Gang", "password": "123456"}';
        xhr.open("post", url, true);
        xhr.setRequestHeader("content-type","application/json");
        xhr.send(user)

4, [example] use of AJAX

4.1 registration and login (regular expression verification of user input + AJAX request)

  • Simulated registration method
  • Simulated Login post mode
<!--  1 get Mode initiation AJAX Request, simulate registration -->
<script>
    function check() {
        var sp = document.getElementById("sp");
        var username = document.getElementById("un").value;
        //Regular expression in user name format
        var reg=/^\w{2,16}$/;

        if (reg.test(username)) {
            //1. Create XMLHttpRequest() object
            var xhr = new XMLHttpRequest();
            //2. open setting request information
            var url = "/select?username=" + username;
            xhr.open("get", url, true);
            //3. Send send request
            xhr.send();
            //4. Set the callback function to render the page by receiving different response results from the server
            xhr.onreadystatechange = function () {
                if (xhr.status == 200 && xhr.readyState == 4) {
                    //The response result is also in the xhr object
                    var result = xhr.responseText;

                    if (result == "true") {
                        sp.innerText = "✔";
                        sp.style.color = "green";
                    } else {
                        sp.innerText = "The user already exists";
                        sp.style.color = "red";
                    }
                }
            }
        } else {
            sp.innerText = "The user name must consist of numbers, letters and underscores, 2-16 position";
            sp.style.color = "red";
        }
    }
</script>
//Submit in post mode: 1. Request header needs to be set; 2. Splice and transfer data
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

<!--  2 post Mode initiation AJAX Request, simulate login  -->   	
<script>
    function login() {
        var userNa = document.getElementById("un").value;//Get user input account
        var password = document.getElementById("pwd").value;//Get user input password
        
        var xhr = new XMLHttpRequest();
        url = "/login.do";
        xhr.open("post", url, true);
        //Because of post submission, the request header needs to be set, and the get method does not need to be set
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //Splice transfer data transmission
        var data = "userNa=" + userNa + "&password=" + password;
        xhr.send(data);
        //Set callback function
        xhr.onreadystatechange = function () {
            if (xhr.status == 200 & xhr.readyState == 4) {
                //Get the response result from xhr, json string
                var jsonStr = xhr.responseText;
                //Convert json string to object
                var jsonObj = JSON.parse(jsonStr);
                if (jsonObj.result=="yes"){
                    var dt=document.getElementById("dt");
                    dt.innerHTML="Welcome"+jsonObj.userInfo.realName;
                }else{
                    alert("Login failed")
                }
            }
        }
    }
</script>

4.2 backend Servlet processing AJAX requests

@WebServlet("/select")
public class SelectServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get AXAJ request parameters
        String username = request.getParameter("username");
        boolean isExist = new UserDao().isExistUserName(username);
        //Respond the result to the client
        response.getWriter().print(isExist);
    }
}

5, [example] select all check boxes and delete them in batch

Check the select all check box, and the check boxes of the sub tags will also be selected; On the contrary, none.

//7. Select all if the select all check box is checked, all check boxes will be checked. If not, all check boxes will be unchecked
        selectAll.onchange = function () {
            alert("Triggered the event");
            alert($(this).is(":checked"));
            if ($(this).is(":checked")) {
                alert("Come in");
                $("input[name='userCheck']").each(function () {
                    $(this).attr("checked", true);
                });
            } else {
                $("input[name='userCheck']").each(function () {
                    $(this).attr("checked", false);
                });
            }
        }

Delete all selected

//6. Method of batch deletion
    function deleteMore() {
        //1. Get the record line checked by the user
        var selectInput = $("input[name='userCheck']:checked");
        if (selectInput.length > 0) {
            var resu = confirm("Once deleted, it cannot be changed. Do you want to delete it anyway?")
            if (resu) {
                //AJAX request, batch delete
                //The splice id 1001100210051112 is sent to the back end for segmentation, and the record is deleted according to the id
                var str = "";
                selectInput.each(function () {
                    str += this.value + ",";
                });
                var xhr = createXMLHttpRequest();
                xhr.open("post", "/deleteBatch.do", true);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                var data = "data=" + str;
                xhr.send(data);
                //Callback function
                xhr.onreadystatechange = function () {
                    if (xhr.status == 200 && xhr.readyState == 4) {
                        var message = xhr.responseText;
                        alert(message);
                        getAllGoods();
                    }
                }
            } else {
                alert("You have cancelled the deletion");
            }
        } else {
            alert("You have not selected delete item");
        }
    }

Topics: Ajax