Java Web Programming with Eclipse contents
Last modified January 14, 2011 04:55 am

back next

Java Servlets

Objectives

References

Video

Overview

This section guides you through the creation of a Java servlet. The instructions in this section show you how to write the servlet in Eclipse and deploy it to the Tomcat web server. Actually, Tomcat is also classified as a web container, or servlet container, because servlets are placed inside a running instance of Tomcat.

The servlet that we create in this section simply generates a Web page that says Hello, World! This simple exercise will help you understand the basic structure of servlets, how to develop them in Eclipse, and how to deploy them in Tomcat.

If you have trouble using Eclipse commands in this chapter, you may want to go through the following two tutorials that are built into Eclipse and accessible through the Eclipse help menu.

Project Creation

We will develop the servlet inside an Eclipse project called website. The following steps show how to create a new Eclipse project that can be used to develop servlets. In these steps, we set the name of the project to website. We also associate jar files to the project that contain class definitions that implement the servlet API, which we need in order to develop servlets. These jar files are a part of the tomcat package; they provide the interface needed for application code to be called by the servlet container.

  1. Make sure you are in the Java Perspective.
  2. Select File ... New ... Project.
  3. Select Java Project and click the Next button.
  4. Set the Project name to website.
  5. Under Project Layout, make sure that the box next to Create separate source and output folders is checked.
  6. Click the Next button.
  7. Select the Source tab.
  8. Set the Default output folder to website/web/WEB-INF/classes. The following screenshot shows the screen at this point.
    Source tab of java settings window
  9. Select the Libraries tab.
  10. Click the Add External JARs button.
  11. Navigate to ${TOMCAT_HOME}/lib.
  12. Select servlet-api.jar and click the Open button.
  13. Click the Add External JARs button.
  14. Select jsp-api.jar, and click the Open button. (Adding jsp-api.jar is optional at this point, but will be used later when developing custom JSP tags.) The following screenshot shows the screen at this point.
    Libraries tab of Java Settings window
  15. Click the Finish button to create the website project.

Attaching Source Code to Jar Files

When we use Eclipse to generate code for us, it will obtain information from a class definition in a jar file. When it creates function signatures (function names, their return values and parameters), it uses the identifiers arg1, arg2 and arg3 for names of parameters in positions 1, 2 and 3 of the function parameter list. However, these names are not very descriptive of their function. To make the parameter names more meaningful, we attach the source code for the jar file so that Eclipse will use the parameter name as it appears in the source code. The other benefit from attaching source code is that comments in the source code become visible when you hover the mouse class names and method names. Execute the following instructions to attach the source code for the jar file that contains the servlet classes.

  1. Go to the Apache Tomcat website and download the source distribution for the version of Tomcat that you installed, but do not expand the zip file.
  2. Locate the servlet-api.jar folder in the Package Explorer view of Eclipse.
  3. Right click servlet-api.jar and select Properties from the pop-up menu.
  4. Select Java Source Attachment and then the Source tab.
  5. Select External File and navigate to and select the Tomcat source code zip file that you downloaded in the first step.
  6. The following screen shot shows the result.
  7. Click OK to complete the operation.
Java Source Attachment window

Deployment Descriptor

Inside Eclipse we store files used for the development of the web application within a project folder. The files within the project are used for building the web application and are not necessarily used as a deployable unit of work. We will keep the folders and files that comprise a deployable instance of the web application in a folder called web, which is stored within the project.

Every Java Web application has a deployment descriptor that is located at WEB-INF/web.xml, relative to the root of the deployable folder. Because we store all deployable objects under a folder called web, this deployment descriptor will be located at web/WEB-INF/web.xml.

The web.xml file configures several aspects of the Web application, the most important information being the servlets and the url-patterns that lead to their invocation.

We will initially create a single servlet and have it invoked when the URL requested by the browser matches the url-pattern /home. To configure this, do the following.

  1. Expand the web folder.
  2. Right-click on the WEB-INF folder and select New ... File.
  3. Specify a name of web.xml and click the OK button.
  4. In the text editor window that appears for web.xml, insert the contents of the following code listing, and save the file.

