Java Reference
In-Depth Information
com.davidflanagan.examples.servlet.Hello
. To run this servlet, you simply
point your browser at:
http://localhost:8080/javaexamples2/servlet/hello
When the Tomcat servlet container is told to run this servlet, it knows to look for
the class in the WAR archive using the filename:
WEB-INF/classes/com/davidflanagan/examples/servlet/Hello.class
A Hello World Servlet
Example 18-1 is a listing of
Hello.java
, which implements a simple “Hello world”
servlet, illustrated in Figure 18-1. The
Hello
servlet inherits from
javax.servlet.http.HttpServlet
and overrides the
doGet()
method to provide
output in response to an HTTP GET request. It also overrides the
doPost()
method, so it can respond to POST requests in the same way. The
doGet()
method outputs a string of HTML text. By default, this string is “Hello World”.
Figure 18−1. The output of the Hello servlet
If the
Hello
servlet can determine a username, however, it greets the user by
name. The servlet looks for a username in two places, starting in the HTTP request
(an
HttpServletRequest
object), as the value of a parameter named
username
.If
the servlet cannot find a request parameter with this name, it looks for an
HttpSession
object associated with the request and sees if that object has an
attribute named
username
. Servlet-enabled web servers (i.e., servlet containers)
provide a session-tracking layer on top of the stateless HTTP protocol. The
HttpSession
object allows a servlet to set and query named attributes with a single
client session. Later in the chapter, we'll see an example that takes advantage of
the session-tracking ability of this
Hello
servlet.
Example 18−1: Hello.java
package com.davidflanagan.examples.servlet;
import javax.servlet.*;
// Basic servlet classes and interfaces
import javax.servlet.http.*;
// HTTP specific servlet stuff
import java.io.*;
// Servlets do IO and throw IOExceptions
/**
* This simple servlet greets the user. It looks in the request and session
* objects in an attempt to greet the user by name.
**/
public class Hello extends HttpServlet {