Understanding AJAX and JSON in Java Web Development

AJAX, an acronym for Asynchronous JavaScript and XML, is a web development technique that enables the creation of interactive and responsive web applications. It allows for partial updates of web pages without requiring a full page reload. AJAX facilitates this by exchanging small amounts of data with the server in the background, leading to a more dynamic user experience.

The core mechanism of AJAX involves a request initiated by a web page. This request is processed by the browser's AJAX angine, which then transmits it to the server. During this period, the client application remains fully interactive. Once the server responds with data, the AJAX engine triggers a predefined event, allowing custom JavaScript logic to execute and update specific parts of the page.

Native JavaScript AJAX implementation revolves around the browser's built-in AJAX engine object. The process typically involves these steps:

  1. Instantiate the AJAX engine object.
  2. Attach an event listener to monitor the server's response.
  3. Specify the request URL.
  4. Send the request to the server.
  5. Process the received data.

Native JavaScript AJAX Example (GET and POST)

The following HTML demonstrates the use of native JavaScript to perform both GET and POST requests to a server-side servlet, illustrating asynchronous and synchronous interactions.



<html>
<head>
    <meta charset="UTF-8">
    <title>AJAX Examples</title>
    <script type="text/javascript">
        function sendGetRequest() {
            // Asynchronous GET request
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("span1").innerHTML = xhr.responseText;
                }
            };
            xhr.open("GET", "ajaxServlet?user=Alice", true); // true for asynchronous
            xhr.send();
        }

        function sendPostRequest() {
            // Synchronous POST request
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("span2").innerHTML = xhr.responseText;
                }
            };
            xhr.open("POST", "ajaxServlet", false); // false for synchronous
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send("user=Bob");
        }
    </script>
</head>
<body>
    <input type="button" value="Send Async GET" onclick="sendGetRequest()"><span id="span1"></span>
    <br>
    <input type="button" value="Send Sync POST" onclick="sendPostRequest()"><span id="span2"></span>
    <br>
    <input type="button" value="Test Button" onclick="alert()">
</body>
</html>

Server-Side Servlet (Java)

The following Java code defines a Servlet that handles the AJAX requests. It includes a delay to demonstrate the difference between asynchronous and synchronous operations.


package com;

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

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AjaxServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // Simulate a delay to observe async/sync behavior
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String userName = request.getParameter("user");
        response.getWriter().write(Math.random() + " " + userName);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response); // Delegate POST to doGet for this example
    }
}

jQuery AJAX Integration

jQuery, a popular JavaScript library, simplifies AJAX operations by providing a more concise and powerful API. It offers several methods for making AJAX requests:

  • $.get(url, [data], [callback], [type]): For making asynchronous GET requests.
  • $.post(url, [data], [callback], [type]): For making asynchronous POST requests.
  • $.ajax(options): A comprehensive method for configurign various AJAX request parameters.

Key parameters for these methods include:

  • url: The server-side endpoint to request.
  • data: Data to be sent to the server (can be an object or JSON string).
  • callback (for $.get/$.post) or success (for $.ajax): A function executed upon successful server response.
  • type: The HTTP method (e.g., "GET", "POST").
  • dataType: The expected data type of the server's response (e.g., "text", "json", "html").
  • async: A booolean indicating whether the request should be asynchronous (default is true).

jQuery AJAX Example

This HTML snippet demonstrates using jQuery's $.get, $.post, and $.ajax methods.



<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery AJAX Examples</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript">
        function callGet() {
            $.get(
                "ajaxServlet01",
                {"name": "Alice", "age": 30},
                function(response) {
                    // Assuming response is JSON like {"name": "Tom", "age": 21}
                    alert(response.name);
                },
                "json"
            );
        }

        function callPost() {
            $.post(
                "ajaxServlet01",
                {"name": "Bob", "age": 25},
                function(response) {
                    alert(response.name);
                },
                "json"
            );
        }

        function callAjax() {
            $.ajax({
                url: "ajaxServlet01",
                async: true, // Default is true
                type: "POST",
                data: {"name": "Charlie", "age": 22},
                success: function(response) {
                    alert(response.name);
                },
                error: function() {
                    alert("Request failed");
                },
                dataType: "json"
            });
        }
    </script>
