Single architecture project development: JSON and Ajax

Posted by reeksy on Wed, 23 Feb 2022 15:15:41 +0100

1,JSON

1.1 JSON description

  • JSON(JavaScript Object Notation) JavaScript object notation (JSON comes from JS).
  • JSON features:
    • JSON is a lightweight data exchange format.
    • JSON adopts a text format that is completely independent of the language, which means that the JSON data of different programming languages are consistent.
    • JSON is easy for people to read and write, but also easy for machine parsing and generation (generally used to improve the network transmission rate).

1.2 differences between XML and JSON

  • XML: extensible markup language. It is a markup language used to mark electronic documents to make them structured.
  • JSON: (JavaScript object notation) is a lightweight data exchange format.
  • The same thing: they can all be used as a data exchange format.
  • Difference between the two:
    • XML is heavyweight and JSON is lightweight. XML takes up more bandwidth in the transmission process. JSON takes up less bandwidth and is easy to compress.
    • Both XML and JSON are used in project interaction. XML is mostly used as configuration file and JSON is used for data interaction.
    • JSON exists independently of the programming language. Any programming language can parse JSON.

1.3 JSON syntax format

{
	"id": 110,
	"name": "President Li",
	"age": 24
}

Syntax note:

  1. The outside is enclosed by {};
  2. The data appears in the form of "key: value" pairs (most of the keys appear in the form of strings, and the values can be strings, numeric values, or even other json objects);
  3. Every two key: value pairs are separated by commas (the last key: value pair omits commas);
  4. If the parameter value is of String type, quotation marks must be added; if it is of numeric type, quotation marks can be added or not;

Following the above four points, you can form a json object.
Code example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
	<script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>

    <script>

        //Custom JSON data format (objects in Java)
        var person = {"name":"tom","sex":"female", "age":12};
        console.log(person);

        //Array format
        var persons = {"person":[{"name":"tom","sex":"female", "age":12},{"name":"jack","sex":"male", "age":22}]};
        console.log(persons);

        //aggregate
        var list = [{"name":"Old five","sex":"female", "age":12},{"name":"president","sex":"male", "age":12}];
        console.log(list);

    </script>
</head>
<body>

</body>
</html>

1.4 conversion of JSON data

At present, the front and back-end ajax communication is almost in JSON format, so the conversion of JSON data is often involved in the development process.

1.4.1 introduction to fastjason

  • Fastjason is a Java library that can convert Java objects into JSON format. Of course, it can also convert JSON strings into Java objects.
  • Fastjason features are as follows:
    • It can support the serialization of Java beans into JSON strings, and can also deserialize JSON strings into Java beans.
    • Fastjason operates JSON very fast.
    • It has no dependence on other packages and is easy to use.

1.4.2 use of fastjason

  • To use the fastjason Library in Maven project, you need to add the dependency of this fastjason package in Maven's configuration file in advance.
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.3</version>
</dependency>

<dependency>
    <groupId>com.colobu</groupId>
    <artifactId>fastjson-jaxrs-json-provider</artifactId>
    <version>0.3.1</version>
</dependency>

1.4.3 converting Java objects to JSON format

  1. Define a JavaBean class named Person.
public class Person {
    private String username;
    private int age;
    private String birthday;
 	get/set method
}
  1. You can use JSON Tojsonstring() converts Java objects to JSON objects:
public class TestFastJSON {

    //Java object to JSON
    @Test
    public void javaBeanToJSON(){

        //Create Person object
        Person p = new Person("Code cloud",15, DateUtils.getDateFormart());

        //Use the toString method of JSON object to convert the object to JOSN data
        String s = JSON.toJSONString(p);

        System.out.println(s); //{"age":15,"birthday":"2020-07-03 19:54:33","username": "code cloud"}
    }


