Servlet Form Data
In many cases, it is necessary to pass some information from a browser to a web server, and ultimately to the backend program. The browser uses two methods to pass this information to the web server: the GET method and the POST method.
GET Method
The GET method sends the encoded user information along with the page request. 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 method for passing information from a browser to a web server. It produces a long string that appears in the browser's address bar. If you are sending a password or other sensitive information to the server, do not use the GET method. The GET method has a size limitation: the request string can have at most 1024 characters.
This information is passed using the QUERY_STRING header and can be accessed via the QUERY_STRING environment variable. Servlets handle this type of request using the doGet() method.
POST Method
A more reliable way to pass information to a backend program is the POST method. The POST method packages information in a way similar to the GET method, but instead of sending the information as a text string after the ? character in the URL, it sends it as a separate message. The message is sent to the backend program as standard output, which you can parse and use. Servlets handle this type of request using the doPost() method.
Reading Form Data Using Servlet
Servlets handle form data, which is automatically parsed using different methods depending on the situation:
- getParameter(): You can call the request.getParameter() method to get the value of a form parameter.
- getParameterValues(): If a parameter appears more than once, call this method, which returns multiple values, such as for checkboxes.
- getParameterNames(): If you want to get a complete list of all parameters in the current request, call this method.
Example Using GET Method with URL
Here is a simple URL that uses the GET method to pass two values to the HelloForm program:
http://localhost:8080/TomcatTest/HelloForm?name=Tutorial&url=example.com
Below 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.tutorial.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 GET Method";
// Handle Chinese characters
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" +
"<body bgcolor="#f0f0f0">n" +
"<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 requests
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Then we create the following entry in the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>com.tutorial.test.HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/TomcatTest/HelloForm</url-pattern>
</servlet-mapping>
</web-app>
Now type http://localhost:8080/TomcatTest/HelloForm?name=Tutorial&url=example.com in the browser's address bar and make sure the Tomcat server is started before triggering the above command. If everything is fine, you will get the following result:
Example Using GET Method with Form
Here 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>Tutorial(example.com)</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. The directory structure is as follows:
Try entering the site name and URL, then click the "Submit" button. The GIF demonstration is as follows:
Example Using POST Method with Form
Let's make a small modification to the above Servlet so that it can handle both GET and POST methods. The following HelloForm.java Servlet program uses both GET and POST methods to process input from the web browser.
Note: If the form data contains Chinese characters, encoding conversion is needed:
String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
package com.tutorial.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" +
"<body bgcolor="#f0f0f0">n" +
"<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 requests
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Now, compile and deploy the above Servlet, and test it using hello.html with the POST method, as shown below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial(example.com)</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 above form. Try entering the site name and URL, then click the "Submit" button. The GIF demonstration is as follows:
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option needs to be selected.
Here is an HTML code example checkbox.html, a form with two checkboxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial(example.com)</title>
</head>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="tutorial" checked="checked" /> Tutorial
<input type="checkbox" name="google" /> Google
<input type="checkbox" name="taobao" checked="checked" /> Taobao
<input type="submit" value="Select Site" />
</form>
</body>
</html>
Below is the CheckBox.java Servlet program that processes the checkbox input from the web browser.
package com.tutorial.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" +
"<body bgcolor="#f0f0f0">n" +
"<h1 align="center">" + title + "</h1>n" +
"<ul>n" +
" <li><b>Tutorial Flag:</b>: "
+ request.getParameter("tutorial") + "n" +
" <li><b>Google Flag:</b>: "
+ request.getParameter("google") + "n" +
" <li><b>Taobao Flag:</b>: "
+ request.getParameter("taobao") + "n" +
"</ul>n" +
"</body></html>");
}
// Method to handle POST method requests
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Set the corresponding web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>CheckBox</servlet-name>
<servlet-class>com.tutorial.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
Here is a general example that uses the getParameterNames() method of HttpServletRequest to read all available form parameters. This method returns an enumeration containing the parameter names in an unspecified 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" +
"<head><meta charset="utf-8"><title>" + title + "</title></head>n" +
"<body bgcolor="#f0f0f0">n" +
"<h1 align="center">" + title + "</h1>n" +
"<table width="100%" border="1" align="center">n" +
"<tr bgcolor="#949494">n" +
"<th>Parameter Name</th><th>Parameter Value</th>n"+
"</tr>n");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>n");
String[] paramValues =
request.getParameterValues(paramName);
// Read single value data
if (paramValues.length == 1) {
String paramValue = paramValues;
if (paramValue.length() == 0)
out.println("<td><i>No Value</i></td>");
else
out.println("<td>" + paramValue + "</td>");
} else {
// Read multiple value data
out.println("<td><ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues);
}
YouTip