BEA Logo BEA WebLogic Server Release 5.0

  Corporate Info  |  News  |  Solutions  |  Products  |  Partners  |  Services  |  Events  |  Download  |  How To Buy

Using WebLogic HTTP Servlets

I. Introduction
What is a servlet?
Overview of HTTP servlet support in WebLogic
How it all fits together

II. The WebLogic internal servlets

III. WebLogic HTTP servlet API reference

IV. Implementing with WebLogic HTTP servlets
General guidelines for developing an HTTP servlet
Initializing a servlet
Using the ServletServlet
Using the servlet classpath
Providing an HTTP response
Retrieving client input
Using session tracking from a servlet
Using cookies in a servlet
Using WebLogic services from an HTTP servlet
Using connection pools with server-side Java
Threading issues in HTTP servlets
Passing the request to another HTTP servlet
Using server-side includes (SSI)
Clustering servlets
Setting up ACLs for servlets in the WebLogic realm
IV. Change history

Other related documents
Using WebLogic JSP (Documentation)
Writing a Web Application
Setting up WebLogic as an HTTP server
All Developers Guides (Documentation)
API Reference (Documentation)
Installing WebLogic (non-Windows)
Installing WebLogic (Windows)
The HttpServlet 2.2 API (at Sun)
Java API Servlet 2.2 Specification (at Sun)
The Java Servlet Tutorial (at Sun)

I. Introduction

The WebLogic Server implements the HTTP servlet 2.2 API, available at:

The HTTP servlet 2.2 specification introduces the new concept of a Web Application. For details on developing and deploying Web Applications on the WebLogic Server, see the Developers Guide "Writing a Web Application".

What is a servlet?

In generic terms, a servlet is any class that can be invoked and executed on the server, most likely on behalf of a client. Don't confuse servlets with applets; a servlet does its work on the server, but an applet does its work on the client. Another way of phrasing what servlets do is "server-side Java".

So, what is an HTTP servlet? An HTTP servlet is a Java class that handles an HTTP request and delivers an HTTP response. HTTP servlets live in an HTTP server and must extend the javax.servlet.http.HttpServlet class, so that they can run in a generic servlet engine framework.

The WebLogic Server can be configured as a fully functional HTTP Server that delivers any arbitrary MIME type to HTTP clients. For more information on setting this up, see the Administrators Guide document, Setting up WebLogic as an HTTP server. To provide more complex web pages that accept input from the client and provide dynamic responses, you must write your own custom HTTP servlets. You can develop sophisticated web sites, such as shopping-carts or online booking forms by combining WebLogic's built-in services like EJB and JDBC, but HTTP servlets are the key to delivering this functionality to the web.

You can write your own custom HTTP servlets and register them with the WebLogic Server. Your HTTP servlets live within the security of the WebLogic Server, and are called upon to service HTTP requests from clients. The work performed by HTTP servlets can be compared to that of CGI scripts, but HTTP Servlets are more sophisticated since:

  • They are written in a well formed, and compiled language -- Java, so are more robust than 'interpreted' scripts.
  • They are an integral part of the HTTP server that supports them.
  • They can be protected by the robust security of the server -- unlike some CGI scripts that are hazardous.
  • They interact with the HTTP request via a well-developed programmatic interface, so are easier to write and less prone to errors.
Other advantages specific to WebLogic HTTP servlets are discussed in the next section, Overview of HTTP servlet support in WebLogic.

This document details how to use HTTP servlets to perform server-side Java tasks in response to HTTP requests. For web services that require more sophisticated presentation, you should use Java ServerPages. With JSP you write the static HTML content directly, and embed the Java logic into the page, as opposed to Servlets which are purely code-based and must write out the static HTML to the response stream.

Top of the page

Overview of HTTP servlet support in WebLogic

The code in your HTTP servlets can use all of WebLogic's server-side services, including EJB, RMI, and JDBC. Below is an overview of the support services available to HTTP servlets:

Session tracking
Session tracking allows a website to track a user's progress across multiple web pages. This is vital functionality to support sites using shopping carts or auctions. WebLogic supports session persistence to a database, providing fail-over between server down time and session sharing between clustered servers.

