Previous     Contents     Index     Next     
iPlanet Application Server Developer's Guide



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 install_dir/ias/docs/index.htm, where install_dir 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 user requests.

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

    • Extend javax.servlet.GenericServlet.

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

  • HTTP servlets

    • Extend javax.servlet.HttpServlet.

    • Have 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 that 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 initialization. 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. This 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 11 "Packaging for Deployment."

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


Dynamically Reloading Servlets at Runtime

If no configuration file changes are needed, servlet reloading in an iPlanet Application Server is done without restarting the server by simply redeploying the servlet. This can also be achieved by replacing the Servlet class file with a new classfile in the same directory.

The iPlanet Application Server notices the new component and reloads it at the next request of the servlet. For more information, see Appendix B "Runtime Considerations."



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




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 11 "Packaging for Deployment."


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 variable 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 servlet locations:


Table 2-1    Important Files and Servlet Locations

Location Variable

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 stand-alone entities (in the Default application). This directory exists under AppPath. Defined by the registry variable ModulesDirName. The default value of this variable in the registry is modules.  

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 "Invoking Servlets."  


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 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 HttpServlet rather than GenericServlet 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.

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

For more information on iPlanet Application Server specific APIs, see "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. You can create a servlet library to be used across multiple applications by placing it in the application named Default.

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 a specific 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 to create a web application Deployment Descriptor (DD) for the servlet.



Servlet Files for an iPlanet Application

The files that make up a servlet include:


The Servlet's Class File

This section describes how to write a servlet, including the decisions to make about an application and the 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. If the servlet is part of a package, you must also declare the package name so the class loader can properly locate it.

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 database access to perform a transaction or passing 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 it accepts any requests. For more information, see the servlet API specification.



Note All init() methods must call super.init(ServletConfig) to set their scope. This makes the servlet's configuration object available to other servlet methods. If this call is omitted, a 500 SC_INTERNAL_SERVER_ERROR appears in the browser when the servlet starts up.



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, all in 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, and so on). 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(), 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 through HTTP GET. For this reason, be sure to implement routines for all possible input types, as explained above. RequestDispatcher methods always call service().

For more information, see "Calling a Servlet Programmatically."


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 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 12 "Creating and Managing User Sessions."

After a successful login, you should 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 for your application, see Chapter 13 "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 12 "Creating and Managing User Sessions."

This example shows a servlet accessing an EJB called ShoppingCart. The servlet creates 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) {
      String jndiNm = "java:comp/env/ejb/ShoppingCart";
      javax.naming.Context initCtx = null;
      Object home = null;
      try {
         initCtx = new javax.naming.InitialContext(env);
         java.util.Properties props = null;
         home = initCtx.lookup(jndiNm);
         cart = ((IShoppingCartHome) home).create();
      }
      catch (Exception ex) {
      .....
      .....
      }
   }

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 write access to all instance variables, as in public synchronized void method() (whole method) or synchronized(this) {...} (block only). Because synchronizing slows response time considerably, synchronize only blocks, or make sure that the blocks in the servlet 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 instance pool used for incoming requests (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 11 "Packaging for Deployment," the iPlanet Application Server Deployment Tool, and the Administrator's 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 cannot 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 be 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. 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."


The Servlet's Deployment Descriptor

Servlet DDs are created by the iPlanet Application Server Deployment Tool (you can also create them by hand). These descriptor files are packaged within Web Application aRchive (.war) files. They contain metadata, plus information that identifies the servlet and establishes its application role.



Note WAR module names identified by the first portion of their filenames (without the .war extensions) must be unique when deploying to the Application Server. Using a Java package-like naming scheme for these module filenames ensures that name collisions do not occur. The benefits of this naming practice apply not only to the iPlanet Application Server, but to other J2EE application servers as well.



The sample applications for iPlanet Application Server contain instructions for creating servlet DDs. These sample applications are located in the install_dir/ias/ias-samples directory.


Elements

The DD 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 11 "Packaging for Deployment."


Changing Configuration Files

To modify deployment descriptor settings, you can use the Deployment Tool or a combination of an editor and command line utilities such as Ant to reassemble and deploy the updated deployment descriptor information.


Using the Deployment Tool

  1. Open the EAR, WAR or EJB JAR file.

  2. Modify the deployment descriptors.

  3. Redeploy the EAR, WAR or EJB JAR module.

  4. Restart the application server to pick up the modified deployment descriptor settings.


Using the Command Line
Refer to the sample applications (in the install_dir/ias/ias-samples directory) for extensive examples of using Ant-based build.xml files to reassemble applications and modules from the command line.

  1. Edit the appropriate deployment descriptor file (web.xml or ias-web.xml) by hand.

  2. Execute an Ant build command (such as build war) to reassemble the appropriate EAR, WAR or EJB JAR module.

  3. Use the iasdeploy command to deploy the EAR or WAR file or module.

  4. Restart the application server to pick up the modified deployment descriptor settings.


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 conform to future standards.

For more information on the iPlanet Application Server features, see Chapter 14 "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 12 "Creating and Managing User Sessions."



Invoking Servlets



Invoke a servlet by either directly addressing it from an application page with a URL or calling it programmatically from an already running servlet. You can also Verify servlet parameters. See the following sections:


Calling a Servlet With a URL

Most times, you call 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 has 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  

The address and optional web server port number handling the request.  

NASApp  

Indicates to the web server that 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). The moduleName corresponds to a directory under AppPath/applicationName for a module that is registered as part of an application. It reflects the .war module name that contains the servlets and JSPs, and its contents are the same as those of the .war module.  

servletName  

The servlet name as configured in the XML file.  

For example:

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


Invoking Generic Application Servlets

Address servlets that are part of the generic Default 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  

The address and optional web server port number handling the request.  

servlet  

Indicates to the web server that 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 with the application name Default. Additionally, the servlet engine of the web server instance must be deactivated in order to pass the requests started with /servlet to the iPlanet Application Server.




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 a context root called Office, the URL to a servlet called ShowSupplies from a browser is as follows:

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. The include() method 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 forward() is invoked. Therefore, only one forward() call can be 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 programmatic (using include() or forward()) or from the URL, can use URL patterns for the servlet specified in the DD XML file or the <servlet-name> entry. For example, if the XML entry in the web.xml file is:

    <servlet-name>Fortune</servlet-name>
    <servlet-mapping>
    <servlet-name>Fortune</servlet-name>
    <url-pattern>/Business</surl-pattern>
    </servlet-mapping>

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

    • http://server:port/NASApp/context_root/Fortune

    • http://server:port/NASApp/context_root/Business




Verifying Servlet Parameters

You can verify the parameters passed to a servlet. This feature can increase iPlanet Application Server response time and save development time.

iPlanet Application Server can call a specified class for parameter verification. Based on the results of the verification, the server can either call the servlet method or abort the call to the servlet, redirecting the user to an error page. You must provide the parameter verification class and specify it in the Deployment Tool during servlet deployment. You can specify which parameters are validated.

The parameter verification code need not be present within the servlet. If more than one servlet accepts the same parameter, they must both use the same parameter verification function for that parameter.

In the IAS Params tab of the servlet descriptor in the Deployment Tool, you can specify the following for each parameter:

  • The name of the parameter

  • Whether verification is required

  • The class and method to call for verification

  • The format of the parameter

  • The parameter's scope

  • The error page to display in case of an error


Previous     Contents     Index     Next     
Copyright © 2002 Sun Microsystems, Inc. All rights reserved.

Last Updated March 06, 2002