Easy Tutorial
❮ Servlet Http Status Codes Servlet Useful Resources ❯

Servlet Form Data

In many cases, it is necessary to pass information from the browser to the web server, ultimately to the backend program. The browser can transmit this information to the web server using two methods: GET and POST.

GET Method

The GET method sends encoded user information to the requested page. The page and the encoded information are separated by the ? character, as shown below:

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default way to pass information from the browser to the web server, resulting in a long string appearing in the browser's address bar. If you are passing passwords or other sensitive information, do not use the GET method. The GET method has a size limit: the request string can contain a maximum of 1024 characters.

This information is passed using the QUERY_STRING header and can be accessed via the QUERY_STRING environment variable. Servlets use the doGet() method to handle this type of request.

POST Method

Another more reliable method to pass information to the backend program is the POST method. The POST method packages the information similarly to the GET method, but instead of sending the information as a text string after the ? character in the URL, it sends the information as a separate message. The message is transmitted to the backend program in the standard output format, which you can parse and use. Servlets use the doPost() method to handle this type of request.

Reading Form Data Using Servlet

Servlets handle form data, which is automatically parsed using different methods depending on the situation:

Example of GET Method Using URL

Below is a simple URL that uses the GET method to pass two values to the HelloForm program.

http://www.example.com/HelloForm?key1=value1&key2=value2

Here is the HelloForm.java Servlet program that processes the input from the web browser. We will use the getParameter() method to easily access the passed information:

package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class HelloForm
 */
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "Using GET Method to Read Form Data";
        // Rest of the code to handle the form data
    }
}
// Process Chinese
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
String docType = "<!DOCTYPE html> \n";
out.println(docType +
    "<html>\n" +
    "<head><title>" + title + "</title></head>\n" +
    "&lt;body bgcolor=\"#f0f0f0\">\n" +
    "&lt;h1 align=\"center\">" + title + "</h1>\n" +
    "<ul>\n" +
    "  <li><b>Site Name</b>: "
    + name + "\n" +
    "  <li><b>URL</b>: "
    + request.getParameter("url") + "\n" +
    "</ul>\n" +
    "</body></html>");
}

// Method to handle POST method request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>HelloForm</servlet-name>
    <servlet-class>com.tutorialpro.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>

Now enter ** in the address bar of your browser and ensure that the Tomcat server is started before triggering the above command. If everything goes well, you will get the following result:


Example of Using the GET Method with a Form

Below is a simple example that uses an HTML form and a submit button to pass two values. We will use the same Servlet HelloForm to process the input.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<form action="HelloForm" method="GET">
Site Name: <input type="text" name="name">
<br />
URL: <input type="text" name="url" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Save this HTML to a file named hello.html with the following directory structure:

Try entering a site name and URL, then click the "Submit" button. The GIF demonstration is as follows:


Example of Using the POST Method with a Form

Let's make a small modification to the above Servlet to handle both GET and POST methods. The following HelloForm.java Servlet program processes input given by the web browser using both GET and POST methods.

Note: If the form submission contains Chinese data, it needs to be transcoded:

String name = new String(request.getParameter("name").getBytes("ISO8859-1"), "UTF-8");
package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class HelloForm
 */
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "Reading Form Data Using POST Method";
        // Handle Chinese characters
        String name = new String(request.getParameter("name").getBytes("ISO8859-1"), "UTF-8");
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "&lt;body bgcolor=\"#f0f0f0\">\n" +
            "&lt;h1 align=\"center\">" + title + "</h1>\n" +
            "<ul>\n" +
            "  <li><b>Site Name</b>: "
            + name + "\n" +
            "  <li><b>URL</b>: "
            + request.getParameter("url") + "\n" +
            "</ul>\n" +
            "</body></html>");
    }

    // Method to handle POST method request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Now, compile and deploy the above Servlet, and test it using the hello.html with POST method as shown below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<form action="HelloForm" method="POST">
