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 Java servlets to control interactions in iPlanet Application Server (iAS) applications.

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

In iAS, servlets make up the presentation logic of an application by acting as a central dispatcher for your application by processing form input, invoking business logic components by accessing Enterprise JavaBeans, and formatting page output using JSPs. Servlets control the application's flow from one user interaction to the next by generating content in response to a request from your user.

This chapter contains the following sections:



Introducing Servlets

The iAS servlets are based on the Java Servlet Specification v2.2. All specifications are accessible from installdir/ias/docs/index.htm, where installdir is the location in which you installed iAS.

There are three kinds of servlets: those that adhere strictly to the specification; those that take advantage both of the specification and additional iAS features; and those that adhere to the specification in non-iAS environments, but that take advantage of iAS features if they are available. This chapter describes standard servlets as well as the iAS features that augment the standards, and enables you to make the best choice for your intended deployment scenario.

The fundamental characteristics of servlets are as follows:

  • Servlets are created and managed at run time by the servlet engine, a component of iAS that runs inside the Java server.

  • The input data on which servlets operate is encapsulated in an object called the request object. A servlet's response to a query is encapsulated in an object called the response object.

  • Servlets call EJBs to perform business logic functions. Servlets call JSPs to perform page layout functions.

  • You can extend a servlet's functionality by using APIs provided with iAS. You are not required to use any of these APIs in order to create a servlet.

  • Servlets control user sessions in order to provide some persistence of user information between interactions.

  • Servlets can be a part of a particular application, or they can reside separately in order to be available to multiple applications. The latter type are said to be members of the generic ("Default") application.

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

  • Servlets are addressable as URLs. The buttons on your application's pages usually point to servlets. Servlets can also call other servlets.

Several features are offered by iAS through iAS-specific APIs that enable your applications to take programmatic advantage of specific features of the iAS environment. For more information, see Accessing Optional iAS Features.


Servlets in iAS Applications

When a user of your application clicks a button on one of your application's pages, the information that the user entered on the page is sent to a servlet. The servlet processes the incoming data and orchestrates a response by generating content, often through the use of business logic components (Enterprise JavaBeans). Once the content is generated, the servlet creates a response page, usually by forwarding the newly generated content to a JavaServer Page (JSP). The response is delivered back to the client, which sets up the next user interaction.

The following illustration shows the life cycle of a single user interaction, the execution of a single servlet.



  1. Process incoming request from client

When a user clicks a button to submit information to your application, form, page, and session data are passed as a parameter to a servlet in a request object. A response object is also passed which contains information about the client itself. The servlet can manipulate these objects as well as forward them to other application components.

If an instance of the servlet does not already exist, iAS instantiates it when it is called. Servlet configuration information is loaded into iAS when the servlet is instantiated.

  1. Generate content

The servlet dispatches business logic tasks by invoking business objects (EJBs). The servlet may also invoke other servlets, JSPs, or other classes as needed to perform discrete tasks. The servlet gathers results in the request object.

  1. Create a response

The servlet generates a response by either creating a browser page and sending it directly to the client, or by dispatching the task to a JSP. The servlet remains in memory, available to process another request.

For a more detailed description of a servlet's life cycle, see How Servlets Work below.


How Servlets Work

This section describes the basic ingredients of all servlets. It shows how iAS runs servlets from the perspective of the server itself. Servlets exist in the iAS Java server process and are managed by an object called the servlet engine. The servlet engine is an internal object that handles all servlet metafunctions. These functions include instantiation, initialization, destruction, access from other components, and configuration management.


Types of Servlets

Servlets must implement the interface javax.servlet.Servlet. There are two main types of servlets:

  • Generic servlets extend javax.servlet.GenericServlet. Generic servlets are protocol independent, meaning that they contain no inherent support for HTTP or any other transport protocol.

  • HTTP servlets extend javax.servlet.HttpServlet. These servlets have built-in support for the HTTP protocol and are much more useful in an iAS environment.

For both types of servlets, you can implement the constructor method init() and/or the destructor method destroy() if you need to initialize or deallocate resources.

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


