Previous     Contents     Index     DocHome     Next     
iPlanet Application Server Programmer's Guide (Java)



Chapter 2   Controlling Applications with Servlets


This chapter describes how to create effective servlets to control application interactions running on an iPlanet Application Server, including standard servlets. In addition, this chapter describes the iPlanet Application Server features to use to augment the standards.

This chapter contains the following sections:



About Servlets

Servlets, like applets, are reusable Java applications. However, servlets run on an application server or web server rather than in a web browser.

Servlets supported by the iPlanet Application Server are based on the Java Servlet Specification v2.2. All relevant specifications are accessible from installdir/ias/docs/index.htm, where installdir is the directory where the iPlanet Application Server is installed.

Servlets are used for an application's presentation logic. A servlet acts as an application's central dispatcher by processing form input, invoking business logic components encapsulated in EJBs, and formatting web page output using JSPs. Servlets control the application flow from one user interaction to the next by generating content in response to a user request.

The fundamental characteristics are:

  • Servlets are created and managed at runtime by the iPlanet Application Server servlet engine.

  • Servlets operate on input data that is encapsulated in a request object.

  • Servlets respond to a query with data encapsulated in a response object.

  • Servlets call EJBs to perform business logic functions.

  • Servlets call JSPs to perform page layout functions.

  • Servlets are extensible; use the APIs provided with the iPlanet Application Server to add functionality.

  • Servlets provide user session information persistence between interactions.

  • Servlets can be part of an application or they can reside discretely on the application server so they are available to multiple applications.

  • Servlets can be dynamically reloaded while the server is running.

  • Servlets are addressable with URLs; buttons on an application's pages often point to servlets.

  • Servlets can call other servlets.

Several iPlanet Application Server API features enable an application to take programmatic advantage of specific iPlanet features. For more information, see Accessing iPlanet Application Server Optional Features.


Servlet Data Flow

When a user clicks a Submit button, information entered in a display page is sent to a servlet. The servlet processes the incoming data and orchestrates a response by generating content, often through business logic components, which are EJBs. Once the content is generated, the servlet creates a response page, usually by forwarding the content to a JSP. The response is sent back to the client, which sets up the next user interaction.

The following illustration shows the information flow to and from the servlet, as:

  1. Servlet processes the client request

  2. Servlet generates content

  3. Servlet creates response and either:

    1. Sends it back directly to the client

      or

    2. Dispatches the task to a JSP



The servlet remains in memory, available to process another request.


Servlet Types

There are two main servlet types:

  • Generic servlets

    • Extends javax.servlet.GenericServlet.

    • Are protocol independent; contains no inherent HTTP support or any other transport protocol.

  • HTTP servlets

    • Extends javax.servlet.HttpServlet.

    • Has built-in HTTP protocol support and are more useful in an iPlanet Application Server environment.

For both servlet types, implement the constructor method init() and the destructor method destroy(); to initialize or deallocate resources, respectively.

All servlets must implement a service() method which is responsible for handling servlet requests. For generic servlets, simply override the service method to provide routines for handling requests. HTTP servlets provide a service method which automatically routes the request to another method in the servlet, based on which HTTP transfer method is used. So, for HTTP servlets override doPost() to process POST requests, doGet() to process GET requests, and so on.



About the Server Engine



Servlets exist in a Java server process on an iPlanet Application Server and are managed by the servlet engine. The servlet engine is an internal object that handles all servlet meta functions. These functions include instantiation, initialization, destruction, access from other components, and configuration management.


Instantiating and Removing Servlets

After the servlet engine instantiates the servlet, the servlet engine runs its init() method to perform any necessary initializations. Override this method to perform an initialize a function for the servlet's life, such as initializing a counter.

When a servlet is removed from service, the server engine calls the destroy() method in the servlet so that the servlet can perform any final tasks and deallocate resources. Override this method to write log messages or clean up any lingering connections that won't be caught in garbage collection.


Request Handling