Site Name: <input type="text" name="name">
<br />
URL: <input type="text" name="url" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Below is the actual output of the form above. Try entering a URL name and URL, then click the "Submit" button. The GIF demonstration is as follows:


Passing Checkbox Data to a Servlet Program

Checkboxes are used when more than one option needs to be selected.

Below is an HTML code example, checkbox.html, a form with two checkboxes.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="tutorialpro" checked="checked" /> tutorialpro.org
<input type="checkbox" name="google"  /> Google
<input type="checkbox" name="taobao" checked="checked" /> Taobao
<input type="submit" value="Select Sites" />
</form>
</body>
</html>

Below is the CheckBox.java Servlet program that handles checkbox input from the web browser.

package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class CheckBox
 */
@WebServlet("/CheckBox")
public class CheckBox extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

        PrintWriter out = response.getWriter();
        String title = "Reading Checkbox Data";
        String docType = "<!DOCTYPE html> \n";
            out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "&lt;body bgcolor=\"#f0f0f0\">\n" +
                "&lt;h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>tutorialpro:</b>: "
                + request.getParameter("tutorialpro") + "\n" +
                "  <li><b>Google:</b>: "
                + request.getParameter("google") + "\n" +
                "  <li><b>Taobao:</b>: "
                + request.getParameter("taobao") + "\n" +
                "</ul>\n" +
                "</body></html>");
    }
}
}

// Method to handle POST method request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}
}

Setting the corresponding web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>CheckBox</servlet-name>
    <servlet-class>com.tutorialpro.test.CheckBox</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CheckBox</servlet-name>
    <url-pattern>/TomcatTest/CheckBox</url-pattern>
  </servlet-mapping>
</web-app>

The above example will display the following result:


Reading All Form Parameters

The following is a generic example that uses the getParameterNames() method of HttpServletRequest to read all available form parameters. This method returns an enumeration of the parameter names in no specific order.

Once we have an enumeration, we can loop through it in the standard way, using the hasMoreElements() method to determine when to stop, and the nextElement() method to get the name of each parameter.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

/**
 * Servlet implementation class ReadParams
 */
@WebServlet("/ReadParams")
public class ReadParams extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadParams() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String title = "Reading All Form Data";
        String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " +
            "transitional//en\">\n";
            out.println(docType +
            "<html>\n" +
```html
<head><meta charset="utf-8"><title>" + title + "</title></head>
<body bgcolor="#f0f0f0">
<h1 align="center">" + title + "</h1>
<table width="100%" border="1" align="center">
<tr bgcolor="#949494">
<th>Parameter Name</th><th>Parameter Value</th>
</tr>
</table>

Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {
    String paramName = (String)paramNames.nextElement();
    out.print("<tr><td>" + paramName + "</td>");
    String[] paramValues = request.getParameterValues(paramName);
    // Read single value data
    if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0)
            out.println("<td><i>No Value</i></td>");
        else
            out.println("<td>" + paramValue + "</td>");
    } else {
        // Read multiple values data
        out.println("<td><ul>");
        for(int i=0; i < paramValues.length; i++) {
            out.println("<li>" + paramValues[i]);
        }
        out.println("</ul></td>");
    }
    out.print("</tr>");
}
out.println("</table></body></html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Now, try the above servlet with the following form:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>

<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Math
<input type="checkbox" name="physics"  /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chemistry
<input type="submit" value="Select Subject" />
</form>

</body>
</html>

Configure the corresponding web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>ReadParams</servlet-name>
    <servlet-class>com.tutorialpro.test.ReadParams</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ReadParams</servlet-name>
    <url-pattern>/TomcatTest/ReadParams</url-pattern>
  </servlet-mapping>
</web-app>

Now, calling the Servlet using the form above will produce the following result:

You can try using the above Servlet to read other form data, such as text boxes, radio buttons, or drop-down boxes. ```

❮ Servlet Http Status Codes Servlet Useful Resources ❯