A Hello World Servlet
Example 20-1
is a listing of HelloNet.java , which implements a simple “Hello world” servlet,
illustrated in Figure 20-1.
The HelloNet
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 20-1. The output of the HelloNet servlet
If the HelloNet
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 HelloNet
servlet.
Example 20-1. HelloNet.java
package je3.servlet; import javax.servlet.*; // Basic servlet ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.