JSP/Servlet | Servlets and JSP/HTML | Accessing a Servlet with Ajax

The method explained earlier, submitting a form to pass values, does not seem very convenient. Outputting a page from a servlet with PrintWriter is quite troublesome. It is more efficient to use HTML and JSP for screen display and use servlets only for server-side processing.

One possible method is to use Ajax. Access the servlet from Ajax inside HTML, obtain the result, and display it. With this approach, the servlet side only outputs the result value, while the display is handled by HTML, making development easier.

Let’s create a sample and explain it while looking at the code. A simple example is shown below.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Hello App Engine</title>
    <style>
    h1 {
        font-size: 16pt;
        background: #AAFFAA;
        padding: 5px;
    }
    </style>
    <script type="text/javascript">
    function doAction() {
        var req =  createRequest();
        if (req == null) {
            alert("It cannot run!");
            return;
        }
        var s = document.getElementById('text1').value;
        req.open("post", "/mygaeapp", true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.onreadystatechange = function(){
            if (this.readyState == 4 && this.status == 200){
                var msg = document.getElementById('msg');
                msg.innerHTML = this.responseText;
            }
        }
        req.send("text1=" + encodeURIComponent(s));
        msg.innerHTML = "<<< please wait... >>>";
    }
         
       function createRequest(){
        var httplist = [
            function(){ return new XMLHttpRequest(); },
            function(){ return new ActiveXObjct("Msxml2.XMLHTTP"); },
            function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
        ];
        for(var i = 0;i < httplist.length;i++){
            try {
                var http = httplist[i]();
                if (http != null) return http;
            } catch(e){
                continue;
            }
        }
        return null;
    }
    </script>
</head>
<body>
    <h1>Hello App Engine!</h1>
    <p id="msg">Enter an integer</p>
    <p name="msg"></p>
    <table>
        <tr>
            <td>Input</td>
            <td><input type="text" id="text1"></td>
        </tr>
        <tr>
            <td></td>
            <td><button onclick="doAction();">Send</button></td>
        </tr>
    </table>
</body>
</html>

MyGaeAppServlet.java

package com.devkuma.mygaeapp;
 
import java.io.*;
import java.net.*;
 
import javax.servlet.http.*;
 
@SuppressWarnings("serial")
public class MyGaeAppServlet extends HttpServlet {
     
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out = response.getWriter();
        out.println("Hello, world!");
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        String param = URLDecoder.decode(request.getParameter("text1"),"utf8");
        int result = 0;
        try {
            int n = Integer.parseInt(param);
            for(int i = 1;i <= n;i++){
                result += i;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        out.println(result);
    }
}

This sample uses index.html and MyGaeAppServlet. Ajax inside the HTML accesses MyGaeAppServlet, receives the result, and displays it.

In this sample, when you enter an integer in the input form, Ajax accesses the servlet, calculates the sum from 0 to that number, receives it, and displays it. Try entering various numbers to confirm the behavior.

Now let’s look at the flow. First, creation of the XMLHttpRequest object used in Ajax communication is collected in the createRequest function. It is called to obtain an XMLHttpRequest object, open specifies the access target and opens the request, and send sets the required value and starts access. This part is JavaScript Ajax communication, so the explanation is omitted here.

The servlet-side processing is actually almost the same as the previous sample. The only differences are as follows.

  1. It uses response.setContentType("text/plain");, so it writes plain text rather than HTML.
  2. The content passed to out.println is only simple text. There are no HTML tags at all.

That is about it, although the numeric calculation processing has been newly added. Ajax usage is not something the servlet side needs to be very aware of. Basically, you can think of it as a JavaScript-side issue.