SE452: Lecture 2 (The Java Servlet API/Intro to Tomcat)

Contents [0/24]

Overview of Today's Class [1/24]
Java Servlets [2/24]
Servlet Container [3/24]
Jakarta Tomcat [4/24]
Tomcat Installation and Setup [5/24]
Running/Configuration [6/24]
A simple Servlet [7/24]
URIs [8/24]
The servlet API [9/24]
The Servlet Framework [10/24]
The servlet lifecycle [11/24]
The Servlet Lifecycle for HttpServlet [12/24]
Web Applications [13/24]
Configuring Tomcat [14/24]
Manager/Admin [15/24]
A little XML [16/24]
XML continued [17/24]
Specifying a context [18/24]
Directory structure of a webapp [19/24]
The deployment descriptor [20/24]
Deploying a web app - expanded war file [21/24]
Configuring Web Apps (more web.xml) [22/24]
Using init parameters [23/24]
Homework [24/24]

Overview of Today's Class [1/24]

Servlet Overview

Tomcat Introduction

Some simple Servlets

Homework Assignment

Java Servlets [2/24]

Servlets provide extensions of functionalities of servers, most commonly HTTP servers. They are precompiled Java programs that are executed on the server side, inside a servlet container.

Servlets provide the following benefits:

Servlet Container [3/24]

Also known as a servlet engine

An extension to a web server

The servlet engine is a key component to an application server

Uses HTTP to communicate with the client (requires HTTP/1.0 and HTTP/1.1)

Takes the request data from the web server, processes it, then responds back through the web server

The servlet container may place security restrictions on the servlets running in the container (like whether or not a Thread object can be created or manipulated directly) in order to insulate other components in the container from being negatively impacted.

Java Servlets are currently part of the J2EE API

Jakarta Tomcat [4/24]

An open-source servlet container

The Reference Implementation for Java Servlets and JavaServer Pages

Tomcat can be used:

Tomcat Installation and Setup [5/24]

Installing Tomcat

  1. Download the zip file from http://jakarta.apache.org/ (or get it from the cd supplied in class)
  2. Get the current version (5.0.9 beta at time of writing)
  3. Unzip it to a directory (ex. D:\, or /users/mwright)
    The top level directory for Tomcat is jakarta-tomcat-4.0.1 This directory is known as Tomcat root or Tomcat home It will be referred to as "tomcat_home"

Subdirectories in "tomcat_home":

Now, it's probably worth discussing how Tomcat handles classloading. You will need to understand this a bit more as you develop more sophisticated applications. Tomcat loads creates a set of class loaders when it is started, with parent-child relationships.

        Bootstrap
          |
       System
          |
       Common
      /      \
 Catalina   Shared
             /   \
        Webapp1  Webapp2 ... 
        

Read the documentation at http://jakarta.apache.org/tomcat/tomcat-5.0-doc/index.html

Set some environment variables

Only JAVA_HOME is really needed, but the second ensures you point to the right instance of Tomcat if you have more than one installed.

On Windows:

	set JAVA_HOME=c:\j2sdk1.4.2
	set CATALINA_HOME=c:\jakarta-tomcat-5.0.9
        

On Linux (bash)

	export JAVA_HOME=/usr/local/j2sdk1.4.2
	export CATALINA_HOME=/usr/local/jakarta-tomcat-5.0.9
        

Running/Configuration [6/24]

Starting/Stopping

To start Tomcat execute startup.sh (Linux) or startup.bat (Windows)

To stop Tomcat execute shutdown.sh (Linux) or shutdown.bat (Windows)

See "tomcat_home"/Running.txt for most common problems if Tomcat will not start Especially if you are using Windows 9x or ME

You can also use the Windows installer for Tomcat, and it will give you the option to run Tomcat as a service. This is preferred for production installations, but may not be as easy to use for development. There are also many other scripts that can be used to start/stop tomcat. The nice thing about using the simple one above is that logs are sent to the console, so you don't have to open them in a text editor to see what is wrong in most cases.

Configuration

Default port: 8080

Once the server is running, to access it, point a web browser to http://localhost:8080/

The file you see is located at "tomcat_home"\webapps\ROOT\index.html Each directory under webapps is a web application (more on these later)

A simple Servlet [7/24]

So.. what does Servlet code look like?


        import javax.servlet.*;
        import javax.servlet.http.*;

        public class HelloServlet extends HttpServlet {

        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
                java.io.PrintWriter out = response.getWriter();
                out.println("Hello World");
                out.close();
            } 
        }
        

