Skip Headers

Oracle9iAS Containers for J2EE Servlet Developerís Guide
Release 2 (9.0.2)

Part Number A95878-01
Go To Documentation Library
Go To Product List
Solution Area
Go To Table Of Contents
Go To Index

Go to previous page Go to next page

Servlet Overview

Oracle9iAS Containers for J2EE (OC4J) enables you to develop standard J2EE-compliant applications. Applications are packaged in standard EAR (Enterprise ARchive) deployment files, which include standard WAR (Web ARchive) files to deploy the Web modules, and JAR files for any EJB and application client modules in the application.

The most important thing to understand about servlet development under OC4J is how the Web application is built and deployed. If OC4J is a new development environment for you, see Chapter 2, "Servlet Development", and Chapter 3, "Deployment and Configuration", to learn how applications are deployed under OC4J.

This chapter introduces the Java servlet and provides an example of a basic servlet. It also briefly discusses how you can use servlets in a J2EE application to address some server-side programming issues.

This chapter covers the following topics:

Information Sources

This section points you to other information sources about servlets and OC4J.

Servlet Information

You should be generally familiar with the Sun Microsystems Java(TM) Servlet Specification, Version 2.3. This is especially true if you are developing a distributable Web application, in which sessions can be replicated to servers running under more than one Java Virtual Machine (JVM).

You can obtain the Servlet 2.3 specification at the following location:

This guide is not a complete reference for servlet development. For example, it does not cover the standard servlet APIs. For servlet API documentation, refer to the Javadoc available from Sun Microsystems at the following location:

In addition, several trade press books are available to teach you how to develop servlets and deploy them in J2EE-compatible applications. In particular, the books from O'Reilly & Associates ( and Wrox ( are useful.

Additional OC4J Documents

You should use this guide together with the following additional Oracle9iAS publications:

Introduction to Servlets

A servlet is a Java program that runs in a J2EE application server, such as OC4J. A servlet is the server-side counterpart of a Java applet. Servlets are one of the four application component types of a J2EE application, others being applets and application client programs on the client side, and EJBs on the server side. Servlets are managed by the OC4J servlet container; EJBs are managed by the OC4J EJB container. These containers, together with the JavaServer Pages container, form the core of OC4J.

JavaServer Pages (JSP) is another server-side component type. JSP pages also involve the servlet container, because the JSP container itself is a servlet and is therefore executed by the servlet container. The JSP container translates JSP pages into page implementation classes, which are executed by the JSP container but function similarly to servlets. See the JSP chapter in the Oracle9iAS Containers for J2EE User's Guide and the Oracle9iAS Containers for J2EE Support for JavaServer Pages Reference for more information about JavaServer Pages.

Most servlets generate HTML text, which is then sent back to the client for display by the Web browser, or is sent on to other components in the application. Servlets can also generate XML, to encapsulate data, and send this to the client or to other components.

The remainder of this section covers the following topics:

Advantages of Servlets

Servlet programming offers advantages over earlier models of server-side Web application development, including the following:

Because servlets are written in the Java programming language, they are supported on any platform that has a Java virtual machine and a Web server that supports servlets. Servlets can be used on different platforms without recompiling. You can package servlets together with associated files such as graphics, sounds, and other data to make a complete Web application. This simplifies application development and deployment.

In addition, you can port a servlet-based application from another Web server to OC4J with little effort. If your application was developed for a J2EE-compliant Web server, then the porting effort is minimal.

Servlets outperform earlier technologies for generating dynamic HTML, such as server-side "includes" or CGI scripts. Once a servlet is loaded into memory, it can run on a single lightweight thread; CGI scripts must be loaded in a different process for every request.

Servlets and the Servlet Container

As with an applet, but unlike a Java client program, a servlet has no static main() method. Therefore, a servlet must execute under the control of a servlet container, because it is the container that calls servlet methods and provides services that the servlet needs when executing.

The servlet overrides the appropriate methods from the servlet base class--javax.servlet.HttpServlet class for HTTP servlets, or possibly javax.servlet.GenericServlet for protocol-independent servlets--in order to process the request and return the response. For example, most servlets override the HttpServlet doGet() method or doPost() method or both to process HTTP GET and POST requests.

The servlet container provides the servlet easy access to properties of the HTTP request, such as its headers and parameters. Also, a servlet can use other Java APIs, such as JDBC to access a database, RMI to call remote objects, JMS for asynchronous messaging, or many other Java and J2EE services.