If you can not edit the web.xml file in the window that Eclipse provides, it is because Eclipse is using the XML editor to provide access to the file. Close this window and right click on web.xml in the Project Explorer view and select Open With ... Text Editor.

Deployment Descriptor web.xml

<?xml version="1.0"?>
<web-app
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
     version="2.4">
   <servlet>
      <servlet-name>home</servlet-name>
      <servlet-class>website.web.HomeServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>home</servlet-name>
      <url-pattern>/home</url-pattern>
   </servlet-mapping>
</web-app>

Note: make sure there is no leading space in the web.xml file. In other words, the file should start with <?xml version="1.0"?> without any space before the left angle bracket.

The url-pattern /home is relative to the context path that identifies the website Web application. Although we haven't specified this yet, the context path will be /website. This means, for a browser to invoke the home servlet, it must request the following URL.

http://localhost:8080/website/home

The deployment descriptor can be used to tell tomcat many things. However, the most basic information provided in a deployment descriptor are the servlets and their associated url patterns. For each servlet in your web application, there should be a servlet element, such as the following.

   <servlet>
      <servlet-name>home</servlet-name>
      <servlet-class>website.web.HomeServlet</servlet-class>
   </servlet>

The above servlet element tells the web container to create an instance of website.web.HomeServlet and call that instance by the name home. Although it is possible to create additional instances of HomeServlet, normally a single instance is made.

In addition to creating servlet instances, the web container should associate url patterns with these instances, so that when the web container receives an HTTP request from a web browser, it can determine which servlet to use to process the request. The following servlet-mapping element in our deployment descriptor tells tomcat that all incoming requests for home should be processed by the servlet instance with name home.

   <servlet-mapping>
      <servlet-name>home</servlet-name>
      <url-pattern>/home</url-pattern>
   </servlet-mapping>

Multiple servlet-mapping elements can be used to associate any number of url patterns with a single servlet instance.

Create Home Servlet

The above deployment descriptor defines a servlet with name home to be an instance of the class website.web.HomeServlet. We will implement this servlet to return the string Hello, World!. To do this, do the following.

  1. Make sure you are in the Java perspective.
  2. Expand the website project.
  3. Right click on src, and select New - Class.
  4. Set the Package to website.web.
  5. Set the Name to HomeServlet.
  6. Make the parent class javax.servlet.http.HttpServlet. You can do this in two ways. The first way is to simply replace java.lang.Object with javax.servlet.http.HttpServlet. The second way is to replace java.lang.Object with HttpServlet, then press Ctrl+space bar to get a list of replacement candidates. The following screen shot shows the result.
    Create a HomeServlet class
  7. Click the Finish button.

Notice that there is a warning icon in the HomeServlet file next to the line starting with public class HomeServlet. If you hover over the warning icon with the mouse pointer, Eclipse will display a short description of the warning, which is that you have not declared a field called serialVersionUID. This warning is generated for every class the implements the Serializable interface, but that does not contain a serialVersionUID field. However, for our purposes, creating field serialVersionUID is not necessary. To turn off this warning, do the following.

  1. Select Window ... Preferences.
  2. Select Java ... Compiler ... Errors/Warnings.
  3. Select Potential programming problems.
  4. Use the dropdown box to Ignore Serializable class without serialVersionUID. The following screen shot shows the result of carrying out steps 1 through 4.
  5. Preferences Setting window
  6. Click the OK button, and click the Yes button to do a full rebuild.

Now, we override the doGet() method we inherit from the parent class. In the HomeServlet.java file, do the following.

  1. Select Source ... Override/Implement methods.
  2. Select the doGet() method by checking the appropriate checkbox. The following screen shot shows the result of carrying out steps 1 through 2.
Override/Implement Methods window
  1. Click the OK button.
  2. Replace the body of the doGet method with the following code.
PrintWriter writer = resp.getWriter();
writer.println("<h1>Hello, World!</h1>");
  1. The following screen shot shows the result of carrying out the previous step.
