Getting Started with Servlets
- Getting Started with Servlets
- The Anatomy of a Servlet
- Sending a Response to the Browser
- The HttpServlet Class
- Choosing Between Java Server Pages and Servlets
Getting Started with Servlets
In This Chapter:
A "Hello World" Servlet
The Anatomy of a Servlet
Sending a Response to the Browser
The HttpServlet Class
Choosing Between Java Server Pages and Servlets
A "Hello World" Servlet
Servlets are a little more involved than Java Server Pages, but in simple cases they aren't too bad. Listing 3.1 shows you the "Hello World" program in servlet form.
Listing 3.1 Source Code for HelloWorldServlet.java
package usingjsp; import javax.servlet.*; import java.io.*; public class HelloWorldServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws IOException { // Tell the Web server that the response is HTML response.setContentType("text/html"); // Get the PrintWriter for writing out the response PrintWriter out = response.getWriter(); // Write the HTML back to the browser out.println("<HTML>"); out.println("<BODY>"); out.println("<H1>Hello World!</H1>"); out.println("</BODY>"); out.println("</HTML>"); } }
The HTML portion of the HelloWorldServlet is probably the most recognizable part. For the sake of completeness, the browser's view of the HelloWorldServlet is shown in Figure 3.1.
Unlike Java Server Pages, servlets are pure Java classes. The good news is that you don't have to learn any additional syntax to create a servlet; the bad news is that you have to do a bit more work in your programs. As you can see from the "Hello World" servlet, the amount of work isn't really that great.
Compiling the Servlet
Before you compile the servlet, make sure the servlet classes are in your classpath. The location of the servlet classes varies depending on which servlet engine you are using, but typically they are in a file called servlet.jar. If you are using the Resin servlet engine, the servlet classes are in a file called jsdk22.jar (for version 2.2 of the Servlet API). The location of the jar file also varies depending on the servlet engine, but you usually find it in the lib direc-tory. Appendixes C-F in this book contain configuration information about several popular Web servers. If all else fails, consult the documentation for your servlet engine. In fact, you should probably consult the documentation first.
If you are having trouble compiling your servlet, see the "Troubleshooting" section at the end of this chapter.
Runtime Classpath
Unlike Java Server Pages, servlets must be in the servlet engine's classpath. When a Java Server Page runs, the JSP engine ensures that the servlet it generates is visible to the JSP engine. Unfortunately, you don't have the luxury of the JSP engine to help you out when you write servlets. Most servlet engines enable you to modify the classpath for the purpose of loading servlets, so you won't have to add all your servlet directories to the system classpath.
Listing 3.1 showed that you can put your servlet into a package. The name of the servlet becomes the fully qualified classname of the servlet. The URL used to load the servlet specifies the pathname for the servlet as /servlet/usingjsp.HelloWorldServlet (refer to Figure 3.1). Most servlet engines contain a special URL mapping for the /servlet directory, which signals that you want to run a servlet. When the Web server sees this special URL, it passes it on to the servlet engine. This /servlet directory usually picks up servlets from the classpath, so you can easily run any servlet that is in your system classpath just by appending the classname to /servlet/.
NOTE
You almost always have to set up a specific URL pattern for running servlets (such as /servlet/) or you need to set up a full URL that points to a servlet. Unlike a JSP, a servlet doesn't have an extension on the end of its name to indicate what kind of a file it is.
If you are having trouble running your servlet, see the"Troubleshooting" section at the end of this chapter.
The HelloWorldServlet In-Depth
The first thing your servlet must do is implement the Servlet interface. There are two ways to do it: subclass from a class that implements the Servlet interface or implement the Servlet interface directly in the servlet. The HelloWorldServlet takes the easier approach by subclassing an existing class that implements Servlet. There are other classes that also implement the Servlet interface, and they will be discussed shortly.
When a request comes in for a particular servlet, the servlet engine loads the servlet (if it has not yet been loaded) and invokes the servlet's service method. The method takes two arguments: an object containing information about the request from the browser and an object containing information about the response going back to the browser.
TIP
Currently, most servlet engines don't automatically reload a servlet after it has been loaded. If you recompile a servlet, you usually need to restart the servlet engine to pick up the changes. This problem should slowly disappear over time as vendors create special class loaders to reload servlets when needed.
Next, the servlet must tell the Web browser what kind of content is being returned. Most of the time, you will be returning HTML content, so set the content type to text/html. As you will see in Chapter 24, "Creating an XML Application," you can also set the content type to text/xml and return XML data back to the browser. Earlier in this chapter, Listing 3.1 showed that you set the content type of the response by invoking setContentType in the response object.
After you have set the content type you are ready to start sending text back to the browser. Of course you need some sort of output object to send the text back. Again, the response object has the methods necessary to get an output stream for writing a response. Because the "Hello World" servlet is writing out text, it only needs a PrintWriter object, so it calls the getWriter method in the response object. If you need to send binary data back to the browser, you should use the getOutputStream method in the response object.
The final part of the "Hello World" servlet should be the most obvious, and if you paid attention in Chapter 2, "Getting Started with Java Server Pages," this part should be the most familiar. The "Hello World" servlet uses the println method in the PrintWriter to send HTML back to the browser. Remember, in Chapter 2 you saw a portion of the servlet code generated by the "Hello World" Java Server Page. Aside from some extra comments, that code is almost identical to the code at the end of the "Hello World" servlet. After all, Java Server Pages eventually become servlets and there are only so many ways to send output from a servlet, so why shouldn't they be similar?