To compile the servlet:

  1. Compile the servlet:
                javac -classpath "tomcat_home"\common\lib\servlet.jar Hello.java
                

But that's not too exciting, and there's much more to discuss so we'll get to deploying and running it in a minute...

URIs [8/24]

Uniform Resource Identifier

defined in RFC 2396

Uniform Resource Locator (URL) is a subset of URI

Example: http://localhost:8080/servlet/Hello

Some common examples (from the spec)

The servlet API [9/24]

Package javax.servlet contains interfaces and abstract classes for protocol independent generic servlets.

Package javax.servlet.http contains interfaces and abstract classes for servlets using the HTTP protocol.

servlet implementation extend the interfaces and classes in javax.servlet

In theory, servlets can be written for other protocols (like mail, IM, etc...)

A servlet engine provides implementation of these two packages... the Tomcat one is in "tomcat_home"/common/lib/servlet.jar

The JavaDocs are available at http://localhost:8080/tomcat-docs/servletapi/index.html once you have Tomcat running...

The Servlet Framework [10/24]

javax.servlet.Servlet

abstract class javax.servlet.GenericServlet

abstract class javax.servlet.http.HttpServlet

interface javax.servlet.SingleThreadModel

interface javax.servlet.ServletRequest

interface javax.servlet.ServletResponse

interface javax.servlet.http.HttpServletRequest extends javax.servlet.ServletRequest

interface javax.servlet.http.HttpServletResponse extends javax.servlet.ServletResponse

The servlet lifecycle [11/24]

The life cycle of a servlet is controlled by the servlet engine. Servlets are instantiated (loaded) and destroyed (unloaded) by the servlet engine. For a generic servlet, the servlet engine calls the following methods:

void init()
abstract void service(ServletRequest request,
         ServletResponse response)
void destroy()

The Servlet Lifecycle for HttpServlet [12/24]

The service() method is overridden to dispatch requests to doGet(), doPost(), etc.

allows services to be added incrementally.

provides default behavior for HEAD, TRACE requests

Do not override the service() method. Why? ... think back to SE450 design patterns...

Override doGet(), doPost() etc. to handle requests GET, POST , etc.


        void doGet( HttpServletRequest request,HttpServletResponse response)
        void doPost( HttpServletRequest request, HttpServletResponse response)
        void doPut( HttpServletRequest request, HttpServletResponse response)
        void doDelete( HttpServletRequest request, HttpServletResponse response)
        void doOptions( HttpServletRequest request, HttpServletResponse response)
        void doTrace( HttpServletRequest request, HttpServletResponse response)
        

Web Applications [13/24]

A Web Application is a collection of servlets, html files, JSPs, classes, and resources used by a servlet container

There is a one-to-one relationship between webapps and a ServletContext object

Web applications are a way to package an application for the servlet container and separate multiple applications from one another inside the same container

To create a web application context, the servlet container must be configured.

In Tomcat, the web application is placed in a directory under "tomcat_root"/webapps

The context must be configured for the application server to use it. Requests will be dispatched to that webapp based on the URI used to access it.

Configuring Tomcat [14/24]

Tomcat is configured in the server.xml file loated in "tomcat_root"/conf/

Add a context entry for your webapp


      
        <Server port="8005" shutdown="SHUTDOWN" debug="0">
         <Service name="Tomcat-Standalone">
         <!-- lots of stuff ... -->
         <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true">
                <!-- SE 452 Context -->
                <Context path="/se452" docBase="se452" debug="0" reloadable="true" />
                <Context path="/myapp" docBase="c:\MyApp" debug="0" reloadable="true" />
                <!-- more stuff -->
                  </Host>
                </Service>
        </Server>
        
        

To configure the listen port, edit the port attribute.


        
         <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
            <Connector 	
               className="org.apache.catalina.connector.http.HttpConnector"
               port="8080" 
               minProcessors="5" 
               maxProcessors="75"
               enableLookups="true" 
               redirectPort="8443"
               acceptCount="10" debug="0"
               connectionTimeout="60000"/>
               
        

Manager/Admin [15/24]

Tomcat now has some nice administration tools that you can use to help you configure and manage it. The configuration of Tomcat is stored in a few files, all stored in "tomcat_root"/conf. The first file is server.xml. This is used for all Tomcat specific configurations. To edit the configuration using the web based tools, point your browser to http://localhost:8080/admin/frameset.jsp.

