Article
Java Servlets - Part 2
Form Handling
As we saw in Part 1, every time a Servlet is asked to handle a page request, it is provided with an HttpServletRequest object, which embodies a complete description of the request. If the page request occurs as a result of a form submission, then this request object contains the values that were submitted in each of the form fields. In this section, I'll show you how to access those values and use them in your Servlets to produce dynamic pages in response.
Retrieving form parameters in a Servlet is really quite simple; you simply use the getParameter method of the HttpServletRequest object. For example, to retrieve the value of the 'name' field and store it in a String variable name, you would use the following:
String name = req.getParameter("name");
Simple, right? Unlike some other languages, Java Servlets use a single method to retrieve request parameters like these whether they were submitted as part of a form with an HTTP POST request, or were included in the URL query string. Let's see an example of this in practice (Greeting.java):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Greeting extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
// Get the name parameter value
String name = req.getParameter("name");
// If a name was specified, build a personalized greeting
String greeting;
if (name == null)
greeting = "Hi there!";
else
greeting = "Hi, " + name + "!";
out.println("<html>");
out.println("<head><title> Weclome to my site! </title></head>");
out.println("<body>");
out.println("<p>" + greeting + "</p>");
out.println("</body></html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
doGet(req,rsp);
}
}
The code given above is relatively straightforward, but let's break down the important lines:
// Get the name parameter value
String name = req.getParameter("name");
First, we retrieve the 'name' parameter. Now, if the request did not include a 'name' parameter, this would return null -- the Java equivalent of nothing. Thus, before we create a personalized greeting with name, we need to check if it's null. If it is, we use a more impersonal greeting that doesn't use name:
// If a name was specified, build a personalized greeting
String greeting;
if (name == null)
greeting = "Hi there!";
else
greeting = "Hi, " + name + "!";
Finally, we display greeting as part of the page:
out.println("<p>" + greeting + "</p>");
Compile this Servlet (or download Greeting.class), then deploy and load it, and you should see something like this:
As expected, since we didn't provide a 'name' parameter for our request, getParameter("name") returns null, and the generic greeting is displayed. Now, to test the personalized greeting, you could create an HTML file with a form in it like the following:
<form action="/servlet/Greeting" method="POST">
Your name: <input type="text" name="name" /><br />
<input type="submit" value="Greet me!" />
</form>
You can do that if you're especially anxious to see a form submission in action, but for purposes of testing our Servlet we can use a much simpler method. Just add a 'name' parameter to the URL you used to load the Servlet above (e.g. http://localhost:8080/servlet/Greeting?name=Kev). This is exactly how the form would be submitted if you specifed method="GET" in the <form> tag above. Here's what you should see:
Now, instead of using a separate HTML file with a <form> tag in it, you could have the Servlet itself prompt the user with a form. The following Servlet, Greeting2 (Greeting2.java), is a modified version of the Greeting Servlet we created above. This time, if the 'name' parameter is not set, the Servlet displays a form prompting the user for his or her name:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Greeting2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
// Get the name parameter value
String name = req.getParameter("name");
// If a name was specified, build a personalized greeting
String greeting;
if (name == null) {
// Get the URL of this Servlet
StringBuffer action = HttpUtils.getRequestURL(req);
greeting = "<form action=\"" + action + "\" method=\"POST\">\n";
greeting += " Your name: ";
greeting += " <input type=\"text\" name=\"name\" /><br />\n";
greeting += " <input type=\"submit\" value=\"Greet me!\" />\n";
greeting += "</form>\n";
} else greeting = "Hi, " + name + "!";
out.println("<html>");
out.println("<head><title> Weclome to my site! </title></head>");
out.println("<body>");
out.println("<p>" + greeting + "</p>");
out.println("</body></html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
doGet(req,rsp);
}
}
Let's look at the important changes here. If the browser doesn't send a 'name' parameter with its request, then the variable name will be assigned a value of null as before. Instead of displaying a generic message, however, our new Servlet will display a form. Since we want that form to be submitted back to the Servlet, we need to obtain the URL that the browser used to load the Servlet and output that as the action parameter of the <form> tag.
One would normally expect the URL to be available from a method of the HttpServletRequest object, but in fact that object only has methods to retrieve small portions of the URL, such as the protocol or path of the request. Instead, the Servlet API includes a class called HttpUtils, which has a number of static methods (methods that belong to the class instead of to objects of the class) for performing useful operations related to Servlets. The HttpUtils.getRequestURL method takes a HttpServletRequest object as a parameter and returns the URL:
if (name == null) {
// Get the URL of this Servlet
StringBuffer action = HttpUtils.getRequestURL(req);
The only catch is that it returns the URL as a StringBuffer instead of the more familiar String. StringBuffers are basically just Strings that can be modified without having to create a new object. As far as printing out its value as part of the <form> tag, you can treat it just like a String:
greeting = "<form action=\"" + action + "\" method=\"POST\">\n";
Note that we place backslashes before any quotes (") in the code so they don't interfere with the quotes that mark the beginning and end of the String of text. We also use the special \n code to represent line breaks that should appear in the HTML.
Compile (or download Greeting2.class) and deploy this new Servlet, then load it (http://localhost:8080/servlet/Greeting2). You should be presented with a form that, when submitted, produces a page with a personalized greeting!