</head>
<body>
    <input type="button" value="jQuery GET" onclick="callGet()"><span id="span1"></span>
    <br>
    <input type="button" value="jQuery POST" onclick="callPost()"><span id="span2"></span>
    <br>
    <input type="button" value="jQuery AJAX" onclick="callAjax()"><span id="span3"></span>
    <br>
</body>
</html>

Server-Side Servlet for jQuery AJAX

This servlet is designed to handle requests from the jQuery AJAX examples, returning data in JSON format.


package com;

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

@WebServlet("/ajaxServlet01")
public class AjaxServlet01 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AjaxServlet01() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String name = request.getParameter("name");
        String age = request.getParameter("age");

        System.out.println("Received: Name=" + name + ", Age=" + age);

        // Respond with JSON
        response.getWriter().write("{\"name\":\"Tom\",\"age\":21}");
    }

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

Understanding JSON Format

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is built on two structures:

  1. Object: A collection of key/value pairs, enclosed in curly braces {}. Keys must be strings, and values can be strings, numbers, booleans, arrays, or other objects. Example: {"firstName": "John", "age": 30}
  2. Array: An ordered list of values, enclosed in square brackets []. Values can be of any valid JSON type. Example: [1, "apple", true]

JSON Examples in JavaScript

The following JavaScript code snippets illustrate various JSON structures and how to access their data:


// Example 1: Simple JSON Object
var person = {"firstName": "Zhang", "lastName": "Sanfeng", "age": 100};
alert(person.lastName); // Output: Sanfeng
alert(person.age);      // Output: 100

// Example 2: Array of JSON Objects
var persons = [
    {"firstName": "Zhang", "lastName": "Sanfeng", "age": 100},
    {"firstName": "Li", "lastName": "Si", "age": 25}
];
alert(persons[1].firstName); // Output: Li
alert(persons[0].age);       // Output: 100

// Example 3: Nested JSON Structure (Object containing an array)
var data = {
    "children": [
        {"name": "Xiao Shuang", "age": 28, "address": "Yangzhou"},
        {"name": "Jianning", "age": 18, "address": "Forbidden City"},
        {"name": "A Ke", "age": 10, "address": "Shanxi"}
    ]
};
alert(data.children[1].name); // Output: Jianning
alert(data.children[2].address); // Output: Shanxi

// Example 4: JSON with multiple arrays
var combinedData = {
    "groupA": [
        {"name": "Xiao Shuang", "age": 28, "address": "Yangzhou"},
        {"name": "Jianning", "age": 18, "address": "Forbidden City"}
    ],
    "groupB": [
        {"name": "Zhang Shuang", "age": 25, "address": "Jilin"},
        {"name": "Shu Jie", "age": 23, "address": "Chifeng"}
    ]
};
alert(combinedData.groupB[1].name); // Output: Shu Jie

// Example 5: Mixed JSON structure (string, object, array)
var mixedData = {
    "key1": "value1",
    "key2": {"firstName": "Zhang", "lastName": "Sanfeng", "age": 100},
    "key3": [
        {"name": "Xiao Shuang", "age": 28, "address": "Yangzhou"},
        {"name": "Jianning", "age": 18, "address": "Forbidden City"},
        {"name": "A Ke", "age": 10, "address": "Shanxi"}
    ]
};
alert(mixedData.key2.lastName);   // Output: Sanfeng
alert(mixedData.key3[2].name);    // Output: A Ke

JSON Conversion Libraries in Java

To facilitate the exchange of data between Java applications and JavaScript clients, Java objects and collections can be converted into JSON strings using various libraries. Popular choices include:

  • json-lib
  • Gson (Google)
  • Fastjson (Alibaba)

These libraries provide efficient mechanisms for serializing Java data structures into the JSON format, making it seamless to integrate with AJAX functionalities.

Tags: Ajax javascript JSON Java Web Servlets

Posted on Tue, 01 Sep 2026 16:05:30 +0000 by ldsmike88