    //List set to Json
    @Test
    public void ListToJSON(){

        //Create Person object
        Person p1 = new Person("Code cloud",15, DateUtils.getDateFormart());
        Person p2 = new Person("usually celadon",13, DateUtils.getDateFormart());
        Person p3 = new Person("Xiao bin",18, DateUtils.getDateFormart());

        List<Person> list = new ArrayList<>();

        Collections.addAll(list,p1,p2,p3);

        //Use the toString method of JSON object to convert the object to JOSN data
        String s = JSON.toJSONString(list);

        System.out.println(s);
        //[{"age":15,"birthday":"2020-07-03 19:59:05","username": "code cloud"}, {"age":13,"birthday":"2020-07-03 19:59:05","username": "tiger"}, {"age":18,"birthday":"2020-07-03 19:59:05","username": "Xiaobin"}]
    }
}
  1. @ JSONField annotation in fastjason
  • Through @ JSONField, we can customize the name of the field for output, control the sorting of the field, and make serialization marks.
    • Specify the name attribute and the name of the field;
    • Use the ordinal attribute to specify the order of fields;
    • Use the serialize attribute to specify that the field is not serialized;
@Data
public class Person {
	
    //Customize the name of the output and sort the output
    @JSONField(name="USERNAME",ordinal = 1)
    private String username;

    @JSONField(name="AGE",ordinal = 2)
    private int age;

    //Exclude fields that do not need to be serialized
    @JSONField(serialize = false)
    private String birthday;

    public Person() {
    }

    public Person(String username, int age, String birthday) {
        this.username = username;
        this.age = age;
        this.birthday = birthday;
    }
}

1.4.4 converting JSON strings to Java objects

  • JSON.parseObject()
    • You can use JSON Parseobject() converts JSON strings to Java objects.
    • Note that when deserializing as an object, there must be a default parameterless constructor, otherwise an exception will be reported.
  • JSON.parseArray()
    • You can use JSON Parsearray() converts a JSON string to a collection object.
//JSON to Java object
    @Test
    public void JSONToJavaBean(){

		// Convert object to JSON string
        String json = "{\"age\":15,\"birthday\":\"2020-07-03 19:54:33\",\"username\":\"Code cloud\"}";
        Person person = JSON.parseObject(json, Person.class);
        System.out.println(person);

        // Convert JSON string to collection object
        String json2 ="[{\"age\":15,\"birthday\":\"2020-07-03 19:59:05\",\"username\":\"Code cloud\"},{\"age\":13,\"birthday\":\"2020-07-03 19:59:05\",\"username\":\"usually celadon\"},{\"age\":18,\"birthday\":\"2020-07-03 19:59:05\",\"username\":\"Xiao bin\"}]";
        List<Person> list  = JSON.parseArray(json2,Person.class);
        System.out.println(list);

    }

2,Ajax

2.1 Ajax overview

If the traditional web page needs to update the content, it must reload the whole web page. Whenever a user sends a request to the server, even if only a little local content needs to be updated, the server will refresh the whole page. The disadvantages of this approach are:

  • Performance will be reduced (a little content, refresh the whole page!)
  • The user's operation page will be interrupted (the whole page is refreshed)

2.1.1 what is Ajax

  • Ajax, namely "Asynchronous Javascript And XML", refers to a web page development technology for creating interactive web page applications.
  • Ajax = asynchronous JavaScript and XML.
  • Ajax is a technology that allows the client to communicate asynchronously with the server when interacting with the server [without refreshing the whole browser]

2.1.2 role of Ajax

  • Ajax can make web pages update asynchronously. This means that a part of a web page can be updated (local update) without reloading the whole web page.

2.1.3 benefits of Ajax

  • Reduce the burden on the server and obtain data as needed.
  • There is no need to refresh the update page to reduce the actual and psychological waiting time of users.
  • Only some pages are updated to make effective use of bandwidth.
  • Mainstream browsers support Ajax.

2.1.4 asynchronous and synchronous

  • How the browser accesses the server
    • Synchronous access: the client must wait for the response from the server, and cannot perform other operations during the waiting process.
    • Asynchronous access: the client does not need to wait for the response of the service. During the waiting period, the browser can perform other operations.

2.2 implementation of ajax in JS mode

  • ajax of JS: first appeared. Use an XmlHttpRequest object. It is specially used for sending ajax requests and receiving responses.
  • Send a request using ajax, receive a response using ajax, and refresh the page using JS.
  • Disadvantages:
    • If you use AJAX technology of JS, you need to write a lot of complex code in order to realize simple functions.
    • JS AJAX code, browser compatibility is poor.

2.3 ajax of jQuery framework

2.3.1 introduction to ajax of jQuery framework

  • jquery is an excellent js framework, which naturally encapsulates the native ajax of js. The operation method of the encapsulated ajax is simpler and more powerful.
  • There are three jquery methods related to Ajax operation that are often used in development: POST, GET and Ajax

2.3.2 GET request method

Load information via remote HTTP GET request. This is a simple GET request function. For complex Ajax parameter settings, please use $ ajax.
Get request mode syntax:

$.get(url,data,callback,type)

  • Parameter 1: url request path;
  • Parameter 2: data carried in data request
    Format: key=value or {username = 'baby', pwd:666};
  • Parameter 3: callback function after successful callback response;
  • Parameter 4: data type of type response, including text, html, xml and json;

Code example

//Send asynchronous request in JQuery get mode
function run2() {
    //1. Parameter 1 url
    var url = "/login";

    //2. Parameter 2 data
    var data = {username:"jack"};

    //3. Send get request
    $.get(url,data,function (param) {
        //Content body of data response
        alert("Response successful! Response data: " + param);
    },"text");
}

2.3.3 POST request mode

Load information via remote HTTP POST request. This is a simple POST request function. For complex Ajax parameter settings, please use $ ajax.
Post request mode syntax:

$.post(url,data,callback,type)
The four parameters are the same as the get method, but the difference is the request method.

Code example

//Send asynchronous request in JQuery post mode
function run3() {
    //1. Parameter 1 url
    var url = "/login";

    //2. Parameter 2 data
    var data = {username:"lucy"};

    //3. Send get request
    $.post(url,data,function (param) {
    	//Content body of data response
    	alert("Response successful! Response data: " + param);
    },"text");
}

2.3.4 Ajax request mode

The $. ajax() method can set the underlying parameters in more detail. This method is usually used for requests that cannot be completed by other methods.
Ajax request mode syntax:

  • Method 1: jQuery ajax({[settings]})
  • Mode 2: $ ajax({})

settings is a js literal object in the form of key value pair {name:value, name:value}. The common name attribute names are as follows:

Code example

//Send request in Ajax mode
function run4() {
 	$.ajax({
	 	url:"/login",
 		async:true, //Asynchronous
 		data:{username:"tom"},
 		type:"POST", //Request mode
 		dataType:"text", //The data type of the returned data
 		success:function (param) {
 			alert("Response successful!! " + param)
 		},
 		error:function () {
 			alert("Response failed!!")
 		}
 	});
}

2.4 case: check whether the user name has been registered

  • Requirement: the user enters the user name, and after the mouse is removed, the user will judge the user name and prompt whether the user name is available.
  • Steps:
    1. Prepare the Servlet, verify the user name, and return the result (available or not);
    2. Bind the mouse removal event to the page input box;
    3. Make asynchronous request and obtain the response result;
    4. Dynamically add HTML code according to the results;
  • Background Servlet
@WebServlet("/checkName")
public class CheckNameServelt extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //Get name
        String username = req.getParameter("username");

        //Encapsulate data
        HashMap<String,Object> map = new HashMap<>();

        //Determine whether the user exists
        if("tom".equals(username)){
            map.put("flag",true);
            map.put("msg","User name already occupied!");
            String data = JSON.toJSONString(map);
            resp.getWriter().print(data);
        }else{
            //User name is not used
            map.put("flag",false);
            map.put("msg","User name can be used!");
            String data = JSON.toJSONString(map);
            resp.getWriter().print(data);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • Foreground JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>new jsp</title>
    <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

    <script>
        $(function() {
            $("#username").blur(function () {

                //Get user name
                var name = $(this).val();

                //Judge that the user name is not empty
                if(name != null && name != ""){
                    $.ajax({
                        url:"/checkName",
                        type:"GET",
                        data:{username:name},
                        dataType:"json",
                        success:function (data) {
                            if(data.flag){
                                //Set span content body
                                $("#spanMsg").html("<font color='red'>" + data.msg+ "</font>");

                            }else if(!data.flag){
                                $("#spanMsg").html("<font color='green'>"+ data.msg + "</font>");
                            }
                        },
                        error:function () {
                            alert("Request processing failed!")
                        }
                    });

                }
            })
        });

    </script>
</head>
<body>
<form action="#" method="post">

    user name: <input type="text" id="username" name="username" placeholder="enter one user name">
    <span id="spanMsg" style="color:red"></span><br>

    password: <input type="text" name="password" placeholder="Please input a password"><br>
</form>

</body>
</html>

Topics: Java JSON Back-end Interview Ajax