JSP/Servlet | Passing Values Between Client and Server | Passing Information to JSP with Ajax

Form submission is certainly a basic HTML feature, but these days it is not used as often. Many people dislike it because every time data is sent, the page is loaded again from the server and refreshed.

Instead of form submission, “Ajax” is often used for communication with the server. Ajax is a feature that uses JavaScript to communicate asynchronously with the server. Because it is asynchronous, meaning processing continues without waiting until the operation finishes, other operations are not blocked during communication. It can obtain necessary information in the background and update the screen display without moving to another page.

Ajax itself does not require JSP; it can be used with only HTML and JavaScript. In other words, an ordinary HTML file is enough. Use JSP as the server-side program accessed from Ajax.

It is faster to understand this by looking at an actual sample. Consider the simple example 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('input').value;
            req.open("post", "hello.jsp?param=" + encodeURI(s));
            req.setRequestHeader("User-Agent","XMLHttpRequest");
            req.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var msg = document.getElementById('msg');
                    msg.innerHTML = this.responseText;
                }
            }
            req.send();
        }

        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">Write something and send it.</p>
    <table>
        <tr>
            <td>Input</td>
            <td><input type="text" id="input" name="input"></td></tr>
        <tr>
            <td></td>
            <td><button onclick="doAction();">Send</button></td>
        </tr>
    </table>
</body>
</html>

hello.jsp

<%@ page language="java" contentType="text/plain; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String method = request.getMethod();
if ("GET".equals(method)){
    out.println("can't access!");
} else {
    String inpt = request.getParameter("param");
    out.println("You wrote '" + inpt + "'.");
}
%>

Here, index.html and hello.jsp are used. Access index.html, write something in the input form, and press the button. Ajax communication accesses hello.jsp and displays the result.

Ajax communication itself is unrelated to JSP, so the explanation is omitted here. If you are interested, look up asynchronous server communication with Ajax. Here, we will check the processing on the JSP side that Ajax accesses.

This time, hello.jsp is accessed with POST so that a result can be received. If you access this page directly with GET, it displays “can not access!”. You can distinguish between GET and POST with the request method.

String method = request.getMethod();
if ("GET".equals(method)){...omitted...}

The getMethod method of the request object returns the access method. The return value is either “GET” or “POST”. The JSP getParameter method can obtain submitted values in the same way whether the request is GET or POST. In normal use, JSP is designed so GET and POST can be handled the same way without being consciously distinguished. However, sometimes processing must be separated, such as processing for GET and processing for POST. In such cases, getMethod is used.

There should be no especially difficult parts elsewhere. What is output with out.println is sent directly to the client through Ajax communication. Also, this time we only receive a text value with Ajax. The page directive at the beginning is written as follows.

<%@ page language="java" contentType="text/plain; charset=utf-8"
    pageEncoding="utf-8"%>

If you look closely, it is contentType="text/plain; charset=utf-8". It has been changed to text/plain instead of text/html. When you are only requesting the server and receiving a result like this, you are simply outputting text, so it should be text/plain.