Instantiating and Removing Servlets
Servlets are instantiated by the servlet engine. After the servlet is instantiated, the servlet engine runs its init() method to perform any necessary initializations. Override this method only if you need to perform an initial function for the life of the servlet, such as initializing a counter.

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


How Servlets Handle Requests
When a request is made, iAS hands the incoming data to the servlet engine, which processes the request, including form data, cookies, session information, and URL name-value pairs, into an object of type HttpServletRequest called the request object. Client metadata is encapsulated as an object of type HttpServletResponse and is called the response object. The servlet engine passes both as parameters to the servlet's service() method.

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 processing on the request data depending on the transfer method. Since the routing takes place in service(), you generally do not override service() in an HTTP servlet. Instead, override doGet() and/or doPost(), etc., depending on the type of request you expect.

Note The automatic routing in an HTTP servlet is based simply on a call to request.getMethod(), which provides the HTTP transfer method. Since request data is already preprocessed into a name-value list in iAS, you could simply override the service() method in an HTTP servlet without losing any functionality. However, this does make the servlet less portable, since it is now dependent on preprocessed request data.

You must override the service() method (for generic servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform the 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 ResultSet object), and then passing the newly generated content to a JSP for formatting and delivery back to the client.


How the Servlet Engine Allocates Resources

By default, the servlet engine creates a thread for each new request. This approach is less resource-intensive than instantiating a new copy of the servlet in memory for every request, but you must make sure to avoid threading issues, since each thread operates in the same memory space and variables can overwrite each other.

If a servlet is specifically written as single-threaded, the servlet engine creates a pool of ten (10) instances of the servlet 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 instances in the pool is configurable in the Deployment Descriptor (i.e. the iAS-specific XML file.) Refer to Chapter 10 "Packaging for Deployment", for more details.

For tips on threading issues, see Handling Threading Issues.


Run-Time Servlet Modifications

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


How Servlets Are Configured

Servlet configuration refers to the servlet's metadata, information about the servlet that enables the server to create and use it in the framework of an application.

For more information about servlet configuration, see , "Packaging for Deployment."


Important Servlet Files and Locations

Servlet files and other application files reside in a directory structure whose location is known to iAS as AppPath. This variable defines the top of a logical directory tree for the application, similarly to the document path in a web browser. By default, AppPath contains the value BasePath/APPS, where BasePath is the base iAS directory. (BasePath is also an iAS variable.)

AppPath and BasePath are variables held in the iAS registry, a repository for server and application metadata. See "The iAS Registry" in Chapter 10 "Packaging for Deployment and the Administration and Deployment Guide.

The following table describes important files and locations for servlets:

Table 2-1 Important files and locations for servlets.

Location

Description

BasePath  

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

AppPath  

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