When a request is made, the iPlanet Application Server hands the incoming data to the servlet engine. The servlet engine processes the request's input data, such as form data, cookies, session information, and URL name-value pairs, into an HttpServletRequest request object type.

The servlet engine also captures client metadata by encapsulating it in an HttpServletResponse response object type. The engine then passes both as parameters to the servlet's service() method.

In an HTTP servlet, the default service() method routes requests to another method based on an HTTP transfer method, such as POST, GET, and so on. For example, HTTP POST requests are sent to the doPost() method, HTTP GET requests are sent to the doGet() method, and so on. This enables the servlet to process request data differently, depending on which transfer method is used. Since the routing takes place in the service method, you generally do not override service() in an HTTP servlet. Instead, override doGet(), doPost(), and so on, depending on the request type you expect.


Tip To enable automatic routing in an HTTP servlet, call request.getMethod(), which provides the HTTP transfer method. Since request data is already preprocessed into a name value list in the iPlanet Application Server, you could simply override the service() method in an HTTP servlet without losing functionality. However, this does make the servlet less portable, since it is now dependent on preprocessed request data.



To perform the tasks to answer a request, override the service() method for generic servlets, and the doGet() or doPost() methods for HTTP servlets. Very often, this means accessing EJBs to perform business transactions, collating the information in the request object or in a JDBC ResultSet object, and then passing the newly generated content to a JSP for formatting and delivery back to the user.


Allocating Servlet Engine Resources

By default, the servlet engine creates a thread for each new request. Which is less resource intensive than instantiating a new servlet copy in memory for each request. Avoid threading issues, since each thread operates in the same memory space where variables can overwrite each other.

If a servlet is specifically written as a single-thread, the servlet engine creates a pool of ten servlet instances to be used for incoming requests. If a request arrives when all instances are busy, it is queued until an instance becomes available. The number of pool instances is configurable in the Deployment Descriptor (DD), which is an iPlanet Application Server specific XML file. For more information about deployment descriptors, see Chapter 10 "Deployment Packaging."

For more information on threading issues, see "Handling Threading Issues".


Updating Servlets at Runtime

Servlets and other application components can be updated at runtime without restarting the server. For more information, see Appendix B, "Dynamic Reloading."


Configuring Servlets for Deployment

When you configure a servlet for deployment, you actually provide the metadata, which the application server uses to create the servlet object and use it in the application framework. For more information about servlet configuration, see Chapter 10 "Deployment Packaging."


Locating Servlet Files

Servlet files and other application files reside in a directory structure location known to the iPlanet Application Server as, AppPath. This variable defines the top of a logical directory tree for the application. The AppPath variable is similar to the document path in a web browser. By default, AppPath contains the value BasePath/APPS, where BasePath is the base iPlanet Application Server directory.

AppPath and BasePath are variables held in the iPlanet Application Server registry, which is a repository for server and application metadata. For more information, see The iPlanet Application Server Registry and the Deployment Tool Online Help.

In addition to AppPath and BasePath, the registry has a third variable called modulesDirName. This varible corresponds to a directory under AppPath that is the home for web modules that do not exist as a part of any J2EE application. They are registered as standalone modules.

Table 2-1 describes important files and locations for servlets:

Table 2-1    Important files and locations for servlets.

Location Vafiable

Description

BasePath  

Top of the iPlanet Application Server tree. All files in this directory are part of the iPlanet Application Server. Defined by the registry variable BasePath.  

AppPath  

Top of the application tree. Applications reside in subdirectories of this location. Defined by the registry variable AppPath.  

modulesDirName  

A special directory that contains all J2EE web and EJB modules that are registered as standalone entities. This directory exists under AppPath.  

