Java Reference
In-Depth Information
Example 18−1: Hello.java (continued)
// This method is invoked when the servlet is the subject of an HTTP GET
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
// See if the username is specified in the request
String name = request.getParameter("username");
// If not, look in the session object. The web server or servlet
// container performs session tracking automatically for the servlet,
// and associates a HttpSession object with each session.
if (name == null)
name = (String)request.getSession().getAttribute("username");
// If the username is not found in either place, use a default name.
if (name == null) name = "World";
// Specify the type of output we produce. If this servlet is
// included from within another servlet or JSP page, this setting
// will be ignored.
response.setContentType("text/html");
// Get an stream that we can write the output to
PrintWriter out = response.getWriter();
// And, finally, do our output.
out.println("Hello " + name + "!");
}
// This method is invoked when the servlet is the subject of an HTTP POST.
// It calls the doGet() method so that this servlet works correctly
// with either type of request.
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
doGet(request, response);
}
}
Running the Hello Servlet
Before you can run this servlet, you must compile and deploy it as described at
the beginning of the chapter. To run a servlet, issue a request for it with a web
browser. The URL you use depends on where the web server is running and how
you deployed the servlet. If you are running Tomcat (or another 2.2-compliant
servlet container) on your local machine, if the web server is listening on port
8080, and if you deploy the servlet as part of a web application named javaexam-
ples2 , you can run the servlet by pointing your browser at:
http://localhost:8080/javaexamples2/servlet/hello
This should display a web page that reads “Hello World”. For slightly more sophis-
ticated output, provide a request parameter with a URL like the following (which
was used to produce the output in Figure 18-1):
http://localhost:8080/javaexamples2/servlet/hello?username=David
Search WWH ::




Custom Search