To deploy new webapps, start/stop/reload/undeploy them, and monitor their status, point your browser to http://localhost:8080/manager/html.

Both of these are linked off the main tomcat page at http://localhost:8080

To setup a user for these accounts, edit the file "tomcat_home"/conf/tomcat-users.xml with a manager and admin role. Here's an example:


        
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat" fullName="Tomcat Admin User" roles="admin,manager,tomcat"/>
</tomcat-users>
        
        

The other file of interest is web.xml. This is the default deployment descriptor settings for all webapps. We'll talk about deployment descriptors more later

A little XML [16/24]

eXtensible Markup Language

Developed by World Wide Web Consortium (W3C) http://www.w3c.org

An XML document is a text document with

XML continued [17/24]

Empty-tags and start-tags may have attributes


        
    <Context path=""
    docBase="webapps/ROOT"
    debug="0"
    reloadable="true" />
        
        

Each attribute is a name-value pair.

Attribute values must be enclosed between quotation marks.

An XML document is well-formed if:

  1. It has a single root element.
  2. All start-tags are matched by end-tags, and vice versa
  3. All start-tags and end-tags are properly nested.

The following segments are not well-formed: <a> <b> </b> </c> <a> <b> </a> </b>

A well-formed XML document forms a tree of elements.

An XML document may impose further restrictions on its structure using a DTD (Document Type Definition) or XML schema.

An XML document is valid, if it is well-formed and satisfies the restrcitions imposed by a DTD or schema.

Specifying a context [18/24]

The contexts of web applications for Tomcat are specified by the <Context> element in server.xml

The <Context> element may have the following attributes:

Directory structure of a webapp [19/24]

The directory structure is J2EE standard.

Assume the document root directory of the web app to be deployed is called "WebApp"

The contents of the document root directory:

WEB-INF content

You can create these directories directly in the directory "tomcat_root"/webapps/, or put them in another directory on your server and map the context to that directory in the Context in server.xml

The deployment descriptor [20/24]

The deployment descriptor is written in xml. It is defined in either a DTD or an XML Schema depending on the version of the specification. For 2.4, it is an XML Schema, which allows a more flexible and controlled implementation. For 2.3 and 2.2, it uses a DTD, which a bit more rigid in how you write the XML document.

