Basic use of Ajax and Json

Keywords: JSON Java Javascript xml

Catalog

I. Ajax

1. Overview

2. Implementation Method

Json

1. Overview

2. Json grammar

3. Json Data and Java Data Conversion

I. Ajax

1. Overview

Ajax (ASynchronous JavaScript And XML), that is, asynchronous JavaScript And XML. Ajax is a technology that can update part of a web page without reloading the whole web page. By exchanging a small amount of data with the server in the background, Ajax can make the web page update asynchronously.

  • Synchronization: The client has to wait for the response from the server, and the client can't do other operations during the waiting period.
  • Asynchronism: The client does not need to wait for the response of the server. In the process of processing the request by the server, the client can do other operations.

2. Implementation Method

[1] Implementation of native JS

  1. create object
  2. Establish a connection
  3. Send requests
  4. Receive response results
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>OneStar</title>
    <script>
        function send() {
            //Send asynchronous requests
            //create object
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            //Establish a connection
            xmlhttp.open("GET","ajaxServlet?username=oneStar",true)
            //Send requests
            xmlhttp.send();
            //Receive and process response results from the server
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var responsetext = xmlhttp.responseText;
                    alert(responsetext);
                }
            }
        }
    </script>
</head>
<body>
<input type="button" value="Send asynchronous requests" οnclick="send();">
</body>
</html>



@WebServlet("/ajaxServlet")
public class ajaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get the request parameters
        String username = request.getParameter("username");
        //Printing
        System.out.println(username);
        //response
        response.getWriter().write("Hello:" + username);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

[2] JQuery implementation (there are three ways)

  1. $. ajax(): $. ajax({key-value pair});
  2. $.get(): $.get(url,[data],[callback],[type])
    url: Request path
    data: Request parameters
    Callback: callback function
    type: type of response result
  3. $.post(): $.post(url,[data],[callback],[type])
    url: Request path
    data: Request parameters
    Callback: callback function
    type: type of response result

Note: When the server responds to the data, the last parameter type should be designated as "json" in order to be used as the JSON data format in the client.

You can also set MIME type to JSON type on the server side: response.setContentType("application/json;charset=utf-8");

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>OneStar</title>
    <script src="JS/jquery-3.3.1.min.js"></script>
    <script>
        function send() {
            //The $. ajax() method
            $.ajax({
                url:"ajaxServlet",  //Request path
                type:"POST",    //Request mode
                data:{"username":"oneStar","age":18} ,   //Request parameters
                success:function (data) {
                    alert(data)
                } ,      //Callback function after successful response
                error:function () {
                    alert("There's a mistake!")
                } ,     //Callback function after response error
                dataType:"text"     //Set the format of the response data received
            });

            //The $. get() method
            $.get("ajaxServlet",{username:"oneStar"},function (data) {
                alert(data);
            },"text");

            //The $. post() method
            $.post("ajaxServlet",{username:"oneStar"},function (data) {
                alert(data);
            },"text");

        }
    </script>
</head>
<body>
<input type="button" value="Send asynchronous requests" οnclick="send();">
</body>
</html>

Json

1. Overview

Json (JavaScript Object Notation), that is, JavaScript object representation, Json is now mostly used to store and exchange information grammar, data transmission between networks, it is smaller, faster and easier to parse than xml!

2. Json grammar

[1] Definition Format

Json data is composed of key-value pairs, keys are quoted, data are separated by commas, objects are saved in braces, and arrays are saved in brackets.

  • Numbers (integers or floating-point numbers)
  • String (in double quotation marks)
  • Logical value (true or false)
  • Array (in middle brackets): {"person": [{}, {}]}
  • Object (in brackets): {address: {province: {Jiangxi}}
  • null

[2] Data acquisition

  • Method 1: json object. Key name
  • Method 2: json object ["key name"]
  • Method 3: Array object [index]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>oneStar</title>
    <script>
        //1. Basic format
        var person = {"name":"Xiao Ming","age":18,"sex":"male"};
        alert(person.name);
        alert(person["name"]);

        //2. Nested format (stored objects in arrays)
        var persons = [
            {"name":"Xiao Ming","age":18,"sex":"male"},
            {"name":"Xiao Bai","age":17,"sex":"female"},
            {"name":"Small black","age":16,"sex":"male"}
            ];
        alert(persons[1].name);

        //3. Nested Format (Array of Objects Stored in Objects)
        var personss = {
            "person":[
                {"name":"Xiao Ming","age":18,"sex":"male"},
                {"name":"Xiao Bai","age":17,"sex":"female"},
                {"name":"Small black","age":16,"sex":"male"}
            ]
        };
        alert(personss.person[1].name);
    </script>
</head>
<body>
</body>
</html>

3. Json Data and Java Data Conversion

To transfer Json data between client and server in future development, the server must convert the data to code used by server if it can use Json data. Usually we use parser to convert. Common parsers are: Jsonlib, Gson, fast json, Jackson. Jackson is a Sping box. A parser built into the rack

[1]Json ----> Java

Steps:

  1. Import Jackson related jar packages
  2. Create Jackson Core Object Mapper
  3. Call the related methods of ObjectMapper for transformation

Conversion method:

  • readValue(json string data, Class)
public static void main(String[] args) throws IOException {
    //Initialization string
    String json = "{\"name\":\"oneStar\",\"age\":18,\"sex\":\"male\"}";
    //Creating ObjectMapper Objects
    ObjectMapper mapper = new ObjectMapper();
    //Convert to a java object (person object)
    person per = mapper.readValue(json,person.class);
    System.out.println(per);
}

[2]Java ----> Json

Steps:

  1. Import Jackson related jar packages
  2. Create Jackson Core Object Mapper
  3. Call the related methods of ObjectMapper for transformation

Conversion method:

  • WriteValue (parameter, obj)
    • File: Converts the obj object to a Json string and saves it to the specified file
    • Writer: Converts the obj object to a json string and fills the json data into the character output stream
    • The parameter is OutputStream: which obj pair to select is converted to a json string and the json data is filled into the byte output stream
  • writeValueAsString(obj): Converting objects to json strings

Annotations: Annotations before attributes

  • @ JsonIgnore: Exclude attributes
  • @ JsonFormat: Formatting of attribute values
public class JsonTest {
    public static void main(String[] args) throws IOException {
        Test1();
        Test2();
    }
    private static void Test1() throws IOException {
        person p = new person();
        p.setAge(18);
        p.setName("oneStar");
        p.setSex("male");

        //Creating ObjectMapper Objects
        ObjectMapper mapper = new ObjectMapper();
        //Conversion
        String per = mapper.writeValueAsString(p);
        System.out.println(per);

        //Put in the specified file after conversion
        mapper.writeValue(new File("D:\\a.txt"),p);

        //Connect data to write after conversion
        mapper.writeValue(new FileWriter("D:\\a.txt"),p);
    }

    private static void Test2() throws IOException {
        person p1 = new person();
        p1.setAge(18);
        p1.setName("oneStar");
        p1.setSex("male");

        person p2 = new person();
        p2.setAge(18);
        p2.setName("oneStar");
        p2.setSex("male");

        person p3 = new person();
        p3.setAge(18);
        p3.setName("oneStar");
        p3.setSex("male");

        List<person> list = new ArrayList<>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        //Creating ObjectMapper Objects
        ObjectMapper mapper = new ObjectMapper();
        //Conversion
        String per = mapper.writeValueAsString(list);
        System.out.println(per);
    }
}

 

Posted by alexander.s on Thu, 05 Sep 2019 23:25:17 -0700