Database access
Your servlets can use JDBC drivers (including WebLogic's) for basic database access. With WebLogic's multitier JDBC driver, you can take advantage of connection pools, server-side data caching, and other multitier features.

The WebLogic Server can support HTTP requests to multiple domains. For more information on how to set up multihoming, see the WebLogic Administration Guide, Setting up and starting the WebLogic Server.

Configuration and management
The WebLogic Console provides an integrated GUI tool for administration of servlets.

WebLogic has built-in security, with SSL (Secure Sockets Layer) for authentication and encryption of client-to-server communications, and ACLs (Access Control Lists) for configurable allocation of server resources.

Logging and report generation
HTTP requests are logged in the access.log file in common log format that you can configure (see the Administrators Guide document, Setting up WebLogic as an HTTP server.) The WebLogic Server can be configured to submit events to WebLogic's Event Topic Tree for each HTTP request, providing detailed common-log fields. You can write report-generating applications that register interest in these HTTP events.

Integrated services
WebLogic HTTP servlets is one of the many services available to WebLogic applications, including JDBC, RMI, EJB, Events, and JavaBeans. The APIs for all of WebLogic's services and facilities share many common aspects that make building a complex networked application easier; your application may use several services, all of which can share access to objects and client resources.

Top of the page

How it all fits together

HTTP servlets are a crucial part of the WebLogic Server's HTTP capabilities. In fact, the WebLogic Server fulfills all of its HTTP requirements using a set of pre-built HTTP servlets that are implemented and registered exactly as you would write and register your own custom servlets. For instance, in the WebLogic Server:

  • Requests for HTML pages and accompanying HTTP data are all handled by an internal servlet called the FileServlet.
  • Server-side includes, or ".shtml" files, are handled using an internal servlet called the ServerSideIncludeServlet.
  • JSP pages are handled by an internal servlet called the JSPServlet.
  • Applets and other class files are served to web-clients using an internal servlet called the ClasspathServlet.

A description of these and the other HTTP servlets that WebLogic uses to handle HTTP requests is given in the next section.

After you write your own HTTP servlets, you register them in the file in exactly the same way as the standard internal servlets that are shipped with the WebLogic Server. Your custom servlets are treated exactly like the standard HTTP servlets that provide the HTTP capabilities.

How does the WebLogic Server know which HTTP servlet should service a particular HTTP request? Each HTTP servlet is registered against a specific URL pattern, so that when a matching URL is requested, the corresponding servlet is called upon to handle the request. For details on registering HTTP servlets with the WebLogic Server, see the WebLogic Administrators Guide, Registering user-written servlets.

Top of the page

II. The WebLogic internal servlets

As described above, WebLogic uses several internal HTTP servlets to support the various types of web-related functionality. These servlets are registered in the file. WebLogic does not publish their classdocs as part of the public API, but a description of each HTTP servlet is provided in the Setting WebLogic Properties document under Registering the WebLogic servlets. You can call upon these servlets from an HTTP client, and can integrate their features into your web based applications.

Top of the page

III. WebLogic HTTP servlet API reference

WebLogic supports the javax.servlet.http package in the Java Servlet 2.2 API. You can find documentation for the package at Sun.

Package javax.servlet
Package javax.servlet.http

Top of the page

IV. Implementing with WebLogic HTTP servlets

General guidelines for developing an HTTP servlet
Writing a servlet
A simple example
Compiling the servlet
Deploying the servlet
Calling the servlet
Using the ServletServlet
Using the servlet classpath
Initializing your servlet
Initializing a servlet at server startup
Using initialization parameters
Overriding the init() method
Providing an HTTP response
Configuring the HttpServletResponse
Composing the visual page
Retrieving client input
Using session tracking from a servlet
A history of session tracking
Tracking a session with the Session object
The lifetime of a session
How session tracking works
Detecting the start of a session
Setting and getting session name/value attributes
Logging out and ending a session
Configuring session tracking
Configuring session cookies
Using URL rewriting
Making sessions persistent
Using cookies in a servlet
What is a cookie?
Setting cookies in an HTTP servlet
Retrieving cookies in an HTTP servlet
Using cookies that will be transmitted by both HTTP and HTTPS
Your application security and cookies
Using WebLogic services from an HTTP servlet
Using connection pools with server-side Java
Setting up the registration for a connection pool
Using a connection pool in your servlet
Threading issues in HTTP servlets
Passing the request to another HTTP servlet
Using server-side includes (SSI)
Clustering servlets
Setting up ACLs for servlets in the WebLogic realm
Setting ACLs for groups of servlets

General guidelines for developing an HTTP servlet

This section describes the steps to develop an HTTP servlet, deploy it on the WebLogic Server, and call it from a web-browser.

Writing a servlet

To write an HTTP servlet class, follow these guidelines:

  1. Import the appropriate packages and classes, including:
      import javax.servlet.*;
      import javax.servlet.http.*;
  2. Your HTTP servlet class must extend javax.servlet.http.HttpServlet. For example:
      class HelloWorldServlet 
            extends javax.servlet.http.HttpServlet {

  3. If your servlet needs to initialize some data, or accept initialization arguments, you should override the method:
      public void init(ServletConfig config) 
              throws ServletException
        // Must call super.init to parse init arguments

    This method is invoked just prior to the first time the servlet is called upon to service an HTTP request. You should call the init(ServletConfig config) method on the super class before attempting to read initialization parameters. It is a good idea to make this the first statement in the method, as shown above. For more details see Initializing a servlet later in this document.

  4. The main function of a servlet is to accept an HTTP request from a web-browser, and return an HTTP response. This work is done by your servlet's service() method.

    Your servlet implements the service() method to respond to any HTTP request. You may have seen other servlet examples implement the doPost() or/and doGet() methods. These reply only to POST or GET requests; If you wish to handle all request types from a single method, your servlet can simply implement the service() method. The HTTP servlet specification describes other methods used to handle other less-common request types, however all of these methods are collectively referred to as service methods.

    All of the service methods take the same parameter arguments; an HttpServletRequest provides information about the request, and an HttpServletResponse, is used by your servlet to reply to the HTTP client. Here is a minimal service method:

      public void doGet(HttpServletRequest request, 
                        HttpServletResponse response) 
        throws ServletException

  5. Servlets should be written so that the desired result occurs even if the user resizes or reloads the browser. For example, if a user resizes their browser while in the process of buying a car, it is possible that the servlet may be invoked again. Without any mechanism to account for browser reloading or resizing, the servlet may act as if the user had purchased 2 cars.

    The other sections in this document describe how to write the functionality of a servlet such as getting user input and providing a response, tracking state, and storing user preferences using cookies.

A simple example

Let's examine a simple servlet that provides a response to an HTTP request. Later, we'll add to this example to illustrate how to use HTTP parameters, cookies, and session tracking.

You can find the source and instructions on how to compile and run all the examples used in this document in the examples/servlets directory of your WebLogic distribution.

First we import the packages that support the servlet functionality. Then we implement the service() method that responds with some HTML to the client's browser. Here is the code:

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

public class HelloWorldServlet extends HttpServlet {
  public void service(HttpServletRequest req, 
                      HttpServletResponse res)
       throws IOException
    // Must set the content type first
    // Now obtain a PrintWriter to insert HTML into
    PrintWriter out = res.getWriter();

    out.println("<html><head><title>" +
                "Hello World!</title></head>");
    out.println("<body><h1>Hello World!</h1></body></html>");

The HttpServletRequest object that is passed to the service() method provides information about the client making the request; we'll discuss that later in this document. The HttpServletResponse object is used to send a response back to the client.

Before you can send a response back to the client, you must first set the content type of the HTTP response using the HttpServletResponse.setContentType() method. Then call the HttpServletResponse.getWriter() method to obtain the servlet output stream through which your servlet passes the HTTP response. The HttpServletResponse must know about the content type before the appropriate type of output stream can be selected.

Once you have an output stream, you can use its print() method to send the contents of your servlet's HTTP response. The content is flushed automatically for you by the WebLogic servlet engine when the servlet service() method returns.

Compiling the servlet

Open a new command shell, and run the setEnv script provided in the root directory of the WebLogic installation. If necessary, edit the script in a text editor to point to the correct JDK and WebLogic home directory.

In the directory containing your servlet Java source code, compile and place your servlet class in the servlet classpath. The setEnv script sets the environment variable %SERVLET_CLASSES% to point to the default servlet classpath directory. You can now compile you servlet with:

 $  javac -d %SERVLET_CLASSES%

The servlet classpath is set up to point to the %SERVLET_CLASSES% directory in the file, with the property:

Search for the property in the file and uncomment it if necessary.

Next, you must deploy the servlet on the WebLogic Server so that it may be called from a web-browser client.

Deploying the servlet

To access your servlet from a web-browser client, you must deploy it on the WebLogic Server. Here are a number of ways you can deploy servlets that will suit different situations:
Register the servlet in the file.
This will deploy the servlet whenever the WebLogic server is started (or restarted).
You may also set ACLs for servlets deployed via the file. This is described in more detail in the Administrators Guide Setting WebLogic Properties.

Hot deploy the servlet from the WebLogic Console.
You may temporarily deploy or un-deploy a servlet from the WebLogic Console without stopping the WebLogic Server. See the Deployment Guide Using WebLogic Server hot deploy. To make this a permanent configuration, you must also register the servlet in the file, as described above.

Call the servlet via the ServletServlet.
The ServletServlet allows you to call any servlet class on the server, even if it is not registered or hot-deployed. This has security and performance disadvantages, but is useful while you are prototyping in the development phase. We recommend that you do not register the ServletServlet in a production system, thus preventing it from being used. See Using the ServletServlet.

Calling the servlet

To invoke a servlet from a browser you encode the servlet's URL into a page link, or an HTML form. However, you can test your HTTP servlet directly by typing the servlet URL into the URL location bar on a web browser, after the pattern:


For our example, running on a WebLogic Server at the default location, enter this URL:


Top of the page

Initializing a servlet

Usually, a servlet is initialized just before its service() method is called for the first time. Once it has been initialized, it is not initialized again for the duration of the WebLogic Server session, unless it is reloaded. You can have your servlet perform certain tasks at initialization by overriding the init() method.

Initializing a servlet at server startup

Alternatively, you can configure the WebLogic Server to initialize a servlet immediately after the server is started by adding the following lines to the file. You should use this feature if your servlet initialization has a noticable delay the first time it is called, or if your servlet needs to be active upon server startup.

# Here we register the myservletclass servlet class
# Configure the ServletStartup class to run MyServlet's init()
# method at startup

where myservletclass is the servlet you wish to initialize when you start the WebLogic Server, associated here with the virtual name MyServlet.

Here is how it works. The ServletStartup class is registered as a system.startupClass and is invoked immediately after the server is started. The ServletStartup class initializes the servlet with the virtual name specified as it is "server" parameter in its startupArgs.

To initialize more than one servlet at server startup time, you must register the ServletStartup class multiple times, using a different virtual name for each servlet. It is a good idea to follow a naming convention, such as that used above, so you do not clash virtual names and you can keep track of registrations.

Using initialization parameters

You can use the file to pass parameters to an HTTP servlet at its initialization. This allows you to customize the behavior of your servlet without having to recompile it. You associate the parameters with the servlet via its virtual name. For example, if the HelloWorldServlet is registered with the virtual name Hello, you can pass it initialization arguments using:


For more information on registering servlets, read the Administrators Guide, Setting WebLogic Properties.

You retrieve initialization parameters by calling the
getInitParameter(String name) method from the parent javax.servlet.GenericServlet class. When passed the name of the parameter, this method returns the parameter's value as a String. There is more on dealing with parameters later in this document.

Overriding the init() method

You can have your servlet perform actions at initialization time by overriding the init() method. It is important that you call the overridden init() method in the super class, so that it may parse the initialization arguments. It is generally a good idea to make this the first line in your implementation of the init() method.

This example reads initArgs that define a greeting, and a default name that can be customized from the file.

  String defaultGreeting;
  String defaultName;

  public void init(ServletConfig config) 
      throws ServletException {

    if ((defaultGreeting = getInitParameter("greeting")) 
        == null)
      defaultGreeting = "Hello";

    if ((defaultName = getInitParameter("person")) == null)
      defaultName = "World";

Here we store the values of each parameter in the class instance variables defaultGreeting and defaultName. Note that the code provides default values for these variables if the initArgs property is missing from the file by checking if the getInitParameter() method returns null.

You can change a few lines in the service() method to use these variables in the response. These are the relevant new lines of code:

  out.println(defaultGreeting + " " + defaultName + "!");

The full source code and instructions for compiling, installing, and trying out the HelloWorld2 example can be found in the WebLogic distribution examples/servlets directory. Don't forget to add the initArgs property to the servlet registration in the properties file:


After you restart the Weblogic Server, view the servlet in your browser with this URL:


Top of the page

Using the ServletServlet

While you are developing servlets, you may find the ServletServlet useful for prototyping. The ServletServlet allows you to invoke servlets that are not registered in the file.

To use the ServletServlet, you must register it in the file with the following line:


You may find it easier to use if you set a permissive ACL (access control list) on the ServletServlet using:


Now you can invoke the ServletServlet from an HTTP request to serve another servlet. You specify the indirected servlet by its full package name, given as the PATH_INFO to the ServletServlet. The PATH_INFO is the remainder of the URL used to reference the servlet. For instance, to invoke the HelloWorldServlet from the ServletServlet, you would use (entered on one line):


The ServletServlet parses the PATH_INFO, and attempts to match it to a given class in the system CLASSPATH of the WebLogic Server or in the servlet classpath, where the slash ("/") is interpreted as a dot (".").

In this example, the class examples.servlets.HelloWorldServlet is called.

If a class does not match the full PATH_INFO name, we try to match a class to the next least specific classname by truncating the last "/xxxx" from the PATH_INFO, and so on until a matching class name is found. The surplus PATH_INFO is passed on in turn to the matching class. If no matching class is found, a server error is reported.

Warning: Each time the ServletServlet is used to invoke a servlet, it instantiates a new servlet object. All instance variables shall be new, and the init() method is called every time the servlet is called to service a request. Also note that it is bad practice to rely on class scope variables since there is no guarantee that they shall be accessible in other invocations.

Note also that once the servlet class has been loaded, it is not loaded again when subsequent servlet objects are instantiated. If you want WebLogic to use your latest servlet class files during runtime, you must use the servlet classpath, described in the next section.

When to use the ServletServlet

In some special cases, you may need to use the ServletServlet as the mechanism for delivering servlets in a production release site. However, be aware that using the ServletServlet has the following disadvantages:

  • The ServletServlet does not administer security access control over the servlets is serves. Users with permission to invoke the ServletServlet may use it to invoke any servlet on the host, including unregistered servlets. This counteracts any ACLs you have on other servlets in your system, and poses a security risk. You may also invoke a specific servlet to serve types of files that should otherwise be served by a more appropriate servlet.

    For example, if you register the ServletServlet under the virtual name servlets, you can use that virtual name to call any servlet class file. A URL request to

    will call upon the weblogic.FileServlet servlet class to serve the source code of index.jsp as a plain HTML file, perhaps exposing code you would prefer to keep confidential.

  • Each time the ServletServlet invokes a servlet, it instantiates a new servlet object. This may be a performance bottleneck on a busy site.

For these reasons, WebLogic does not recommend the use of the ServletServlet in a production system unless it is a special circumstance that explicitly requires it.

Top of the page

Using the servlet classpath

Servlet classes placed in the servlet classpath are dynamically reloaded when they are modified. The WebLogic Server can be configured to check for updates periodically, or whenever a class is invoked.

You can use the servlet classpath to re-deploy your HTTP servlets at runtime, as they are updated, without the need to restart the WebLogic Server. As of release 4.0, classes that are referenced by JSP or JHTML pages are also reloaded if located in the servlet classpath. Note that JSP and JHTML pages are always recompiled if modified -- however, the classes they use must be in the servlet classpath if you want them reloaded when they are modified.

To use the reload-on-modify feature, follow these steps:

  1. Place your HTTP servlet classes in a directory hierarchy that is outside of the system CLASSPATH. A standard directory for servlets exists in the default WebLogic installation at:
    You should place your servlet classes under this directory using the -d option in your servlet compile command. If you run the setEnv script provided in the root directory of the WebLogic installation, it will set up the environment variable SERVLET_CLASSES to point to this directory. You can use the variable in your compile command, such as:
     $  javac -d %SERVLET_CLASSES%

  2. By default, the servlet classpath is set to the directory referenced by %SERVLET_CLASSES% in the file. Search for this property and uncomment it if necessary:

    You can add multiple directories to the servlet classpath, just as you would for the Java system classpath, separated by semi-colons ";". Note that in the properties file, you use forward slashes "/" on all operating systems.

  3. Configure the WebLogic Server to periodically check for modified servlet classes by setting the following property in the file:

    where the server checks every x seconds for modified servlet classes. If x is set to zero, the servlet classes are checked every time they are invoked. If x is set to "-1", the servlet classes are never checked (effectively disabling the reload-on-modify feature).


Although it is recommended that you use the default %SERVLET_CLASSES% directory as your servlet classpath for all of your servlets, you can use other directories by adding them to the servlet classpath property.

The servlet classpath should never share directories with other classpaths used by the WebLogic Server. These include the Java system classpath, and the weblogic.class.path. The behavior is not defined if you duplicate classes in other classpaths and the servlet classpath, or point the servlet classpath to the other classpaths; you may find that the reload-on-modify feature will not work correctly, and if may be confusing to debug your code.

Servlets in the servlet classpath cannot contain native methods. The Java security model prevents class loaders other than the system class loader from loading classes that contain native code.

You can reference servlets in the servlet classpath from the ServletServlet. These servlets are also reloaded if modified, as is true for registered servlets.

Beware if you store a reference to one of your classes in an HTTP session, and that class is loaded from the servlet classpath. If your servlet is reloaded, you will recieve a ClassCastException when you retrieve the object from the HTTP session. See the notes on The dreaded ClassCastException for more details.

Top of the page

Providing an HTTP response

This section describes how your HTTP servlet provides a response to the client. All responses should be delivered via the HttpServletResponse object that is passed as a parameter to the service() method of your servlet.

Configuring the HttpServletResponse

There are several properties that you may set for a servlet, via the HttpServletResponse object, that translate into HTTP header information. At a minimum, you must set the content type using the setContentType() method, even before you obtain the output stream to which you write the page contents. For HTML pages, this should be set to "text/html". For example:


You can set header attributes using the setHeader() method. For dynamic responses, it is useful to set the "pragma" attribute to "no-cache", causing the browser to always reload the page and ensuring the data is current.

 res.setHeader("Pragma", "no-cache"); 

If you use htmlKona to compose the servlet page, automatic default header details are provided.

Composing the visual page

Your servlet sends back an HTTP response via an output stream that you obtain from the HttpServletResponse object using the getWriter() or the getOutputStream() methods. You write the contents of the response to the output stream using the print() method. You should not close the output stream using the close() method and avoid flushing its contents. Not doing so allows the WebLogic Server to take advantage of persistent HTTP connections.

The response that your servlet sends back to the client must look like regular HTTP content. For the most part, this means you must send back the contents of an HTML page. Generating this content from Java code can be problematic since you'd like to tap into the creative tallent of your HTML authors yet you do not want to involve them with the complexities of writing the application logic. A better approach is provided by JavaServer Pages (JSP) which allows you to concentrate on the HTML design of your pages and embed your servlet logic right into the HTML, or encapsulate it in JavaBeans or custom JSP tags. Editors such as Dreamweaver are being developed to allow you to graphically create and edit JSP pages.

Optimizing the response

The WebLogic Server attempts to use HTTP persistent connections by default whenever possible. A persistent connection attempts to reuse the same HTTP TCP/IP connection for subsequent communications between the client and the server. Your application performance can be greatly enhanced since new connections need not be opened for immediate subsequent requests. This is a common requirement for HTML pages containing many in-line images, where each request image would otherwise require a TCP/IP connection.

You can configure the ammount of time that the WebLogic Server will keep an HTTP connection open with the KeepAlive properties as described in the Administrators Guide "Setting WebLogic Properties", under the section Configuring persistent HTTP connections.

You do not need to make special considerations for persistent connections in your application design. One point of note is that the WebLogic Server must know the length of the HTTP response in order to establish a persistent connection. A Content-Length property is automatically added to the HTTP response header. However, this requires that the response is buffered so that the length may be determined. WebLogic is unable to buffer the response if your servlets explicitly flush the ServletOutputStream, and hence is unable to use persistent connections in this case. For this reason, you should avoid explicitly flushing the HTTP resonse in your servlets.

You may decide that in some cases, it is better to flush the response early to display information in the client before the page has completed
-- for instance to display a banner advert whlist some time-consuming page content is calculated. Conversely, you may wish to increase the size of the buffer used by the servlet engine to accomodate a larger response before being flushed. You can manipulate the size of the response buffer using the related methods of the javax.servlet.ServletResponse interface.

Top of the page

Retrieving client input

The HTTP servlet API provides a clean interface for retrieving user input from web pages.

An HTTP request from a web browser can be accompanied by other information besides the URL, such as information about the client, the browser, cookies, and user query parameters. Query parameters used to carry user input from the browser, and are either appended to the URL address (the GET method) or included in the HTTP request header (the POST method).

HTTP servlets need not deal with these details; All of the information in the request is automatically parsed, regardless of the send method, and made accessible via the HttpServletRequest object.

You can arrange for query parameters to be sent from the client in a number of ways:

  • Encode the parameters directly into the URL of a link on a page. This approach uses the GET method for sending parameters. The parameters are appended to the URL after a "?" character. Multiple parameters are separated by a "&" character. Parameters are always specified in a name=value pair so ordering is not important. The following link might be placed in a web page, sending the parameter "color" with value "purple" to an HTTP servlet called ColorServlet (to be entered on one line):
      Click Here For Purple!</a>

  • Enter the URL with query parameters into the browser location by hand. This is equivalent to clicking on the link shown in the above example.

  • Query the user for input with an HTML form. The contents of each user input field on the form are sent as query parameters when the form's submit button is pressed. You specify the method that the form uses to send the query parameters (POST or GET) in the <FORM> tag using the METHOD="GET|POST" attribute.

Query parameters are always sent in name/value pairs, and are accessed through the HttpServletRequest object. You can obtain an Enumeration of all parameter names in the query, and fetch each parameter value using its parameter name. A parameter usually has only one value, but can hold an array of values. Parameter values are always interpreted as Strings, so you may need to cast them to a more appropriate type.

This sample from a service()method examines query parameter names and their values from a form. Note that request is the HttpServletRequest object.

  Enumeration params = request.getParameterNames();
  String paramName = null;
  String[] paramValues = null;

  while (params.hasMoreElements()) {
    paramName = (String) params.nextElement();
    paramValues = request.getParameterValues(paramName);
    System.out.println("\nParameter name is " + paramName);
    for (int i = 0; i < paramValues.length; i++) {
      System.out.println(", value " + i + " is " +

Useful methods of HttpServletRequest

Allows you to determine the request method, such as a GET or a POST.

Allows you to access the query string -- the remainder of the requested URL following the "?" character.

An example using query parameters

We can extend the HelloWorld2 servlet example to accept a username as a query parameter, to build in a more personal greeting. The source code for the example is included in the distribution in the examples\servlets directory. We have taken the service() method from the HellowWorld2 example and implemented it as shown here:

  public void service(HttpServletRequest req,
           HttpServletResponse res)
       throws IOException
    String name, paramName[];
    if ((paramName = req.getParameterValues("name")) 
        != null) {
      name = paramName[0];
    else {
      name = defaultName;

    // Set the content type first
    // Obtain a PrintWriter as an output stream
    PrintWriter out = res.getWriter();

    out.print("<html><head><title>" + 
                "Hello World!" + </title></head>");
    out.print(defaultGreeting + " " + name + "!");

Here we use the getParameterValues() method to retrieve the value of the name parameter from the HTTP query parameters. We retrieve these values in an array of type String. We expect a single value for this parameter, which we assign to the first element in the name array. If the parameter is not present in the query data, null is returned; in this case, we assign name to the default name that was read from the initArgs property by the init() method.

Compile and install the servlet example, then invoke it using the ServletServlet and the servlet classpath, using this URL in your browser (on one line):


We do not document how to use HTML in this document. If you need help with HTML forms, check out "The iDocs Guide to HTML".

Note: Your code should never assume that parameters are included in an HTTP request. Since the deprecation of the getParameter() method, you might be tempted to shorthand the getParameterValues() method by tagging an array subscript to the end. However, this method can return null if the parameter is not available, resulting in a NullPointerException.

  String myStr = res.getParameterValues("paramName")[0];
Instead, use..
  if ((String myStr[] = 
            res.getParameterValues("paramName"))!=null) {
    // Now you can use the myStr[0];
  else {
    // paramName was not in the query parameters!

Top of the page

Using session tracking from a servlet

Session tracking means that you can track a user's progress over multiple servlets or HTML pages, which by nature are stateless. A "session" is defined as a series of browser requests that come from the same client, and are often related, during a certain time period. Session tracking is important for tying together a series of browser requests -- think of these as pages -- that may have some meaning as a whole, such as a shopping cart application.

A history of session tracking

Before session tracking matured conceptually, developers tried to build state into their pages by stuffing information into hidden fields on a page or embedding user choices into URLs used in links with a long string of appended characters. You can see good examples of this at most search engine sites, many of which still depend on CGI. These sites track user choices with URL parameter name/value pairs that are appended to the URL, after the reserved HTTP character "?". This can result in a very long URL that the CGI script must carefully parse and manage. You can't pass this information from session to session. Once you lose control over the URL -- that is, once the user leaves one of your pages -- the user information is lost forever.

Later, Netscape introduced browser cookies, which can be used to store user related information on the client for each server. At last, servers had a place to store information about a user's preferences, but some browsers still do not fully support this, and some people prefer to turn the 'cookie' options off on their browsers. Another factor that should be considered is that most browsers limit the amount of data that can be stored with a cookie.

The HTTP servlet specification defines a solution that allows the server to store user details in a tangible place on the server, and protects your code from the complexities of tracking sessions. Your servlets may use an HttpSession object to track a user's input over the span of a single session and share session details between multiple servlets.

Tracking a session with the HttpSession object

Interface javax.servlet.http.HttpSession

Under the Java Servlet API, which WebLogic implements and supports, each servlet can access a server-side session via its HttpSession object. An HttpSession object is your servlet's view of the session. You can access an HttpSession in the servlet's service() method using the HttpServletRequest object, depicted as the variable request here:

  HttpSession session = request.getSession(true);

An HttpSession object is created if one doesn't already exist for that client when the request.getSession(true) method is called with the argument true. The session object lives on the WebLogic Server for the lifetime of the session, during which it accumulates information related to that client. Your servlet adds to or removes information from the session object as necessary. A session is associated with a particular client, although that user may not be identified as anything other than anonymous. Each time the client visits your servlet, the same associated HttpSession object is retrieved when the getSession() method is called.

For more details on the methods supported by the HttpSession refer to the HttpServlet API.

This example service() method counts how many times you have hit the servlet in a session.

public void service(HttpServletRequest request, 
                    HttpServletResponse, response) 
            throws IOException
  // Get the session and the counter param attribute
  HttpSession session = request.getSession (true);
  Integer ival = (Integer) 
  if (ival == null) // Initialize the counter
    ival = new Integer (1);
  else // Increment the counter
    ival = new Integer (ival.intValue () + 1);
  // Set the new attribute value in the session
  session.setAttribute("simplesession.counter", ival);
  // Output the HTML page
  out.print("<center> You have hit this page ");
  out.print(ival + " times!");

The lifetime of a session

A session is intended for tracking a user's selections over a series of pages in a single transaction, such as browsing for an item, adding it to a shopping cart, then billing via credit card. A session is transient, and its lifetime ends when:

  • A user leaves your site and does not accept cookies
  • A user quits the browser
  • The session is timed out due to no activity
  • The session is completed and invalidated by the servlet
  • The user logs out and is invalidated by the servlet

For more persistent long term storage of data your servlet should write details to a database using JDBC or EJB and associate the client with this data via a long lived cookie and/or username and password. Although we describe here that sessions use cookies and persistence internally, you should not use sessions as a general mechanism for storing data about a user.

How session tracking works

How does the WebLogic Server know which session is associated with each client? When an HttpSession is created in a servlet it is associated with a unique ID. The browser must provide this session ID with its request in order for the server to find the session data again. The server attempts to achieve this by setting a cookie on the client. Each time the client sends a request to the server from then onwards, it includes the cookie containing the ID. The server automatically parses the cookie, and supplies the session data when your servlet calls the getSession() method.

Note:  The webserver name is embedded in a cookie so that the browser knows to return the cookie on subsequent requests to the same server. In a web application that includes both HTTP and HTTPS pages on WebLogic Server, the server name includes the port number (for example "https://localhost:7002"). Netscape browsers interpret server names with different port numbers as different servers. This means that a user with a Netscape browser gets two sessions: one for HTTP pages and one for HTTPS pages. To prevent this, set the weblogic.httpd.session.cookie.domain property to the domain name of the server so that cookies do not contain the port number.

If the client does not accept cookies, the only alternative is to encode the ID into the URL links in the pages sent back to the client. For this reason, you should always use the encodeURL() method when you include URLs in your servlet response. See Using URL rewriting later in this document. The WebLogic Server knows whether or not the browser accepts cookies and will not unnecessarily encode URLs, so you should make a habit of always using this method. WebLogic automatically parses the session ID from an encoded URL, and retrieves the correct session data when you call the getSession() method. This means no disruption to your servlet code regardless of the method used.

Detecting the start of a session

After you have obtained a session using the getSession(true) method, you can tell if the session has just been created by calling the HttpSession.isNew() method. If this method returns true, then the client did not indicate that it already has a valid session, and at this point the client is unaware of the new session, until a reply is posted back from the server.

You should design your application to accommodate each of these conditions in a way that suits your business logic. For example, your application might redirect the client's URL to a login/password page if you determine that the session hasn't yet started. Here is a code example:

  HttpSession session = request.getSession(true);
  if (session.isNew()) {

At the login page, you should offer the ability to login to the system, or create a new account.

Setting and getting session name/value attributes

You store data in an HttpSession object using name/value pairs. Use these methods from the HttpSession interface:


Here is a code snippet that shows how to get all of the existing name/value pairs:

  Enumeration sessionNames = session.getAttributeNames();
  String sessionName = null;
  Object sessionValue = null;

  whlie (sessionNames.hasMoreElements()) {
    sessionName = (String)sessionNames.nextElement();
    sessionValue = session.getAttribute(sessionName);
    System.out.println("Session name is " + sessionName +
                ", value is " + sessionValue);

To add or overwrite a named attribute, you use the setAttribute() method. To remove a named attribute altogether, use the removeAttribute() method.

Note: You can add any Java descendant of Object as a session attribute and associate it with a name. However, if you are using session persistence, your attribute 'value' objects must implement

Working with the ClassCastException

You will invariably encounter this mysterious exception at some point when you start developing HTTP sessions seriously. Here is why it happens...

  1. You store a reference to a custom class in an HTTP session. Let's call your custom class myFoo.
  2. Whilst in mid-session, you change your servlet (or JSP or JHTML), causing it to be reloaded. In fact, it is necessary for it to be reloaded by a completely new class loader, and the old class loader that had previously loaded it must be discarded.
  3. Since your custom class myFoo is also located under the servlet classpath, it too is reloaded by the new class loader.
  4. Now, when you retrieve myFoo from the HTTP session, you cast it to the expected type, but you recieve a ClassCastException. The exception is thrown even if class myFoo has not changed. Since it has been loaded by a different class loader, it is regarded by the JVM as incompatible.
Note that if you are using session persistence, the class contents must be serialized, hence you will not see this issue.

Here are some suggested work arounds to this problem:

  • Do not place your class myFoo in the servlet classpath. Instead, place it in the system classpath or the weblogic.class.path that are accessible by the WebLogic Server; it will not be reloaded when the servlet is modified. This solution has the drawback that you can't prototype the myFoo class, since you must restart the server in order to reload the class after it is modified.

  • If you need to prototype the class, you could write a wrapper method within it to store and retrieve its contents to and from the session. You do not access the class directly from the session, but instead call it is wrapper methods to store or populate it is contents from the session. So long as you use standard Java class types to store the class contents, they will not be reloaded when the servlet is reloaded. This approach has performance drawbacks since your wrapper methods would need to set or get multiple name=value pairs for each of your class's attributes.

  • Another workaround is to catch the ClassCastException, and replace the old class that is stored in the session with a newly instantiated class, or remove it from the session. Unfortunately, you will lose the session data that was previously stored in the class, so you should write your application to handle this scenario. This is the easiest solution to the problem -- remember that you should not be storing critical information in an HTTP session, but rather storing it in a database.
The above exception will generally occur whilst you are developing your servlets, and should not be an issue in a stable production system. If you are upgrading your system online, we advise that you warn your customer base.

Logging out and ending a session

If your application deals with sensitive information you might consider offering the ability to log out of the session. This is a common feature with shopping carts and internet email accounts. When the same browser returns to the service, the user must log back into the system. To achieve this, you can invalidate the current session by calling:


You should not reference an invalidated session after you have called this method. If you do, an IllegalStateException will be thrown. The next time a user visits your servlet from the same browser, the session data will be missing, and a new session will be created when the getSession(true) method is called, at which point, you might send the user to the login page again.

Configuring session tracking

For details on configuring session tracking, see the Administrators Guide, Setting up session management.

Using URL rewriting

In some situations, a browser may not accept cookies, which makes session tracking using cookies impossible. URL rewriting is a work-around to this scenario that can be substituted automatically when the WebLogic Server detects that the browser does not accept cookies. URL rewriting involves encoding the session ID into the hyper-links on the web pages that your servlet sends back to the browser. When the user subsequently clicks these links, the WebLogic Server extracts the ID from the URL address and finds the appropriate HttpSession when your servlet calls the getSession() method.

To enable URL rewriting in the WebLogic Server, you must set the following property in your file:


There are some general guidelines for how your code should handle URLs in order to support URL rewriting. You should avoid writing a URL straight to the output stream, as shown here:

  out.println("<a href=\"/myshop/catalog.jsp\">catalog</a>");

Rather, you should use the HttpServletResponse.encodeURL() method instead. Calling this method does two things; it both determines if the URL needs to be rewritten, and if so, it rewrites it, by including the session ID in the URL.

In addition to URLs that are returned as a response to the WebLogic Server, you will also need to encode URLs that send redirects, for example:

  if (session.isNew()) {

The WebLogic Server will use URL rewriting when a session is new, even if the browser does accept cookies, since the server cannot tell if a browser does accept cookies or not in the first visit of a session.

Your servlet may determine if a given session was determined from a cookie by checking the boolean returned from the HttpServletRequest.isRequestedSessionIdFromCookie() method. Your application may wish to respond appropriately, or simply rely on URL rewriting by the WebLogic Server.

Making sessions persistent

The WebLogic Server can be set up to record session data in a persistent store. If using session persistence, you can expect the following characteristics:

  • Good failover, since sessions are saved across server down-time.

  • Better load balancing, since any server can better handle requests for any number of sessions, and use caching to optimize performance. See the cacheEntries property above.

  • Sessions can be shared across clustered WebLogic Servers. Note that session persistence is no longer a requirement in a WebLogic Cluster. Instead, you may use in-memory replication of state.

  • For customers who want the highest in servlet session persistence, JDBC-based persistence is the best choice. For customers who wish to sacrifice some amount of session persistence in favor of drastically better performance, in-memory replication is the appropriate choice. JDBC-based persistence is noticeably slower than in-memory replication. In some cases, in-memory replication has outperformed JDBC-based persistence for servlet sessions by a factor of eight.

  • It is legal to put any kind of Java object into a session, but for file, JDBC and in-memory replication we only replicate objects that are

How not to use sessions...

Session persistence is not used for storing long term data between sessions. That is, you should not rely on a session still being active when a client returns to a site at some later date. Instead, your application should record long-term or important information in a database.

Sessions are not a convenience wrapper around cookies. You should not attempt to store long term or limited term client-data in a session. Instead, your application should create and set its own cookies on the browser. Examples of this might include an auto-login feature where the cookie might live for a long period, or an auto-logout feature where the cookie might expire after a short period of time. Here, you should not attempt to use HTTP sessions, but instead write your own application specific logic.

Use Serializable attribute value

When you use persistent sessions, all attribute 'value' objects that you add to the session must implement For more details on writing serializable classes, refer to the online java tutorial about serializable objects. If you add your own serializable classes to a persistent session, be careful that each instance variable of your class is also serializable. Otherwise, you can declare it as transient, and WebLogic will not attempt to save that variable to persistent storage. One common example of an instance variable that must be made transient is the HttpSession object.

Configuring session persistence

For details on setting up persistent sessions, see the Administrators Guide Setting up WebLogic as an HTTP server: Configuring session persistence.

Top of the page

Using cookies in a servlet


What is a cookie?

A cookie a piece of information that the server asks the client browser to save locally on the user's disk. Each time the browser visits the same server, it sends all cookies relevant to that server with the HTTP request. Cookies are useful for identifying clients as they return to the server.

Each cookie has a name and a value. A browser that supports cookies generally allows each server domain to store up to 20 cookies at up to 4k per cookie.

Setting cookies in an HTTP servlet

To set a cookie on a browser, you must create the cookie, give it a value, and add it to the HttpServletResponse that is the second parameter in your servlet's 'service' method. The following code illustrates this:

  Cookie myCookie = new Cookie("ChocolateChip", "100");

This adds a cookie called "ChocolateChip" with a value of "100" to the browser client when the response is sent. The expiration of the cookie is set to the biggest possible value, which effectively makes the cookie last forever. Since cookies only accept string-type values, you should cast to and from the desired type that you wish to store in the cookie. A common practice is to use the handle ID of an EJB instance for the cookie value and store the user's details in the EJB.

Retrieving cookies in an HTTP servlet

You can retrieve a cookie object from the HttpServletRequest that is passed to your servlet as an argument to the service() method. The cookie itself is presented as a javax.servlet.http.Cookie object.

In your servlet code, you can retrieve all the cookies sent from the browser by calling:

  Cookie[] cookies = request.getCookies();

This method returns an array of all cookies sent from the browser, or null if no cookies were sent by the browser. Your servlet will need to process the array in order to find the correct named cookie. You can get the name of a cookie using the Cookie.getName() method. Note that it is possible to have more that one cookie with the same name, but different 'path attributes'. If your servlets set multiple cookies with the same names, but different 'path attributes' you will also need to compare this using the Cookie.getPath() method. The following code illustrates how to access the details of a cookie sent from the browser. It assumes that all cookies sent to this server will have unique names, and that we are looking for a cookie called "ChocolateChip" that we may have previously set in a browser client:

  Cookie[] cookies = request.getCookies();
  boolean cookieFound = false;

  for(int i=0; i < cookies.length; i++) {
    thisCookie = cookies[i];
    if (thisCookie.getName().equals("ChocolateChip")) {
      cookieFound = true;

  if (cookieFound) {
    // We found the cookie! Now get its value
    int cookieOrder = String.parseInt(thisCookie.getValue());

For more details on cookies, see The Cookie API and The Java Tutorial: Using Cookies.

Using cookies that will be transmitted by both HTTP and HTTPS

Because HTTP and HTTPS requests are sent to different ports, some browsers may not include the cookie sent in an HTTP request with a subsequent HTTPS request (or vice-versa). This may cause new sessions to be created when servlet requests alternate between HTTP and HTTPS. To ensure that all cookies set by a specific domain are sent to the server every time a request in a session is made, set the following property in the file for the server (or cluster) that hosts the servlet:

This property will instruct the browser to include the proper cookie(s) for all requests to hosts in the domain specified in place of "". For more information on this property or configuring session cookies, see Setting up WebLogic as an HTTP Server.

Your application security and cookies

Using cookies that enable automatic account access on a machine is convenient, but can be undesirable from a security perspective. Consider the following rules of thumb when designing your application.
  • Your servlet shouldn't assume that a cookie is always correct for a user. Sometimes, machines are shared, or the same user may wish to access a different account.

  • Allow your users to make a choice about leaving cookies on the server. On shared machines, a user may not wish to leave an automatic login for their account. Don't assume that a user knows what a cookie is; instead ask a question like:

    Auto login from this computer?

  • Always ask for a password to log on for sensitive data -- unless the user requests otherwise -- you can store this preference, and their password, in their session data. The session cookie should be configured to expire when the user quits the browser.

Top of the page

Using WebLogic services from an HTTP servlet


If you write a browser client, your client has access to many of the rich features of WebLogic in spite of the fact that your client isn't a Java client application (for more on writing Java client applications, see Writing a WebLogic client application).

When you write server-side Java, you can access the WebLogic services such as factory methods -- like JNDI, RMI, EJB, JDBC connections, etc. -- as a WebLogic server-side process, rather than a Java client application. You can do this with a static method from the weblogic.common.T3Services class, as shown here:

 T3ServicesDef t3s =

Once you have a T3ServicesDef object, you can call any of the factory methods from that interface to get access to WebLogic services. For example, here is how you might submit an event registration from a servlet (where request is the HttpServletRequest object):

  ParamSet eventParameters = new ParamSet();
  String name;
  Enumeration names = request.getHeaderNames();
  while (names.hasMoreElements()) {
    name = (String)names.nextElement();
    try {
      eventParameters.setParam(name, request.getHeader(name));
    catch (Exception e) {;}

  EventMessageDef ev = T3Services.getT3Services().events()
    .getEventMessage("HTTPWATCH", eventParameters);


Here is another example of how you might use WebLogic services from a servlet, through the log() and config() services:

  T3ServicesDef t3s = T3Services.getT3Services();
  String consoleEnabled =
  String logmsg = "Console enabled was set to " +
                  consoleEnabled + " at " +
                  new java.util.Date();
  LogServicesDef logger = t3s.log();

Top of the page

Using connection pools with server-side Java

WebLogic supports the use of JDBC connection pools from server-side Java classes, including servlets. We provide two server-side JDBC drivers: one for routine use for most database operations, and another for transactional operations such as Enterprise JavaBeans (EJB). Because WebLogic's servlet persistence is EJB-based, you will also use a connection pool as part of your configuration setup for persistence.

A connection pool is a named group of identical JDBC connections to a database that are created when the connection pool is registered, usually when starting up WebLogic Server. Your servlets "borrow" a connection from the pool, use it, then return it to the pool by closing it. This is far more efficient than creating a new connection for each client each time they need to access the database. Another advantage is that you do not need to hard-code details about the database your application uses.

WebLogic supplies special JDBC "pool" drivers that give server-side Java access to connection pools that are registered on the same WebLogic Server.

WebLogic's JDBC pool drivers include:

  • Pool driver for most server-side operations:

    Driver URL: jdbc:weblogic:pool
    Driver package name: weblogic.jdbc.pool.Driver

    This driver, which is most often used with servlets, is documented here.

  • JTS pool driver:

    Driver URL: jdbc:weblogic:jts
    Driver package name: weblogic.jdbc.jts.Driver

    For more about using the JTS-based JDBC pool driver for EJBeans, read The WebLogic EJB Environment.

Setting up the registration for a connection pool

To configure a connection pool, you add a registration for it to the file. The connection pool is created each time you start the WebLogic Server and exists until the server is shut down. There are more details on setting properties for JDBC connection pools in the Administrators Guide, Setting WebLogic properties.

You configure most aspects of the connection pool from the properties file, such as:

  • Username and password ACLs for connecting to your database
  • The name of the connection pool
  • The size of the connection pool, and how it should grow on demand

It is easy to use a connection from the pool in your servlet code. Your servlet code is abstracted from administration details of the pool. You can configure the pool, or even point the named connection pool at a completely different database, all without changing or recompiling any code.

Here is an example of a registration from a file for a connection pool named sales and its ACL (access control list). This pool uses WebLogic jDriver for Oracle to connect to an Oracle database; the WebLogic jDriver for Oracle requires a set of OCI client libraries on the WebLogic Server host.



If you do not set an ACL for a connection pool, or one is not provided by the context of your code (such as the properties of a t3 Client), it defaults to "everyone" -- that means any user can grab a connection. If you want to restrict access to the pool to certain users, you must set up an access control list, as shown above. Then you set up a username and password for each application user with a java.util.Properties object in your code. Note that this username and password is the valid username and password that matches a user registered in the file, and not a database username and password. At runtime, the username and password supplied by the application is checked against the list of T3Users established in the access control list for the connection pool.

Each of the users in the access control list must be registered and have been assigned a password in the file, as shown here:


Using a connection pool in your servlet

Here is a simple servlet that selects all of the records from a database table using dbKona, and displays them using htmlKona.

First we load the pool driver and cast it to java.sql.Driver. The full pathname of the driver is weblogic.jdbc.pool.Driver.

  Driver myDriver = 
  (Driver) Class.forName("weblogic.jdbc.pool.Driver").newInstance();

Then, we create the connection with the URL for the driver, plus (optionally) the name of the registered connection pool. The URL of the pool driver is jdbc:weblogic:pool.

You can identify the pool in one of two ways:

  • You can add the name of the pool to the end of the URL. In that case you will not need a Properties object unless you are setting a username and password for use of a connection from the pool.

  • You can specify the name of the pool in a java.util.Properties object using the key connectionPoolID.

Here is an illustration that obtains a connection from a pool, using a URL that incorporates the name of the connection pool. The second argument to this method is a java.util.Properties object, which we pass here as null. If you do not set the username and password for a T3User in a Properties object, the username defaults to "guest". If you are using an ACL, it must contain the user "guest", for this default connection to be successful.

  Connection conn =
     myDriver.connect("jdbc:weblogic:pool:sales", null);

This code snippet illustrates how to obtain a connection using a Properties object to set the name of the connection pool to "myConnectionPool" :

  Properties props = new Properties();
  props.put("connectionPoolID", "myConnectionPool");
  Connection conn =
    myDriver.connect("jdbc:weblogic:pool", props);

Note that the Driver.connect() method is used here instead of DriverManger.getConnection(). Although you may use DriverManger.getConnection() to obtain a database connection, BEA recommends that you use Driver.connect() because this method is not synchronized and provides better performance.

Note that the Connection returned by connect() is an instance of weblogic.jdbc.pool.Connection.

You must use the close() method on the Connection object, when you have finished with your JDBC work, so that the connection is properly returned to the pool. A good coding practice is to create the connection in a try block and then close the connection in a finally block, to make sure the connection is closed in all cases.

Here is the entire servlet. This servlet displays the contents of the "emp" database table in an HTML table on a web page.

package examples.jdbc.pool;

import java.sql.*;
import java.util.Properties
import javax.servlet.*;
import javax.servlet.http.*;
import weblogic.db.jdbc.*;
import weblogic.html.*;

public class simpleselect extends HttpServlet {

  public synchronized void service(HttpServletRequest req,
                                   HttpServletResponse res)
    throws IOException
    Connection conn = null;
    try {

      Properties props = Properties();
      props.set("user",            "joeuser");
      props.set("password",        "dP3m*spQc!");

      Driver myDriver = 
        (Driver) Class.forName("weblogic.jdbc.pool.Driver").newInstance();
      conn =  myDriver.connect("jdbc:weblogic:pool:sales",props);


      TableDataSet ds = new TableDataSet(conn, "emp");
      TableElement tbl = new TableElement(ds);

      ServletPage hp = new ServletPage("Simple select");


    catch (Exception e) {
      ServletPage hp = 
        new ServletPage("An Exception occurred");
      ByteArrayOutputStream ostr = 
        new ByteArrayOutputStream();
      e.printStackTrace(new PrintStream(ostr));
          HeadingElement("An Exception occurred:", 2))
        .addElement(new LiteralElement(ostr.toString()));
    finally {

Note that the htmlKona class TableElement automatically generates a formatted html table from a TableDataSet.

This example may be compiled and run from the distribution directory examples/jdbc/pool.

Top of the page

Threading issues in HTTP servlets

When designing a servlet, you must consider how the servlet is invoked by the WebLogic Server under high load. It is inevitable that more than one client will hit your servlet simultaneously. You must write your servlet code to guard against sharing violations on shared resources or instance variables. The following tips will help you to design around this issue.

As of the WebLogic 4.5 release, the SingleThreadModel is supported as specified in the JSDK2.1. An instance of a class that implements the SingleThreadModel is guaranteed not to be invoked by multiple threads simultaneously. Multiple instances of a SingleThreadModel servlet are used to service simultaneous requests, each running in a single thread.

When designing your servlet, you should take care over shared resources outside of the servlet class such as file and database access. The multiple servlet instances used are identical, and may use exactly the same resources, so there are still synchronization and sharing issues that must be resolved, even if you do implement the SingleThreadModel. For instance, the SurveyServlet example (distributed with the JSDK) writes to a file - the SingleThreadModel will not protect against multiple servlet instances writing to the same file.

WebLogic recommends that shared resource issues are handled by the developer on an individual servlet basis. The following guidelines may be helpful:

  • Wherever possible, synchronization should be avoided, since it will cause subsequent servlet requests to bottle-neck until the current thread has completed.
  • Variables that are specific to each servlet request should be defined within the scope of the service methods. Local scope variables are stored on the stack, so are not shared by multiple threads running within the same method, avoiding the need to be synchronized.
  • Access to external resources should be synchronized on a Class level, or encapsulated in a transaction.

Top of the page

Passing the request to another HTTP servlet

Sometimes, when a servlet is requested, it may conditionally pass the request on to be handled by another servlet. This is sometimes refered to as "Servlet Chaining". A common example might be where the application requires that the user is logged in before performing a certain function. If the servlet is requested and the user is not logged in, the request is redirected to a login servlet. Some token might be saved in the HTTP session to note where the original request was made so that control can return here after a successful login.

A servlet passed a request onto another servlet via the RequestDispatcher. This avoids the need to send an HTTP-redirect response back to the client. The RequestDispatcher correctly passes the HTTP request onto the HTTP servlet it represents. To obtain the appropriate RequestDispatcher for a particular HTTP servlet, use one of the following methods from the ServletContext, which your servlet may access via the call:

  ServletContext sc = getServletConfig().getServletContext();
Your servlet may look up the RequestDispatcher for a servlet using one of these methods:
ServletContext.getRequestDispatcher(String path)
Where path is the URL that the requested servlet handles for this servlet context. For example, a path of "/login" might obtain a RequestDispatcher for a servlet registered to handler requests to "/login". The returned RequestDispatcher can then be used to forward the request to the login servlet.

ServletContext.getNamedDispatcher(String name)
Where name is the name assigned to the servlet in a Web Application deployment descriptor. You must deploy your servlets in a Web Application to use this method. For more details, see the Developers Guide "Writing a Web Application". This method has the advantage that the servlet URL is separated from the servlet name in your servlet code. The Web Application deployment descriptor also makes this distinction between servlets and servlet-mappings.

The RequestDispatcher has two methods that allow you to either forward the entire servlet request to a servlet, or include the output from another servlet in your servlet's response. These are discussed in the next two sections.

You may obtain a RequestDispatcher for any HTTP resource within a context, including HTTP Servlets, JSP pages, or plain HTML pages. Simply request the appropriate URL path for the resource in the getRequestDispatcher() method.

Forwarding a request

Once you have the correct RequestDispatcher, your servlet forwards a request via the RequestDispatcher.forward() method, passing the HTTPServletRequest and HTTPServletResponse as arguments.

It must not have attempted to write any previous output to the response. If the servlet has retrieved the ServletOutputStream or the PrintWriter for the response prior to forwarding the request, an IllegalStateException will be thrown.

All other output from the original servlet is ignored after the request has been forwarded.

Including a request

Your servlet can include the output from another resource using the RequestDispatcher.include() method, passing the HTTPServletRequest and HTTPServletResponse as arguments.

Any attempt to set the response status code, or any HTTP header information from the included servlet response is ignored. In effect, you may use this method to achive a servler-side-include of another HTTP resource from your servlet code.

Top of the page

Using server-side includes

Note: We recommend that you use JavaServer Pages and the JSP include directive to achive the same effect as SSI in the WebLogic Server. You can write plain HTML into a JSP page without using the more sophisticated features of JSP. JSP allows you to include data in a JSP page in two ways; this is described concisely in section 2.7 of the JSP specification. For more details, please see the Developers Guide Using WebLogic JSP.

WebLogic supports a subset of server-side includes (SHTML files) using an internal WebLogic servlet called the ServerSideIncludeServlet. Server-side includes allow you to include templates in your HTML pages. You define the templates in other files, and may include them in many other web pages to make maintenance easier. For example, you might define a header and a footer for all of your web pages. When you wish to change the headers, you can make the change in the single template file to take effect on all other pages that include the template file.

You may also invoke a servlet using the servlet tag to generate dynamic content within your web page, although for new projects we recommend you consider using JSP.

HTML files containing server-side includes traditionally have an .shtml extension. The ServerSideIncludeServlet is registered in the file to handle all requests for files with this extension. Like the FileServlet, the ServerSideIncludeServlet searches for files below the document root. For details on setting up the ServerSideIncludeServlet, see Using server-side includes in the Administrators Guide, "Setting up WebLogic as an HTTP server".

WebLogic supports two SSI directives:

  • The #include directive allows you to incorporate another file within this page. The server embeds the included file in the page that is sent back to the browser.
    <!--#include virtual=filename-->
    Note: WebLogic only implements the virtual tag from the NCSA specification, where virtual gives a file that is relative to the document root. Currently, the included files are not interpreted for sub-ServerSideInclude directives.

  • The <servlet> tag will cause the WebLogic Server to invoke a named servlet when the page is requested. The servlet might perform a specific task, or provide some dynamic content in the page.

    You must set the name attribute to the virtual name of the registered servlet (for more about registering servlets for use with WebLogic, read Setting up WebLogic as an HTTP server).

    <servlet name=servletVirtualName>
      <param name=paramName value=paramValue>
    Note: Due to limitations in the HTTP specification, your embedded servlet may not set header information in the page response. This includes setting cookie data to be sent back to the client.

Top of the page

Clustering servlets

WebLogic supports clustering servlet services across a WebLogic Cluster. Clustering provides failover and load balancing to increase the performance and reliability of your website. Provided that you use HTTP sessions as they were intended, there are no servlet implementation differences that you must consider.

For details on setting up a WebLogic Cluster, including using JDBC session persistence and in-memory state replication with a proxy server, see the Administrator Guide Setting up a WebLogic Cluster: Setting up HTTP servlets.

Top of the page

Setting up ACLs for servlets in the WebLogic realm


WebLogic controls access to internal resources like HTTP servlets through Access Control Lists (ACLs) set up in the WebLogic Realm. Entries for ACLs in the WebLogic Realm are listed as properties in the file. (For more info on the properties file, see the WebLogic Administrators Guide, Setting WebLogic properties.

You can set the execute permission for an HTTP servlet by adding a property to the properties file. The ACL named weblogic.servlet controls access to all registered servlets. Setting the execute permission for the weblogic.servlet ACL to everyone allows anyone to execute any servlet without entering a password, except those servlets with more specific ACLs.

To limit access to an individual servlet, you must set its execute permission to a list of one or more users. For example, setting the weblogic.servlet.AdminProperties ACL to the user system would allow general access (without a password) to all registered servlets except AdminProperties; only the system user would be able to execute that servlet. (The user "system" always has access to all servlets, but in this case setting the permission for this servlet effectively denies permission to everyone else.) Here is an example:


Setting ACLs for groups of servlets

You can organize servlets into groups using a delimited virtual name, then set a single ACL for those virtual names. In this example, we register all administration servlets against the virtual name pattern Admin.xxxx. We set one ACL to allow access to all servlets, and another ACL that limits access to all servlets beginning with the virtual name pattern Admin. The second ACL is more specific than the first, so it effectively limits administration abilities to the system user.

  # Allow anyone to execute registered servlets
  # Allow only 'system' to execute any 'Admin' servlets

The following property has been deprecated:

Its equivalent property is:

It is recommended that you upgrade your properties file immediately, since we cannot guarantee how long deprecated properties will be supported.

Top of the page

Change history

Release 3.1.0

With this release, WebLogic support for the Java Servlet API is now in full compliance with release 2.0 of the JSDK. This is the same interface provided by Java Web Server 1.1.1 (shipped as the packages in javax.servlet.http.* in JDK 1.2). In addition, the webserver support in WebLogic has been made to more closely track standard webserver configuration and management.

There are many property changes associated with this release that will, over the long term, greatly simplify the management of applets, servlets, JSP or JHTML pages, static HTML, and all other associated MIME types in the WebLogic environment. Here is a summary:

You will now register six servlets:

  1. weblogic.servlet.jhtmlc.PageCompileServlet for automatic page compilation of JHTML files, located in the document root. The document root is established by setting weblogic.httpd.documentRoot to a relative or absolute path. Relative paths will be mapped below the default setting for this property, which is weblogic/myserver/public_html.

    Example property:

    Example URL:

  2. weblogic.servlet.ServerSideIncludeServlet for serving SHTML pages (server-side includes) located in the document root.

    Example property:

    Example URL:

  3. weblogic.servlet.FileServlet serves standard HTML files and other MIME resources located in the document root. Note that this registration has changed: There is now only one initArg for this servlet, defaultFilename. The initArg dochome has been superseded by the more flexible document root property. Although dochome is still supported for backwards compatibility, if document root is set, the dochome argument will be ignored. If the requested file isn't found, FileServlet serves the file set as the defaultFilename.

    Example property:

    Example URL:

  4. weblogic.servlet.ServletServlet for serving servlets located in the servlet classpath. The servlet classpath is established by setting weblogic.httpd.servlet.classpath to an absolute path that is not located in the system CLASSPATH. Classes located in this path do not need to be registered in the properties file. You can determine how often WebLogic checks to see if there is a newer version to load by setting the property weblogic.httpd.servlet.reloadCheckSecs to a positive number; setting this property to "-1" means WebLogic will never reload the class. "Reload" includes all dependent classes that have been modified since the last reload.

    Example property:

    Example URL:

  5. weblogic.servlet.ClasspathServlet for serving servlets and other Java class files located in the system CLASSPATH. You do not need to register servlets or other classes to be loaded with this servlet.

    Example property:

    Example URL:

  6. weblogic.t3.srvr.ProxyServlet is for proxying requests to another HTTP server and works as it always has.

Added performance enhancement for better buffering of the servlet output stream.

Added safeguards to prevent files ending with "/" or "." from being improperly served.

Changed implementation of HttpServletRequest.getServletPath() so that it returns null when appropriate.

Changed exception handling in getCookies() such that one bad Cookie will not spoil those that follow, in response to feedback that cookie parsing in WebLogic is to strict; it is very compliant with the spec, but apparently a lot of other web-servers and browsers aren't.

Fixed problem with dropping a slash in calls to HttpUtils.getRequestURL().

Calls to flush the servlet output stream now actually do so.

Fixed backward compatibility problem with FileServlet so that older-style dochome is not ignored.

Fixed problem in keeping privileged status long enough during WebLogic startup on UNIX to complete bind to a port lower than 1025.

Fixed a problem with the proxy servlet. A request that comes in as HTTPS must be proxied as HTTP, since there is no way to proxy SSL and return to a client as an authenticated server.

Improved performance in HTTP logging. Note that all HTTP log messages are now written exclusively to the HTTP log (default name is access.log) when HTTP logging is enabled. HTTP log messages are no longer written to the weblogic.log.

Support to properly handle UnavailableExceptions thrown by servlets. WebLogic now responds to the current and future requests with a 503 (Service Unavailable) HTTP error. If the servlet specifies a time at which it will again be available, WebLogic will attempt to use the servlet for requests that are submitted after the specified time.

HTTPD log format now complies strictly with NCSA Common Log Format.

Added support for GET with "If-Modified-Since" and for HEAD requests.

Made HTTP thread usage smarter so that keep-alive is sensitive to server load. This prevents keep-alive in HTTP connections from tying up all server resources in a high-load situation. Keep-alive is maintained only if other requests will not be neglected by doing so.

Added support for the HTTP response header "Server: WebLogic [version]"

Fixed how URLs are dealt with so that a URL is only munged if the current session didn't come from a cookie.

Fixed reporting of cookie age so that it now reports a standard date and time.

Improved URL resolution so that a servlet group can be registered with its file extension (for example, "*.jhtml" is now valid in the properties file.) Multilevel names are also now recognized; for example, registering "" will now cause WebLogic to serve the servlet "servlet.baz" for the request "http://myserver/foo/bar". The order in which servlets are searched for is: an exact match of the URL, through each level from the lowest to the highest; then a match for an extension of the URL; finally defaulting to the default servlet.

Implemented a portion of the session interface that causes the session tracker to respect the "HttpBindingListener" interface when binding or unbinding objects to a session. When an object that implements that interface is bound, the valueBound() method of that is called.

Changed usage of getRemoteHost() in HTTP logging to be configurable based on the property weblogic.system.enableReverseDNSLookups.

Enabled writing out the access.log by default, which is the destination of all WebLogic HTTP-related log messages. Previously this log had to be enabled in the properties file; it is now enabled by default.

Added support for getWriter() and getCharacterEncoding to implementation of ServletResponse.

Release 3.0.4 -- 4/28/98

Fixed a problem related to HTTP proxying from an HTTP/1.1 client to an HTTP/1.0 server, so that the forwarded headers from a 1.1 client are readable by an HTTP/1.0 server, specifically for HTTP/1.1 features like chunked transfer-encoding that a 1.0 server does not handle.

Release 3.0 -- 1/29/98

Fixed a bug in HttpServletRequest.getPathInfo(). It was returning the query string rather than just the path.

Added support for access control lists for HTTP servlets.

Release 2.5 -- 8/23/97

Upgraded HTTP servlet support to the latest version of the Java Servlet API (FCS 1.01) (javax.servlet.http). Note that Sun changed the package names from java.servlet to javax.servlet between the last alpha release (A2) and FCS. The package documentation for HttpServlet (which WebLogic supports) is available at Sun.

Sun made changes in the specification that may affect your servlets:

  1. You must change import statements from java.servlet.* to javax.servlet.*. Please note that these are Sun's package name changes, not BEA's.

  2. The method HttpServletRequest.getHeaderName(int i), which returned a String, changed to a method HttpServletRequest.getHeaderNames(), which returns an Enumeration. The method getHeader(), which originally took an int argument, now takes a String argument -- one of the elements of the Enumeration, cast as a String. Here is an example of how your implementation may change:
      // What your code probably looked like...
      for (int i - 0;
           (name = req.getHeaderName(i)) != null;
           i++;) {
        doSomeThing(name, req.getHeader(i));
      // What your code probably should look like...
      Enumeration names = req.getHeaderNames();
      while (names.hasMoreElements()) {
        name = (String)names.nextElement();
        doSomeThing(name, req.getHeader(name));

  3. Added support for FormServlet to htmlKona. htmlKona originally had a class called FormServlet (sub-classed from HtmlPage) that we removed from the API when version A2 of the Java Servlet API came out with the class java.servlet.http.FormServlet. The FCS version of the Java Servlet API no longer has this class, so we have added support for weblogic.html.FormServlet back into the htmlKona library. (This was removed finally in 3.0.)

Added support for reloading servlets without restarting the WebLogic Server, with these two properties:


Please see WebLogic properties for more instructions on using these new properties.

Added support for serving all file types with the WebLogic Server's HTTP capability, including .HTML, .JAR, .CAP, .ZIP, etc.

Release 2.4 -- 5/20/97

Increased performance and robustness for HTTP servlets in WebLogic.

Release 2.3.2 -- 3/18/97

Registered servlets can now be authorized for HTTP access on a per-servlet basis with the following properties:


To set up per-servlet security, you must first create a username and password, by setting the property weblogic.user.username=password, as in this example for user "peter":


Then add this user to the comma-delimited list for access to a particular servlet. For example, for the servlet registered as "counter" that already has users peter and paul, you can add the new user mary as shown here:


Note that there are no spaces in property entries.

Release 2.3 -- 12/23/96

Upgraded support for JeevesA2-style HTTP servlets. To continue to use Jeeves-style servlets with the WebLogic Server, you must track the current release of Jeeves. You will need to make changes to your code and recompile your servlets. Note that WebLogic only supports Jeeves-style servlets that extend HttpServlet or one of its subclasses.

Code changes include:

  1. Make sure that you do not have any old versions of Jeeves in your CLASSPATH. This will cause a ClassCastException when the WebLogic Server tries to load a servlet. If you have the current version of Jeeves in your CLASSPATH, the WebLogic classes must be first.

  2. Your servlets should now import java.servlet.* and java.servlet.http.*.

  3. Your servlet class should extend java.servlet.http.HttpServlet, or one of its subclasses.

  4. Change all references to ServletResponse and ServletRequest objects to HttpServletResponse and HttpServletRequest.

  5. Remove calls to ServletResponse.writeHeaders(). The method no longer exists.

  6. All of the final static ints for status that were in ServletResponse have moved to HttpServletResponse.

  7. Change all calls to ServletRequest.getQueryParameter() to HttpServletRequest.getParameter().

  8. The class in htmlKona, FormServlet, that we provided in release 2.1 and 2.2 has now appeared in JeevesA2, so we have discontinued support for the class in htmlKona. If you were sub-classing weblogic.html.FormServlet, you should now subclass java.servlet.http.FormServlet instead.

WebLogic does not support the Jeeves HTML classes (java.servlet.html.*). htmlKona offers a much richer, object-oriented set of Java objects for generating HTML for your servlets.

Release 2.0.9 -- 9/9/96

Introduced support for HTTP servlets. Servlets must be registered in the file for initialization when the WebLogic Server is started.


Copyright © 2000 BEA Systems, Inc. All rights reserved.
Required browser: Netscape 4.0 or higher, or Microsoft Internet Explorer 4.0 or higher.
Last updated 02/1/2000