Here's a simple example using the 2.4 spec


        
        <?xml version="1.0" encoding="ISO-8859-1"?>
        <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">

            <display-name>A Simple Application</display-name>
            <servlet>
                <servlet-name>catalog</servlet-name>
                <servlet-class>com.mycorp.CatalogServlet</servlet-class>
                <init-param>
                    <param-name>catalog</param-name>
                    <param-value>Spring</param-value>
                </init-param>
            </servlet>
            <servlet-mapping>
                <servlet-name>catalog</servlet-name>
                <url-pattern>/catalog/*</url-pattern>
            </servlet-mapping>
            <session-config>
                <session-timeout>30</session-timeout>
            </session-config>
            <welcome-file-list>
                <welcome-file>index.jsp</welcome-file>
                <welcome-file>index.html</welcome-file>
                <welcome-file>index.htm</welcome-file>
            </welcome-file-list>
        </web-app>
        
        

And an even simpler (minimal) example using the 2.3 spec...


        
        <?xml version="1.0" encoding="ISO-8859-1"?>
        <!DOCTYPE web-app PUBLIC 
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
        "http://java.sun.com/dtd/web-app_2_3.dtd">
        <web-app>
        </web-app>
        
        

The details of web.xml can be found in chapter 13 of the specification

Deploying a web app - expanded war file [21/24]

Copy the configured web.xml to WebApp/WEB-INF

for example, with Context se452, it goes to "tomcat_home"/webapps/se452/WEB-INF/

with Context myapp, it goes to C:\MyApps\WEB-INF\

Then, copy servlet class files ( HelloServlet.class ) to WebApp/WEB-INF/classes

for context se452 it goes in"tomcat_home"/webapps/se452/WEB-INF/classes/

for context myapps it goes in C:\MyApp\WEB-INF\classes\

This is known as expanded (or exploded) war format... we'll discuss war files in a minute

Configuring Web Apps (more web.xml) [22/24]

The servlet and a servlet-mapping element are important sections in the deployment descriptor (web.xml).

servlet element: the servlet definition

servlet-mapping element: servlet mapping

An example webapp for a simple servlet:


        
<web-app>
  <servlet>
   <servlet-name>hello</servlet-name>
   <servlet-class>HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>hello</servlet-name>
   <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

    
        

A servlet can be invoked with the URL specified in the servlet mapping:

http://localhost:8080 protocol, host, and port

/se452,/myapps the context prefix

/hello the servlet url

Sometimes we want to initialize a servlet when it is first loaded by the servlet engine.

Initialization parameters are usually handled in the init() method.


        void init()
        

Override this one to initialize a servlet


        void init( ServletConfig config)
        

Do not override this one, if you do override, you must call super.init(ServletConfig config) You can access the ServletConfig's methods through the servlet itself, since the interface is implemented by GenericServlet

Using init parameters [23/24]

Enhancements to the HelloServlet servlet.

Takes two initialization parameters

It is placed in a package named se452.week2


        
package se452.week2; 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class HelloServlet3 extends HttpServlet { 

  protected String bgcolor;
  protected String fgcolor;

  public void init() { 
    bgcolor = getInitParameter("bgcolor");
    fgcolor = getInitParameter("fgcolor");
  }
 public void doGet(HttpServletRequest request, 
		    HttpServletResponse response) 
    throws ServletException, IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    out.println("<html>");
    out.println("<head><title> Hello </title></head>");
    if (bgcolor != null) { 
      out.println("<body bgcolor=\"" + 
			bgcolor + "\">");
    } else { 
      out.println("<body>");
    }

     if (fgcolor != null) { 
      out.println("<h1><font color=\"" + fgcolor + "\"> Hello! </font></h1>"); 
    } else { 
      out.println("<h1> Hello! </h1>"); 
    }
    out.println("<br>"); 
    out.println("The request URI is <i>" + 	request.getRequestURI() + "</i>"); 
    out.println("</body>");
    out.println("</html>");
  }
}

        
        

Deploy HelloServlet again

  1. Add the se452.week2 package directory to WebApp/WEB-INF/classes
  2. Copy the new HelloServlet3.class file to the directory
  3. Edit the web.xml file to refer to the new package name.

New, in web.xml:


        
 <servlet>
   <servlet-name>hello</servlet-name>
   <servlet-class>se452.week2.HelloServlet3</servlet-class>
   <init-param>
     <param-name>bgcolor</param-name>
     <param-value>white</param-value>
   </init-param>
   <init-param>
     <param-name>fgcolor</param-name>
     <param-value>green</param-value>
   </init-param>
  </servlet>
  <servlet-mapping>
   <servlet-name>hello-green</servlet-name>
   <url-pattern>/green/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
   <servlet-name>hello-red</servlet-name>
   <url-pattern>/red</url-pattern>
  </servlet-mapping>

    
    

Homework [24/24]

Complete the following tasks:

  1. Create a new Context in your Tomcat server.xml file for your coursework this quarter. Name it after your DePaul id. Mine, for example, would be mwright1. At a minimum, set the path, docBase, debug, and reloadable attributes. Feel free to play around with these as well.
  2. Create your webapp directory according to the instructions in the notes, or reference the Tomcat documentation for details. Add the WEB-INF directory, and the classes directory in WEB-INF, etc.
  3. Create a valid web.xml file.
  4. Write a servlet that reads initialization parameters and writes valid html. It should read in at least two parameters and do something interesting with them. For example, you could read in a parameter (remember it's a string) and use it to loop a certain number of times based on the parameter. Or, you could parse a date entered as a parameter, and change the look of the page based on how far that date is from today. The servlet should also be in a package. (se452.depaulid, where depaulid is your id used to login to campusconnection, mwright1 in my case)
  5. Make sure your servlet handles both GET and POST requests.
  6. Edit web.xml so your servlet is called by a url that doesn't contain the word "servlet" and is not the same name as your servlet class name.
  7. Create a simple index.html file and place it at the root of our webapp. Provide a link in this file to run your test servlet, along with a little description of what the user will see when it is executed.
  8. Place the class file and source file in the correct location in WEB-INF and test your servlet. When you are done, zip the entire webapp (in my case, the mwright1 directory) and post it in the COL submission area. Name the zip file the same as your userid (ex. mwright1.zip).
  9. Make sure to comment your source appropriately, including @author and other appropriate javadoc tags.

Grading Breakdown:

ItemPoints
Context File10
web.xml settings10
index.html10
Webapp structure10
Coding style, javadoc10
Proper Submission10
Servlet functionality40
Total:100

Questions or problems? Try posting a question to the Discussion forum on the DL web site.


Revised: 2003/9/28