AppPath/appName/*  

Top of the subtree for the application appName. The appName directory in turn contains subdirectories for different modules within the application. For more information, see .  


Deploying Servlets

You normally deploy servlets with the rest of an application using the iPlanet Application Server Deployment Tool. You can also deploy servlets manually for testing or to update servlets while the server is running. For more information, see the iPlanet Application Server Deployment Tool Online Help.



Designing Servlets



This section describes basic design decisions to make when planning the servlets that help make up an application.

Web applications generally follow a request-response paradigm so that a user normally interacts with a web application by following a directed sequence of completing and submitting forms. A servlet processes the data provided in each form, performs business logic functions, and sets up the next interaction.

How you design the application as a whole determines how to design each servlet by defining the required input and output parameters for each interaction.


Choosing a Servlet Type

Servlets that extend HttpServlet are much more useful in an HTTP environment, since that is what they were designed for. We recommend that all iPlanet Application Server servlets extend from HttpServlet rather than from GenericServlet in order to take advantage of the built-in HTTP support. For more information, see Servlet Types.


Create Standard or Non-Standard Servlets

One important decision to make with respect to the servlets in your application is whether to write them strictly according to the official specifications, which maximizes their portability, or to utilize the features provided in the iPlanet Application Server APIs. These APIs can greatly increase the usefulness of servlets in an iPlanet Application Server framework.

Also, create portable servlets that only take advantage of the iPlanet Application Server features if the servlet runs in an iPlanet Application Server environment.

For more information on iPlanet Application Server specific APIs, see Accessing iPlanet Application Server Optional Features.


Planning for Servlet Reuse

Servlets by definition are discrete, reusable applications that run on a server. A servlet does not necessarily have to be tied to one application. Create a servlet library to be used across multiple applications.

However, there are disadvantages to using servlets that are not part of a specific application. In particular, servlets in the "default" application are configured separately from those that are part of the application.



Creating Servlets



To create a servlet, perform the following tasks:

  • Design the servlet into your application, or, if accessed in a generic way, design it to access no application data.

  • Create a class that extends either GenericServlet or HttpServlet, overriding the appropriate methods so it handles requests.

  • Use the iPlanet Application Server Administration Tool (iASAT) to create a web application Deployment Descriptor (DD) for the servlet.



Servlet Files for iPlanet Application

The files that make up a servlet include:


The Servlet's Class File

This section describes how to write a servlet, and the decisions you make about your application and your servlet's place in it.


Creating the Class Declaration

To create a servlet, write a public Java class that includes basic I/O support as well as the package javax.servlet. The class must extend either GenericServlet or HttpServlet. Since iPlanet Application Server servlets exist in an HTTP environment, the latter class is recommended.

The following example header shows the HTTP servlet declaration called myServlet:

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

public class myServlet extends HttpServlet {
   servlet methods...
}


Overriding Methods

Next, override one or more methods to provide servlet instructions to perform its intended task. All processing by a servlet is done on a request-by-request basis and happens in the service methods, either service() for generic servlets or one of the doOperation() methods for HTTP servlets. This method accepts incoming requests, processing them according to the instructions you provide, and directs the output appropriately. You can create other methods in a servlet as well.

Business logic may involve a database access to perform a transaction or passes the request to an EJB.


Overriding Initialize
Override the class initializer init(), to initialize or allocate resources for the servlet instance's life, such as a counter. The init() method runs after the servlet is instantiated but before accepting any requests. For more information, see the servlet API specification.

Note that all init() methods must call super.init(ServletConfig) in order to set their scope. This makes the servlet's configuration object available to other servlet methods.

The following example of the init() method initializes a counter by creating a public integer variable called thisMany:

public class myServlet extends HttpServlet {
   int thisMany;

   public void init (ServletConfig config) throws ServletException
   {
      super.init(config);
      thisMany = 0;
   }
}

Now other servlet methods can access the variable.


Overriding Destroy
Override the class destructor destroy() to write log messages or to release resources that are not released through garbage collection. The destroy() method runs just before the servlet itself is deallocated from memory. For more information, see the servlet API specification.

For example, the destroy() method could write a log message like the following, based on the example for Overriding Initialize above:

out.println("myServlet was accessed " + thisMany " times.\n");


Overriding Service, Get, and Post
When a request is made, the iPlanet Application Server hands the incoming data to the servlet engine to process the request. The request includes form data, cookies, session information, and URL name-value pairs, into a type HttpServletRequest object called the request object. Client metadata is encapsulated as a type HttpServletResponse object called the response object. The servlet engine passes both objects as the servlet's service() method parameters.

The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, GET, etc.) For example, HTTP POST requests are routed to the doPost() method, HTTP GET requests are routed to the doGet() method, and so on. This enables the servlet to perform different request data processing depending on the transfer method. Since the routing takes place in service(), there is no need to generally override service() in an HTTP servlet. Instead, override doGet() and/or doPost(), and so on, depending on the expected request type.

The automatic routing in an HTTP servlet is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In an iPlanet Application Server, request data is already preprocessed into a name-value list by the time the servlet sees the data, so simply overriding the service() method in an HTTP servlet does not lose any functionality. However, this does make the servlet less portable, since it is now dependent on preprocessed request data.

Override the service() method (for generic servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform tasks needed to answer the request. Very often, this means accessing EJBs to perform business transactions, collating the needed information (in the request object or in a JDBC result set object), and then passing the newly generated content to a JSP for formatting and delivery back to the client.

Most operations that involve forms use either a GET or a POST operation, so for most servlets you override either doGet() or doPost(). Note that implementing both methods to provide for both input types or simply pass the request object to a central processing method, as shown in the following example:

public void doGet (HttpServletRequest request,
                 HttpServletResponse response)
         throws ServletException, IOException {
   doPost(request, response);
}

All request-by-request traffic in an HTTP servlet is handled in the appropriate doOperation() method, including session management, user authentication, dispatching EJBs and JSPs, and accessing iPlanet Application Server features.

If a servlet intends to call the RequestDispatcher method include() or forward(), be aware the request information is no longer sent as HTTP POST, GET, and so on. In other words, if a servlet overrides doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to receive its data via HTTP GET. For this reason, be sure to implement routines for all possible input types, as explained above.

For more information, see Calling a Servlet Programmatically. RequestDispatcher methods always calls service().



Note Arbitrary binary data, like uploaded files or images, can be problematic, since the web connector translates incoming data into name-value pairs by default. Program the web connector to properly handle these kinds of data and package them correctly in the request object.




Accessing Parameters and Storing Data

Incoming data is encapsulated in a request object. For HTTP servlets, the request object type is HttpServletRequest. For generic servlets, the request object type is ServletRequest. The request object contains all request parameters, including your own request values called attributes.

To access all incoming request parameters use the getParameter() method. For example:

String username = request.getParameter("username");

Set and retrieve values in a request object using setAttribute() and getAttribute(), respectively. For example:

request.setAttribute("favoriteDwarf", "Dwalin");

This shows one way to transfer data to a JSP, since JSPs have access to the request object as an implicit bean. For more information, see Using JavaBeans.


Handling Sessions and Security

From a web or application server's perspective, a web application is a series of unrelated server hits. There is no automatic recognition if a user has visited the site before, even if their last interaction were seconds before. A session provides a context between multiple user interactions by remembering the application state. Clients identify themselves during each interaction by with a cookie, or, in the case of a cookie-less browser, by placing the session identifier in the URL.

A session object can store objects, such as tabular data, information about the application's current state, and information about the current user. Objects bound to a session are available to other components that use the same session.

For more information, see Chapter 11 "Creating and Managing User Sessions."

With a successful login, direct a servlet to establish the user's identity in a standard object called a session object that holds information about the current session, including the user's login name and whatever additional information to retain. Application components can then query the session object to obtain user authentication.

To provide a secure user session to your application, see Chapter 12 "Writing Secure Applications."


Accessing Business Logic Components

In the iPlanet Application Server programming model, you implement business logic, including database or directory transactions and complex calculations in EJBs. A request object reference can be passed as an EJB parameter to perform the specified task.

Store the results from database transactions in JDBC ResultSet objects and pass object references to other components for formatting and delivery to the client. Also, store request object results by using the request.setAttribute() method, or in the session by using the session.putValue() method. Objects stored in the request object are valid only for the request length, or in other words for this particular servlet thread. Objects stored in the session persist for the session duration, which can span many user interactions.

JDBC result sets are not serializable, and cannot be distributed among multiple servers in a cluster. For this reason, do not store result sets in distributed sessions. For more information, see Chapter 11 "Creating and Managing User Sessions."

This example shows a servlet accessing an EJB called ShoppingCart by creating a cart handle by casting the user's session ID as a cart after importing the cart's remote interface. The cart is stored in the user's session.

import cart.ShoppingCart;
   
   // Get the user's session and shopping cart
   HttpSession session = request.getSession(true);
   ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());

   // If the user has no cart, create a new one
   if (cart == null) {
      cart = new ShoppingCart();
      session.putValue(session.getId(), cart);
   }

Access EJBs from servlets by using the Java Naming Directory Interface (JNDI) to establish a handle or proxy, to the EJB. Next, refer to the EJB as a regular object; overhead is managed by the bean's container.

This example shows JNDI looking up a proxy for the shopping cart:

String jndiNm = "java:comp/env/ejb/ShoppingCart";
javax.naming.Context initCtx;
Object home;
   try
   {
      initCtx = new javax.naming.InitialContext(env);
   }
   catch (Exception ex)
   {
      return null;
   }
   try
   {
      java.util.Properties props = null;
      home = initCtx.lookup(jndiNm);
   }
   catch(javax.naming.NameNotFoundException e)
   {
      return null;
   }
   catch(javax.naming.NamingException e)
   {
      return null;
   }
   try
   {
      IShoppingCart cart = ((IShoppingCartHome) home).create();
   
}
catch (...) {...}

For more information on EJBs, see Chapter 4 "Introducing Enterprise JavaBeans."


Handling Threading Issues

By default, servlets are not thread-safe. The methods in a single servlet instance are usually executed numerous times simultaneously (up to the available memory limit). Each execution occurs in a different thread though only one servlet copy exists in the servlet engine.

This is efficient system resource usage, but is dangerous because of how Java manages memory. Because parameters (objects and variables) are passed by reference, different threads can overwrite the same memory space as a side effect. To make a servlet (or a block within a servlet) thread-safe, do one of the following:

  • Synchronize access to all instance variables, as in the following example:

    public synchronized void method() (whole method) or
    synchronized(this) {...} (block only). Because synchronizing slows response time considerably, synchronize only blocks, or write blocks that do not need synchronization.

    For example, this servlet has a thread-safe block in doGet() and a thread-safe method called mySafeMethod():

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

       public class myServlet extends HttpServlet {

       public void doGet (HttpServletRequest request,
                        HttpServletResponse response)
                throws ServletException, IOException {
          //pre-processing
          synchronized (this) {
             //code in this block is thread-safe
          }
          //other processing;
          }

       public synchronized int mySafeMethod (HttpServletRequest request)
          {
          //everything that happens in this method is thread-safe
          }
       }

  • Use SingleThreadModel to create a single-threaded servlet. In this case, when a single-threaded servlet is registered with the iPlanet Application Server, the servlet engine creates a 10 servlet instances pool used for incoming requests (for example, 10 copies of the same servlet in memory). The number of servlet instances in the pool is changed by setting the number-of-singles element in the iPlanet Application Server specific web application DD to a different number. The iPlanet Application Server Deployment Tool is used to modify this number in the iPlanet Application Server specific web application DD. For more information on the iPlanet Application Server web application DD, see Chapter 10 "Deployment Packaging," iPlanet Application Server Deployment Tool, and the Administration Guide. A single-threaded servlet is slower under load because new requests must wait for a free instance in order to proceed, but this is not a problem with distributed, load-balanced applications since the load automatically shifts to a less busy kjs process.

    For example, this servlet is completely single-threaded:

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

       public class myServlet extends HttpServlet
          implements SingleThreadModel {
          
    servlet methods...
       }


Delivering Client Results

The final user interaction activity is to provide a response page to the client. The response page can be delivered in two ways:


Creating a Servlet Response Page
Generate the output page within a servlet by writing to the output stream. The recommended way to do this depends on the output type.

Always specify the output MIME type using setContentType() before any output commences, as in this example:

response.setContentType("text/html");

For textual output, such as plain HTML, create a PrintWriter object and then write to it using println. For example:

PrintWriter output = response.getWriter();
output.println("Hello, World\n");

For binary output, write to the output stream directly by creating a ServletOutputStream object and then write to it using print(). For example:

ServletOutputStream output = response.getOutputStream();
output.print(binary_data);

Note, a servlet can not call a JSP from a PrintWriter or ServletOutputStream object.



Note If you use the iPlanet Application Server with the iPlanet Web Server, do not set the date header in the output stream using setDateHeader(). This results in a duplicate date field in the response page's HTTP header the server returns to the client. This is because the iPlanet Web Server automatically provides a header field. Conversely, Microsoft Internet Information Server (IIS) does not add a date header, so one must provided.




Creating a JSP Response Page
Servlets can invoke JSPs in two ways:

  • The include() method in the RequestDispatcher interface calls a JSP and waits for it to return before continuing to process the interaction. The include() method can be called multiple times within a given servlet.

    This example shows a JSP using include():

       RequestDispatcher dispatcher =
          getServletContext().getRequestDispatcher("
    JSP_URI");
       dispatcher.include(request, response);
       ... //processing continues

  • The forward() method in the RequestDispatcher interface hands the JSP interaction control. The servlet is no longer involved with the current interaction's output after invoking forward(), thus only one call to the forward() method can be made in a particular servlet. Note, you cannot use the forward() method if you have already defined a PrintWriter or ServletOutputStream object.

    This example shows a JSP using forward():

       RequestDispatcher dispatcher =
          getServletContext().getRequestDispatcher("
    JSP_URI");
       dispatcher.forward(request, response);


    Note Identify which JSP to call by specifying a Universal Resource Identifier (URI). The path is a String describing a path within the ServletContext scope and must begin with a backslash ("/"). There is also a getRequestDispatcher() method in the request object that takes a String argument indicating a complete path. For more information about this method, see the Java Servlet Specification, v2.2, section 8.



For more information about JSPs, see Chapter 3 "Presenting Application Pages with JavaServer Pages."


About the Servlet's Deployment Descriptor

Servlet DDs are created with the iPlanet Application Server Deployment Tool. These descriptors are packaged within the Web Application aRchive (.war) files that contain metadata, the servlet information that identifies it and establishes its application role.


Elements

The DDs for a servlet contains standard J2EE specified elements as well as iPlanet Application Server specific elements. The servlet DDs convey the elements and configuration information of a web application between developers, assemblers, and deployers. For more information about these elements, see Chapter 10 "Deployment Packaging."


Dynamically Reloading Servlets
Servlet reloading in an iPlanet Application Server is done without restarting the server by simply redeploying the servlet. The iPlanet Application Server notices the new component and reloads it within 10 seconds. For more information, see Appendix B "Dynamic Reloading."



Note This feature is turned off by default for a production environment. Turn it on when needed



To load a new servlet configuration file into the iPlanet Application Server, perform the following steps to make the changes active:

  1. Stop the server.

  2. Deploy the new servlet XML file by incorporating it in the original .war file.

  3. Restart the server.


Accessing iPlanet Application Server Optional Features

Many additional iPlanet features augment servlets for use in an iPlanet Application Server environment. These features are not a part of the official specifications, though some are based on emerging Sun standards and conforms to the future standards.

For more information on the iPlanet Application Server features, see Chapter 13 "Taking Advantage of the iPlanet Application Server Features."

The iPlanet Application Server provides support for more robust sessions, based on a previous version model of the iPlanet Application Server. This model uses the same API as the session model described in the Servlet 2.2 Specification, which is also supported. For more details on distributable sessions, see Chapter 11 "Creating and Managing User Sessions."



Invoking Servlets



Invoke a servlet by either, directly addressing it from an application page with a URL or by calling it programmatically from an already running servlet.


Calling a Servlet With a URL

Most times, call the servlets by using URLs embedded as links in the application's pages. This section describes how to invoke servlets using standard URLs.


Invoking Specific Application Servlets

The URL request path that leads to a servlet responding to a request composes several sections. Each section has to locate the appropriate servlet. The request object exposes the following elements when obtaining the request's URI path:

  • Context Path

  • Servlet Path

  • PathInfo

For more information on these elements, see the Java Servlet Specification, v2.2, section 5.4.

Address servlets that are part of a specific application as follows:

http://server:port/NASApp/moduleName/servletName?name=value

Table 2-2 describes each URL section.


Table 2-2    URL Fields for Servlets within a Specific Application  

URL element

Description

server:port  

Address and optional web server port number handling the request.  

NASApp  

Indicates to the web server this URL is for an iPlanet Application Server application, the request routes to the iPlanet Application Server executive server.  

moduleName  

The servlet module name (these names are unique across the server).  

servletName  

The servlet name, as configured in the XML file.  

The module name moduleName corresponds to a directory under AppPath/applicationName or AppPath/modulesDirName depending on whether the module is registered as part of an application or as a standalone entity, respectively. It reflects the .war module name that contains the servlets and JSPs, and its contents are the same as those of the .war module. For example:

http://www.my-company.com/NASApp/OnlineBookings/directedLogin


Invoking Generic Application Servlets

Address servlets that are part of the generic application as follows:

http://server:port/servlet/servletName?name=value

Table 2-3 describes each URL section.


Table 2-3    URL Fields for Servlets within a Generic Application

URL element

Description

server:port  

Address and optional web server port number handling the request.  

servlet  

Indicates to the web server this URL is for a generic servlet object.  

servletName  

The servlet name, as specified in the servlet-name element in the Web App XML file.  

?name=value...  

Optional servlet name-value parameters.  

For example:

http://www.leMort.com/servlet/calcMortgage?rate=8.0&per=360&bal=180000



Note All servlets deployed to use the /servlet path, must be deployed as part of the "default" application.




Calling a Servlet Programmatically

First, identify which servlet to call by specifying a URI. This is normally a path relative to the current application. For instance, if your servlet is part of an application with the context root called Office, the URL to a servlet called ShowSupplies from a browser:

http://server:port/NASApp/Office/ShowSupplies?name=value

You can call this servlet programmatically from another servlet in one of two ways, as described below.

  • To include another servlet's output use the include() method from the RequestDispatcher interface. This method calls a servlet by its URI and waits for it to return before continuing to process the interaction. include() can be called multiple times within a given servlet.

    For example:

       RequestDispatcher dispatcher =
          getServletContext().getRequestDispatcher("/ShowSupplies");
       dispatcher.include(request, response);

  • To hand interaction control to another servlet, use the RequestDispatcher interface's forward() method with the servlet's URI as a parameter.

    Note, forwarding a request means the original servlet is no longer involved with the current interaction output after invoking forward(). Therefore, only one forward() call is made in a particular servlet.

    This example shows a servlet using forward():

       RequestDispatcher dispatcher =
          getServletContext().getRequestDispatcher("/ShowSupplies");
       dispatcher.forward(request, response);



    Note Both servlet invoking mechanisms, either programatically (using include() or forward()) or from the URL, can use URL patterns for the servlet specified in the DD XML file, as well as in the <servlet-name> entry. For example, if the XML entry for a servlet in the web.xml file is:

    <servlet-name>F</ servlet-name>
    <servlet-mapping>
    <servlet-name>
    F</ servlet-name>
    <url-pattern>
    B</ url-pattern>
    </servlet-mapping>

    You can access the servlet in either of the following ways:

    • http://serverName:portNumber/NASApp/<context root>/F

    • http://serverName:portNumber/NASApp/<context root>/B




Previous     Contents     Index     DocHome     Next     
Copyright © 2000 Sun Microsystems, Inc. Some preexisting portions Copyright © 2000 Netscape Communications Corp. All rights reserved.

Last Updated January 25, 2001