HomeServlet.java file

When you enter this code, observe the red error icon on the left-hand side of the window. You can read the error message by hovering over the icon with the mouse as shown in the following screen shot.

Error message

The error message in this case is that certain classes "cannot be resolved to a type." You can either fully qualify the class names with their package names, as in java.io.PrintWriter, or you can identify the package location of the classes with an import statement. The standard practice is to use import statements.

Adding import statements are easy with Eclipse. To add the imports to HomeServlet, do the following.

Select Source ... Organize Imports.

Notice the asterisk (*) before the name HomeServlet.java in the window's tab. This indicates that changes to the file have not yet been saved. Save the file, and observe the disappearance of the asterisk. The following listing shows the HomeServlet.java file.

HomeServlet.java

package website.web;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class HomeServlet extends HttpServlet {
 
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException {
      PrintWriter writer = resp.getWriter();
      writer.println("<h1>Hello, World!</h1>");
   }
}

Web Application Deployment

At this point our Web application can be deployed to the Tomcat server. There are several ways to deploy web applications in tomcat, which are detailed in the tomcat documentation. This book recommends that you deploy applications using the manager application that is installed with tomcat. To do this, do the following. (Make sure that you replace ${WORKSPACE} with the actual path to your Eclipse workspace.)

In Eclipse create a new file in the top level of your website project called website.xml with the following contents. (Convert the back slashes to forward slashes if you are working under Linux or MacOS. In all cases, the slash before website in the path attribute needs to be a forward slash.)

<Context path="/website" docBase="${WORKSPACE}\website\web" />

Go to the manager application and locate the section called Deploy. Set the context path to /website. (Use a forward slash regardless of whether you are working in Windows, Linux or Mac.) Set the XML Configuration file URL to the following, where ${WORKSPACE} is the path to your Eclipse workspace. (Convert the back slashes to forward slashes if you are working under Linux or MacOS.)

${WORKSPACE}\website\website.xml

Click the Deploy button and then inspect the message section at the top of the manager application web page. If you see the following message, then you need to debug.

FAIL - Failed to deploy application at context path /website

If the application failed to start, you should check to make sure the path to website.xml is valid. You may also want to open the various tomcat log files and search for an error message that can give you a clue to solve the problem.

If the manager application reports successful deployment, the next step is to verify that the application is working correctly by going to http://localhost:8080/website/home in your browser.

If you make changes to Java code in a project, the changes will not be immediately deployed. To see the changes, you should reload the application through the manager application. If you make changes to the deployment descriptor (web.xml) in a project, reloading the application will not work. Instead, you need to stop and then start the application, which you can do in the manager application.

Exercises

(1) Servlet Mapping Element

Add an additional servlet mapping element to the deployment descriptor that associates the home servlet with the url pattern index.html. Test that the home servlet can be reached in the following 4 different ways.

(2) Methods doGet and doPost

Become familiar with the doGet and doPost methods by creating a servlet called TestServlet that accepts a string provided by the user and displays it back to the user. To do this, you need to create an HTML form with an input field and a submit button. This file should be located in the web folder in order to be visible to the browser. In the servlet, you need to call the getParameter method of the HTTPServletRequest object passed into doPost in order to get the value that the browser is sending. Make sure that the method attribute of the HTML form is post. The key that you pass into getParameter should match the name of the input field you used in the HTML form.

You can either add this servlet to the website application or to a newly created application. Creating a new application requires more work but will help you better understand the process of creating web applications.

(3) Adding Two Numbers

Similar to problem 2, create a new servlet called AddServlet and associated HTML file called add.html. The add.html file contains a form that accepts 2 numbers in input boxes and submits them to the AddServlet. The add servlet adds the numbers and presents the result to the user.

To solve this problem, you need to convert a string that you get from the form submission into a double (or an int if you prefer). For this purpose, you will need to use the parseDouble method of the Double class.

double doubleValue = Double.parseDouble(stringValue);
For integers, you whould use something like the following.
int intValue = Integer.parseInt(stringValue);

back next

Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved.