Article

Home » Server-side Coding » Java and J2EE » Java Servlets - Part 2

About the Author

Kevin Yank

author_kev1 Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote Build your own Database Driven Website using PHP and MySQL, a practical step-by-step guide published by SitePoint, and he's co-author of the SitePoint Tech Times, a bi-weekly newsletter for technically-minded web developers. Kev believes that any good webmaster should have seen at least one episode of MacGyver.

View all articles by Kevin Yank...

Java Servlets - Part 2

By Kevin Yank

August 16th, 2001

Reader Rating: 9

Page: 1 2 3 4 5 Next

As we learned in Part 1 of this article, a Java Servlet is a small Java program designed to handle Web browser requests and produce dynamically generated Web pages in response. We have already seen how to write, compile, and deploy simple Servlets. If you aren't familiar with these tasks, you should read and understand Part 1 before proceeding.

In this second part, we'll look a little more in depth at what makes Servlets tick. First off, we'll examine how the HttpServletRequest object can be used to fetch information about the browser request responsible for invoking the Servlet, such as the contents of an HTML form that was submitted as part of the request. Since forms can be submitted both with GET and POST requests, we'll learn how to make a Servlet that handles these two request types with the same code. We'll also take another stroll through the web.xml file that I introduced last time to learn how to configure your Servlets on the fly.

Finally, to demonstrate all of these concepts in action, we'll build a simple Quiz Servlet that you can expand and use to create Web-based multiple choice quizzes.

Handling GET and POST Requests

As I explained in Part 1, a Servlet handles a standard Web page request (using the HTTP GET method) by implementing a method called doGet and using it to produce and send a dynamic response. Now, while the vast majority of page requests on the Web are GET requests, another HTTP request method, POST, is very common as well.

A GET request can submit forms by sending all of the information entered in the form as part of the URL. For example, if a form contained two fields, name and email, and I typed Kevin Yank and kevin@sitepoint.com into the respective fields, then if the form were submitted using HTTP GET the browser would attempt to load a URL such as:

http://www.mysite.com/servlet/Submit?name=Kevin+Yank&email=kevin%40sitepoint.com

The Servlet (Submit in the above example) would then be able to access the values of name and email using the HttpServletRequest object (more on this in the next section).

The POST request method allows forms to be submitted more discretely. Instead of sending the submitted values as part of the URL, the values are sent invisibly as part of the HTTP request body. The mechanics of this are not important; what is important is that this circumvents nasty issues such as submitted passwords (which should presumably remain hidden at all times) appearing in the URL.

In addition, if a user bookmarks the page resulting from a GET submission, the URL that is bookmarked will include all of the information submitted in the form, so that clicking the bookmark will effectively re-submit the form to produce the same page, whereas a bookmark of a POST submission's results only includes the URL, and none of the submitted form data. There are times when each of these behaviors are desirable (search engines, for instance, tend to use GET so that users can bookmark their favorite searches to quickly resubmit them whenever needed), so you should learn how to handle both of them.

Since handling GET requests with a Servlet requires you to implement a doGet method in your Servlet class, it stands to reason that handling POST requests requires a doPost method. Here's a simple Servlet that handles both request types (RequestType.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestType extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse rsp)
               throws ServletException, IOException {
   rsp.setContentType("text/html");
   PrintWriter out = rsp.getWriter();

   out.println("<html>");
   out.println("<head><title> Request Type: GET </title></head>");
   out.println("<body>");
   out.println("<p>This page is the result of a GET request.</p>");
   out.println("</body></html>");
 }

 public void doPost(HttpServletRequest req, HttpServletResponse rsp)
               throws ServletException, IOException {
   rsp.setContentType("text/html");
   PrintWriter out = rsp.getWriter();

   out.println("<html>");
   out.println("<head><title> Request Type: POST </title></head>");
   out.println("<body>");
   out.println("<p>This page is the result of a POST request.</p>");
   out.println("</body></html>");
 }

}

Compile this Servlet (or download RequestType.class) and deploy it on your Tomcat server, then load http://localhost:8080/servlet/RequestType. You should see a page like the following:

Result of a GET RequestIf you have Apache set up with Tomcat, then http://localhost/servlet/RequestType (specifying port 8000 if necessary) should work as well. As you can see, typing a URL to load it in a Web browser produces a GET request, which is handled in this case by our RequestType Servlet's doGet method. To test out our Servlet's handling of POST requests, we must create an HTML page with a form in it to submit via POST. Create the following HTML file (PostTest.html):

<html>
<head>
<title> POST Test </title>
</head>
<body>

 <form method="POST" action="servlet/RequestType">
   <input type="submit" value="POST" />
 </form>

</body>
</html>

As you can see, this page contains a simple HTML form that is set to submit via a POST request (method="POST") to our RequestType Servlet (action="servlet/RequestType"). Place this file in Tomcat's webapps\ROOT\ directory (e.g. D:\Program Files\Apache Group\jakarta-tomcat-3.2.3\webapps\ROOT) -- this is where Tomcat expects to find non-Java Web resources such as HTML and image files. You should then be able to load http://localhost:8080/PostTest.html and click the 'POST' button to load the RequestType Servlet with a POST request:

Result of a POST RequestTo try this on your Apache server, you'll need to place PostTest.html in Apache's document root directory, or use a JkMount directive in Apache's configuration file to redirect requests for /PostTest.html to Tomcat as described in Part 1.

Often you'll want a Servlet to treat GET and POST requests the same way. In most cases you don't care whether a form is submitted via GET or POST when you're designing the Servlet to handle its processing, so the fact that you need to implement two different methods to handle both cases may seem like a bit of a pain. Instead, what you can do is write a single doGet method to handle all requests and then just make doPost call the doGet method. Here's an updated (and somewhat shorter) version of the RequestType Servlet called RequestType2 that does this (RequestType2.java):

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestType2 extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse rsp)
               throws ServletException, IOException {
   rsp.setContentType("text/html");
   PrintWriter out = rsp.getWriter();

   String requestType = req.getMethod();

   out.println("<html>");
   out.println("<head><title> Request Type: " + requestType +
               " </title></head>");
   out.println("<body>");
   out.println("<p>This page is the result of a " + requestType +
               " request.</p>");
   out.println("</body></html>");
 }

 public void doPost(HttpServletRequest req, HttpServletResponse rsp)
               throws ServletException, IOException {
   doGet(req,rsp);
 }

}

The first thing to notice is that the doPost method has been reduced to a single line, which simply calls the doGet method with the same HttpServletRequest (req) and HttpServletResponse (rsp) parameters:

   doGet(req,rsp);

Now, since this particular Servlet needs to be sensitive to the request type used to invoke it (the whole point of the Servlet is to display the request type), we use the getMethod method of the HttpServletRequest object to get a String (either "GET" or "POST") to indicate the HTTP method that was used in the request.

   String requestType = req.getMethod();

We then use the requestType variable thus produced in our output lines to display the request type where required. Compile (or download RequestType2.class) and deploy the RequestType2 Servlet and try it out if you like.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links