AppPath/appName/*  

Top of the subtree for the application appName. Files in this directory are part of the specific application appName. This corresponds to the URL used to access the application's components; see .  


Deploying Servlets

You normally deploy servlets with the rest of an application using the iAS Deployment Manager. You can also choose to deploy servlets manually for the purposes of testing or for updating servlets while the server is running.

For more information, see the iAS Deployment Tool Administration and Deployment Guide.



Designing Servlets



This section describes some of the basic design decisions you have to make when planning the servlets that help make up your application.

Web applications generally follow a request-response paradigm. 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 helps to determine how to design each servlet by defining the required input and output parameters for each interaction.


Choose a Component: Servlet or JSP

If the layout of a page is its main feature and there is little or no processing involved to generate the page, you may find it easier to use a JSP alone for the interaction.

For example, after the Online Bookstore sample application authenticates a user, it provides a boilerplate "portal" front page where the user can choose one of several tasks, including a book search, purchase selected items, etc. Since this portal conducts little or no processing itself, it could be implemented solely as a JSP.

Think of JSPs and servlets as opposite sides of the same coin. Each can perform all the tasks of the other, but each is designed to excel at one task at the expense of the other. The strength of servlets is in processing and adaptability, and since they are Java files you can take advantage of integrated development environments while you are writing them. However, performing HTML output from them involves many cumbersome println statements. Conversely, JSPs excel at layout tasks because they are simply HTML files and can be edited with HTML editors, though performing computational or processing tasks with them can be awkward. Choose the tool that is right for the job you undertake.

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


Choose Servlet Type: HttpServlet or GenericServlet

Servlets that extend HttpServlet are much more useful in an HTTP environment, since that is what they were designed for. We recommend that all iAS servlets extend from HttpServlet rather than from GenericServlet in order to take advantage of this built-in HTTP support.

For more information, see Types of Servlets.


Create Standard or Non-Standard Servlets

One of the most important decisions 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 whether to utilize the features provided by iAS as APIs. These APIs can greatly increase the usefulness of your servlets in an iAS framework.

You can also create more portable servlets that only take advantage of iAS features if the servlet is running in an iAS environment.

For more information on iAS-specific APIs, see Accessing Optional iAS Features.


Planning for Code Re-Use

Servlets by definition are discrete, reusable applications that run on a server. A servlet does not necessarily have to be tied to one individual application. You could create a library of servlets 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.


How Many Servlets for Each Interaction?

There are several possibilities for programming a given user interaction with a servlet. The method you choose for a given interaction determines how you write the servlet that handles the interaction.


One servlet handles one request

The most straightforward servlet expects one certain request and provides one certain response, as in the following diagram:



A servlet can tailor the output by setting conditions. For example, a login page could lead to a welcome page for users, an administrative page for site managers, and an error page for incorrect login, as in the following diagram:




One servlet handles multiple requests

You can write a single servlet to handle many similar (or even dissimilar) requests by setting a conditional flag for each request, as in the following diagram:



For example, if a single servlet handles several steps, you could conditionalize the service() method based on a flag in the request object:

flag = request.getParameter("flag");
if ( flag.equals("step1")) {
    process_step1;}
else if ( flag.equals("step2")){
    process_step2;}
}

Additionally, the response the servlet provides can be conditional, based on the input it receives, as in the following diagram:




Several servlets handle one request

If reusable code is your goal, you can create several small servlets to handle individual functions in the course of a request, and each servlet can call other servlets for subprocessing using the forward() method, as in the following diagram:



You can call or include JSPs as well. By this method, you could create a library of discrete functional entities and use them wherever needed.



Creating Servlets



To create a servlet, you must perform the following tasks:

  • Design the servlet into your application, or, if you want it to be accessed in a generic way, design it so that it accesses no application data.

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

  • Use the iAS Administration Tool (iASAT) to create a Web-application Deployment Descriptor (DD) for the servlet.

For information about creating the files that make up a servlet, see the following sections:


Writing the Servlet's Class File

This section describes how to write a servlet, and the decisions you have to 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 iAS servlets exist in an HTTP environment, the latter is recommended.

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

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

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


Overriding Methods

Next, you must override one or more methods to provide instructions for the servlet to perform its designated task.

All of the processing done by a servlet on a request-by-request basis happens in the service methods, either service() for generic servlets or one of the doOperation() methods for HTTP servlets. This method accepts the incoming request, processes it 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 accessing a database to perform a transaction, or passing the request to an EJB.


Overriding init
You can override the class initializer init() if you need to initialize or allocate resources for the life of the servlet instance, such as a counter. The init() method runs after the servlet is instantiated but before it accepts 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 correctly. This makes the servlet's configuration object available to the other methods in the servlet.

The following example 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 methods in the servlet can access this variable.


Overriding destroy
You can override the class destructor destroy() to write log messages or to release resources that would not be 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 this, based on the example for Overriding init above:

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


Overriding service, doGet, and doPost
When a request is made, iAS hands the incoming data to the servlet engine, which processes the request, including form data, cookies, session information, and URL name-value pairs, into an object of type HttpServletRequest called the request object. Client metadata is encapsulated as an object of type HttpServletResponse and is called the response object. The servlet engine passes both objects as parameters to the servlet's service() method.

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 processing on the request data depending on the transfer method. Since the routing takes place in service(), you generally do not override service() in an HTTP servlet. Instead, override doGet() and/or doPost(), etc., depending on the type of request you expect.

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

You must override the service() method (for generic servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform the 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 ResultSet 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 you can implement both methods to provide for both types of input, or simply pass the request object to a central processing method, as in the following example:

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

All of the actual 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 iAS features.

If you have a servlet that you intend to also call using a RequestDispatcher method include() or forward() (see Calling a Servlet Programmatically), be aware that the request information is no longer sent as HTTP POST, GET, etc. RequestDispatcher methods always call service(). In other words, if a servlet overrides doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to have received its data via HTTP GET. For this reason, be sure to implement routines for all possible types of input, as explained above.

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. You can program the web connector to properly handle this kind of data and package it correctly in the request object. Accessing Parameters and Storing Data

Incoming data is encapsulated in a request object. For HTTP servlets, the request object is of type HttpServletRequest. For generic servlets, the request object is of type ServletRequest. The request object contains all the parameters in a request, and you can also set your own values in the request. The latter are called attributes.

You can access all the parameters in an incoming request by using the getParameter() method. For example:

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

You can also set and retrieve values in a request object using setAttribute() and getAttribute(), respectively. For example:

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

This reveals 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 Java Beans" in Chapter 3 "Presenting Application Pages with JavaServer Pages".


Handling Sessions and Security

From the perspective of a web server or application server, a web application is a series of unrelated server hits. There is no automatic recognition that a user has visited the site before, even if their last interaction was mere seconds before. A session provides a context between multiple user interactions by "remembering" the application state. Clients identify themselves during each interaction by way of 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".

Upon a successful login, you can 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 other information you want to retain. Application components can then query the session object to obtain authentication for the user.

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


Accessing Business Logic Components

In the iAS programming model, you implement business logic, including database or directory transactions and complex calculations, in EJBs. A pointer to the request object can be passed as a parameter to an EJB, which then performs the specified task.

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

JDBC ResultSets are not serializable, and thus can not be distributed among multiple servers in a cluster. For this reason, do not store ResultSets 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 handle to the cart 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);
   }

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

This example shows the use of JNDI to look 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 instance of each servlet can be executed numerous times (up to the limit of available memory) simultaneously, with each execution occurring in a different thread though only one copy of the servlet exists in the servlet engine.

This arrangement is efficient in how it uses system resources, but it can be dangerous because of how memory is managed in Java. 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 your blocks so that they do not need to be synchronized.

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
    }
}

  • Create a single-threaded servlet by implementing SingleThreadModel. In this case, when you register a single-threaded servlet with iAS, the servlet engine creates a pool of 10 servlet instances (i.e., 10 copies of the same servlet in memory) that can be used for incoming requests. The number of servlet instances in this pool can be changed by setting the number-of-singles element in the iAS specific web application deployment descriptor (DD) to a different number. The iAS Deployment Tool is used to modify this number in the iAS specific web application DD. Refer to Chapter 10 "Packaging for Deployment" in this document and the iASDT Administration and Deployment Guide for more iAS web application DD details. A single-threaded servlet can be slower under load because new requests must wait for a free instance in order to proceed, but this is less of 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 Results to the Client

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


Creating a Response Page in a Servlet
You can generate the output page within a servlet by writing to the output stream. The recommended way to do this depends on the type of output.

You must always specify the output MIME type using setContentType() before any other 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, you can write to the output stream directly by creating a ServletOutputStream object and then writing to it using print(). For example:

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

Note that your servlet can not call a JSP if you create a PrintWriter or ServletOutputStream object.

Note If you are using iAS with iPlanet Web Server (iWS), do not set the date header in the output stream using setDateHeader(). Doing so results in a duplicate date field in the HTTP header of the response page that the server returns to the client. This is because NES automatically provides this header field. Conversely, Microsoft Internet Information Server (IIS) does not add a date header, so you must provide one in your code.


Creating a Response Page in a JSP
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 invocation using include():

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

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

This example shows a JSP invocation using forward():

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

Note You identify which JSP to call by specifying a URI (Universal Resource Identifier). The path is a String describing a path within the scope of the ServletContext 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. See the Java Servlet Specification, v2.2 section 8 for more details about this method.

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


Creating the Servlet's Deployment Descriptor

Servlet deployment descriptors (DDs) are created by the iAS Deployment Tool (iASDT). These descriptors are packaged within the Web Application ARchive (.war) files that contain metadata, information about the servlet that identifies it and establishes its role in the application.


Deployment Descriptor Elements

The deployment descriptor for a servlet contains standard J2EE specified elements as well as iAS specific elements. The servlet DDs conveys the elements and configuration information of a web application between Developers, Assemblers, and Deployers. For a description of these elements refer to Chapter 10 "Packaging for Deployment".


Dynamically Reloading Servlets
You can reload servlets into iAS without restarting the server. Simply overwrite the servlet by redeploying. iAS "notices" the new component and reloads it within 10 seconds. For more information, see Appendix B "Dynamic Reloading.".

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

  1. Stop the server.

  2. Deploy the new servlet XML war file.

  3. Restart the server.


Accessing Optional iAS Features

The iAS provides many additional features to augment your servlets for use in an iAS environment. These features are not a part of the official specifications, though some are based on emerging Sun standards and will conform to those standards in the future.

For more details on iAS features, see Chapter 13 "Taking Advantage of iAS Features".

The iAS also provides support for more robust sessions, based on a model from a previous version of iAS. 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



You invoke a servlet either by directly addressing it from an application page with a URL, or by calling it programmatically from another servlet that is already running.


Calling a Servlet With a URL

Most of the time, you call servlets using URLs embedded as links in your 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 servicing a request is composed of several sections. Each of these sections has an important purpose in locating the appropriate servlet. The request object will expose the following elements obtained from the request URI path:

  • Context Path

  • Servlet Path

  • PathInfo

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

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

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

Each section of the URL is described in the table below:


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

URL element

Description

server:port  

Address and optional port number for the web server handling the request.  

NASApp  

Indicates to the web server that this URL is for a iAS application, so the request is routed to the iAS executive server.  

appName  

The application's name.  

servletName  

The servlet's name, as configured in the XML file.  

The application name appName must correspond to a directory under AppPath . This directory contains files extracted out during registration, like .jsps, and static content files like .html, .jpg and so on. For example:

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


Invoking Generic Application Servlets

Address servlets that part of the generic application as follows:

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

Each section of the URL is described in the table below:

A

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

URL element

Description

server:port  

Address and optional port number for the web server handling the request.  

servlet  

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

servletName  

The servlet's name, as specified in the servlet-name element in the web app XML file.  

?name=value...  

Optional name-value parameters to the servlet.  

For example:

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

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


Calling a Servlet Programmatically

You can call a servlet programmatically from another servlet in two ways, as described below.

Note that you identify which servlet to call by specifying a URI, or Universal Resource Identifier. This is normally a path relative to the current application. For instance, if your servlet is part of an application called Office, the URL to a servlet called ShowSupplies is shown below. The bold section is the portion of the URI to use in the call:

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

  • Include another servlet's output using the include() method from the RequestDispatcher interface. include() 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);

  • Hand control of the interaction to another servlet using the forward() method in the RequestDispatcher interface. takes the servlet's URI as a parameter.

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

This example shows a servlet invocation using forward():

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

Note Both mechanisms of invoking servlets, either programatically, or using the include()/forward() mechanism, or from the URL, can use the URL patterns for the servlet specified in the DD XML, as well as the <servlet-name> entry. For example,

if an XML entry for a servlet in the web.xml file is

<servlet-name>Foo</servlet-name>
<servlet-mapping>
<servlet-name>Foo</servlet-name>
<url-pattern>Bar</url-pattern>
</servlet-mapping>

then you can access the servlet either as

http://s:p/NASApp/AppName/Foo

or

http://s:p/NASApp/AppName/Bar

where

s: server name
p: port number
AppName: name of the application


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

Last Updated June 25, 2000