Article

Java Servlets - Part 1

Page: 1 2 3 4 5 6 Next

A Simple Servlet

When it comes right down to it, a Servlet is just a Java class, and you should already know how to write a Java class:

public class MyClassName {  
 // ... properties and methods ...  
}

But not just any class will do. Servlets for use on the Web should be subclasses of the javax.servlet.http.HttpServlet class, which is built into every Web server that supports servlets. Although different servers may implement this class differently, the properties and methods supported by it are dictated by the Java Servlet Specification. As of this writing, version 2.2 is the latest release of the spec, though version 2.3 is in the final draft stage. The documentation that makes up the specification includes a reference of all of the classes that Servlet-capable servers must provide.

So creating a Servlet is as simple as creating a subclass of HttpServlet:

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
public class MyServlet extends HttpServlet {  
 // ... properties and methods ...  
}

Notice that we're importing the three packages java.io, javax.servlet and javax.servlet.http in the above. javax.servlet.http contains the HttpServlet class that we're extending, while javax.servlet contains a number of classes related to working with Servlets and java.io contains all the standard Java classes for performing input and output. Since the vast majority of Servlets make use of classes in those latter two packages, it's best to just include them right off the bat so we don't forget later.

A Servlet must provide at least one method that is used by the Web server to handle requests. The name of the method(s) depends on the type of request we want to handle. An HTTP GET request is the simplest form of page request, and comes about either as a result of the user typing a URL or clicking on a link. To let your Servlet handle GET requests, you must provide a method called doGet as follows:

 public void doGet(HttpServletRequest req, HttpServletResponse rsp)  
               throws ServletException, IOException {  
   // ... handle GET requests  
 }

As you can see, doGet must be a public method that returns nothing (void), and takes two parameters:

  • An HttpServletRequest object (this class is part of the javax.servlet.http package), which in the above example we assign to a variable called req.
  • An HttpServletResponse object (also in javax.servlet.http), which we assign to rsp.

When this method is called, the HttpServletRequest (req) passed as a parameter will be an object that provides access to all the information related to the browser request that triggered this Servlet. Using various methods of HttpServletRequest, you can find out things like the IP address of the requesting browser, or the values sent in the URL query string (e.g. index.html?name=value). Meanwhile the HttpServletResponse (rsp) represents the response to be sent to the browser. It is this object that allows us to send HTML code back to the browser, for instance. But more on req and rsp in a moment.

If you're worried about the throws ServletException, IOException portion of the function declaration, don't be. We haven't covered this in any of the previous articles in this series, but it's really pretty simple. All this does is indicate the types of Exceptions (errors) that may occur as a result of calling this method. In this case, when the Web server calls the doGet function in order to process a GET request, it must be prepared for the fact that a ServletException or an IOException may occur, and it must handle these errors gracefully. While this sounds scary, it actually makes our job easier. An IOException, for example, could occur if the Web browser was closed before it finished downloading the response our Servlet was sending it. But since the doGet function is declared such that it may throw (cause) IOExceptions, we don't have to worry about these errors, since the Web server will handle them for us when they do occur!

Now, in this example, we'll make our Servlet send a simple HTML page to the browser in response to its request. Here's the complete code for the doGet method:

 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> Simple Servlet </title></head>");  
   out.println("<body>");  
   out.println("<p>This is a simple Servlet!</p>");  
   out.println("</body></html>");  
 }

This again isn't as complicated as it may seem at first glance. Let's step through the body of this method one line at a time:

   rsp.setContentType("text/html");

On this line, we are calling the setContentType method of the rsp variable (which you'll recall contains an HttpServletResponse object). This method sets the HTTP Content-Type header to the "text/html" MIME type, which tells the Web browser to expect an HTML Web page. Any Servlet that generates a Web page must start by setting this content type. Likewise, a Servlet that generates a plain text file would set the Content-Type to "text/plain", and a Servlet that generated a GIF file would use "image/gif".

   PrintWriter out = rsp.getWriter();

Now, since we're going to generate a Web page, we'll want to send HTML code to the Web browser. HTML code is simply plain text, and the standard Java I/O class for outputting plain text data is java.io.PrintWriter. On this line, we declare a variable called out to store a PrintWriter (recall that we imported the java.io package, so we can refer to this class directly without giving its fully qualified name). To obtain a PrintWriter object that is set up to output text as the response to the Web browser, we simply call the getWriter method of rsp, which contains our response object, and assign the returned value to our new out variable.

   out.println("<html>");

The rest of the doGet method simply uses the PrintWriter (out) to output HTML code to the browser. Just as in the sample programs in previous articles, where we could output text to the screen with System.out.println (System.out is also a PrintWriter), we can output lines of text to the Web browser with the println method of our out object. Recall that println automatically starts a new line at the end of the String that it is told to output. If you don't want to start a new line in the HTML code, you can use the print method instead of println.

Download the full MyServlet.java file or type it out from the listings above and save it somewhere convenient on your computer (I use a directory called D:\JavaDev, for example). Next, we'll see how to compile and deploy a Servlet.

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

Sponsored Links