Figure 1-1 shows how a servlet relates to the servlet container and to a client, such as a Web browser. When the Web listener is the Oracle HTTP Server (powered by Apache), then the connection to the OC4J servlet container goes through the mod_oc4j module. See the Oracle HTTP Server Administration Guide for details.

Figure 1-1 Servlets and the Servlet Container

Text description of fc01.gif follows.

Text description of the illustration fc01.gif

Request Objects, Response Objects, and Filters

The HttpServlet methods, such as doGet() and doPost(), take two parameters: a javax.servlet.http.HttpServletRequest object and a javax.servlet.http.HttpServletResponse object (instances of classes that implement the HttpServletRequest and HttpServletResponse interfaces). The servlet container passes these objects to the servlet, or to the next filter if there is a filter chain.

The Servlet 2.3 specification enables servlet filters, which are Java programs that execute on the server and can be interposed between the servlet (or group of servlets) and the servlet container for special request or response processing. See Chapter 4, "Servlet Filters", for more information.

The request and response objects support methods that let you write efficient servlet code. "A First Servlet Example" shows that you can get a stream writer object from the response and use it to write statements to the response stream.

Session Tracking

Servlets provide convenient ways to keep the client and a server session in synchronization, enabling stateful servlets to maintain session state on the server over the whole duration of a client browsing session.

These techniques involve cookies or URL rewriting, and the javax.servlet.http.HttpSession object. See "Session Tracking" for more information.

A First Servlet Example

Looking at a basic example is the best way to see how servlets are coded and what they can do. This section shows the code for a simple servlet, but with a twist for globalization. The code is commented to explain the basics of servlet development.

Hello World Code

A "Hello World" example is a good way to demonstrate the basic framework that you use to write a servlet. This servlet just prints the date and a greeting back to the client, but in Swedish.

Here is the code:

import java.text.*;
import java.util.*;
// The first three package imports support I/O, and the locale info and date
// formatting. The next two imports include the packages that support
// servlet development.
import javax.servlet.*;
import javax.servlet.http.*;
// HTTP servlets extend the javax.servlet.http.HttpServlet class.
public class HelloWorldServlet extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    // doGet() overrides the HttpServlet method. Each method of this class
    // has request and/or response parameters.

    // Set the content type of the response.

    // Get a print writer stream to write output to the response. You
    // could also get s ServletOutputStream object to do this.
    PrintWriter out = res.getWriter();

    // This statement tells the client the language of the content--Swedish.
    // However, many Web browsers will ignore this info.
    res.setHeader("Content-Language", "sv");

    // Set the locale information, so the date will be formatted in a Swedish-
    // friendly way, and the right words are used for months and so on.
    Locale locale = new Locale("sv", "");

    // Get the date format.
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,

    // Also set the local time zone.

    // Now use the printer object to send some HTML header info to the
    // output stream. 
    out.println("<HTML><HEAD><TITLE>Hej V\u00e4rlden!</TITLE></HEAD>");

    // Send the date to the output.
    out.println(dateFormat.format(new Date()));

   // And then, greet the client--
    out.println("<p>In Swedish (p\u00E5 Svenska):");
    out.println("<H2>Hej V\u00E4rlden!</H2>");

    // Don't forget to close the HTML tags.

Compiling and Deploying the Servlet

To try out this servlet in your OC4J server, enter the code using your favorite text editor, and save it as in the j2ee/home/default-web-apps/WEB-INF/classes directory. This is the location where the container finds servlet classes for the OC4J default application. Next, compile the servlet, using a Java 1.3.x-compliant compiler.

For convenience during development and testing, use the OC4J auto-compile feature for servlet code. Set the attribute development="true" in the <orion-web-app> element of the global-web-application.xml configuration file. You may also have to set the source-directory attribute appropriately. With auto-compile enabled, after you change the servlet source and save it in a specified directory, the OC4J server automatically compiles and redeploys the servlet the next time it is invoked.

You can find global-web-application.xml in the config directory under the j2ee/home directory. See "Element Descriptions for global-web-application.xml and orion-web.xml" for more information about development and source-directory.

Running the Servlet

Assuming the OC4J server is up and running, by default you can invoke the servlet and see its output from a Web browser as follows, where <host> is the name of the host that the OC4J server is running on, and <port> is the Web listener port:


This example assumes that /j2ee is the root context of the Web application. By default, this is the case for the OC4J default Web application. Typically, use port 7777 for access through the Oracle HTTP Server with Oracle9iAS Web Cache enabled.

For related information, see "Invoking a Servlet" and "The global-web-application.xml and orion-web.xml Files".

Go to previous page Go to next page
Copyright © 2002 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Go To Product List
Solution Area
Go To Table Of Contents
Go To Index