Thursday, December 11, 2008

Servlet Event Listeners

Overview
First introduced as part of version 2.3 of the Servlet specification, application event listeners allow you to receive notifications of certain web application events. The primary goal of providing application events is to allow you to better manage resources at either the context or HTTP session level. For example, you can be notified when a web application has been created and is ready to handle requests and create a pool of objects to be used by servlets. Conversely, when the web application is terminated, you can gracefully destroy the object pool.

Four different types of listeners are defined by the specification:
ServletContextListener Allows notification of context lifecycle events (create and destroy)
ServletContextAttributesListener Allows notification of context attribute changes (add, modify, and remove)
HttpSessionListener Allows notification of HTTP session lifecycle events (create and destroy)
HttpSessionAttributesListeners Allows notification of HTTP session attribute changes (add, modify, and remove)

Each of these listener interfaces can be implemented by a listener object. The object is registered with the web application via entries in the deployment descriptor (web.xml). Next, we’ll take a look at simple examples of each type of listener as well as the corresponding configuration in web.xml.

ServletContextListener
Implementing the javax.servlet.ServletContextListener interface allows you to receive context lifecycle events. Note that there is a one-to-one relationship between a context and a web application, so it is safe to say that context lifecycle events can be viewed as web application lifecycle events as well.
The ServletContextListener is, in my opinion, the most powerful of the event listeners in that it allows you to manage resources that will be used by your web application, such as a JDBC connection pool. When you receive notification that the context has been created, you can create and initialize a pool of JDBC connections, and when the context is destroyed, you can properly tear it down.
Prior to the introduction of the ServletContextListener, many servlet developers would use a preloaded servlet to manage resources. The servlet would be preloaded when the web application started and its init() method would be called, which is where any resource initialization code would reside. When the web application was destroyed, the servlet destroy() method would be invoked and any resources would be destroyed as well. This is still a perfectly acceptable way to handle resources, but using the ServletContextListener is a much cleaner (and more elegant) way to handle context lifecycle events.
Let’s take a look at a simple implementation that simply outputs messages to the servlet log file when context events take place:

package com.omh.listeners;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;

/**
* Simple example of implementing the application lifecycle
* event listener ServletContextListener
*/
public class MyContextListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

context.log(context.getServletContextName() + " initialized");
}

public void contextDestroyed(ServletContextEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

context.log(context.getServletContextName() + " destroyed");
}
}
When a web application is started, a ServletContext is created as well. Once the ServletContext has been initialized, the servlet container checks its internal list of listeners. If any listeners implement javax.servlet.ServletContextListener, the contextInitialized() method will be invoked on that listener. A similar process is followed when the web application is destroyed. The following shows how our event listener is configured within web.xml:




com.omh.listeners.MyContextListener



Listeners are simply specified by adding a element with a corresponding entry that specifies the full package name of the class that implements one of the application event listeners. You can specify any number of listeners, and a single class can implement any number of the event listener interfaces. The order in which you specify event listeners in web.xml is important, because the servlet container will invoke the listeners in that same order when events occur. Note that when a context is destroyed, the listeners are invoked in reverse order. Remember that, in order to be fully portable, the elements in web.xml must appear in the same order as they appear in the XML grammar.

Using Tomcat 4.0, the servlet log file will contain the following messages after starting and then stopping the server:
Java Servlets Developer's Guide Listener Examples initialized

Java Servlets Developer's Guide Listener Examples destroyed
Note that you must specify a element within web.xml in order to get the web application name from getServletContextName(). If you don’t specify a , you will get the message “null initialized” instead.

ServletContextAttributeListener

Implementing the javax.servlet.ServletContextAttributeListener interface allows you to receive notification when attributes are added, modified, or removed from the ServletContext for a web application. Perhaps you have a very complex web application that stores state information in the ServletContext and you require notification of certain changes in state. Maybe you allow a servlet to cache information in the context, and have a background thread automatically destroy the cache after a certain amount of time (the thread can be started when the attribute is added). Whatever the reason, implementing the ServletContextAttributeListener gives you fine-grain control over these events.
Again, let’s take a look at an example that simply logs the context attribute events as they happen:
package com.omh.listeners;

import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContext;

/**
* Simple example of implementing the application lifecycle
* event listener ServletContextAttributeListener
*/
public class MyContextAttributeListener
implements ServletContextAttributeListener
{
public void attributeAdded(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object attributeValue = event.getValue();

context.log("Add context attribute " +
attributeName + "=" + attributeValue);
}

public void attributeRemoved(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object attributeValue = event.getValue();

context.log("Remove context attribute " +
attributeName + "=" + attributeValue);
}

public void attributeReplaced(ServletContextAttributeEvent event)
{
// Grab ahold of the ServletContext
ServletContext context = event.getServletContext();

String attributeName = event.getName();
Object oldAttributeValue = event.getValue();
Object attributeValue =
context.getAttribute(attributeName);

context.log("Replace context attribute " +
attributeName + "=" + attributeValue +
" old value=" + oldAttributeValue);
}
}
To see the listener in action, you first need to configure it within web.xml



com.omh.listeners.MyContextListener




and then create a simple servlet that uses context attributes:
package com.omh;

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

/**
* Simple servlet for testing a ServletContextAttributeListener
*/
public class TestContextAttributes
extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");

// Get an output stream that takes into account
// the proper character encoding
PrintWriter out = resp.getWriter();

// Get the context
ServletContext context = getServletContext();

// Set, modify, and delete an attribute
String name = "com.omh.name";

out.println("Setting " + name + " to Bob
");
context.setAttribute(name, "Bob");
out.println("Setting " + name + " to Larry
");
context.setAttribute(name, "Larry");
out.println("Removing " + name);
context.removeAttribute(name);
}
}
Note that the context attribute name I’m using includes my class package name. This is a good idea for two reasons. First, using the package name will greatly reduce the chance that another application will use the same name. Second, it helps you debug problems, because the name will contain the package name of the code that put it there.

Requesting this servlet will cause something like the following to be logged to the servlet log file:
Add context attribute com.omh.name=Bob
Replace context attribute com.omh.name=Larry old value=Bob
Remove context attribute com.omh.name=Larry

Basics of Filters : Servlet Filters ( Your First Filter )

Overview

Filters are a powerful feature first introduced in version 2.3 of the Servlet API. Filters allow you to write a software component that can then be placed into the request and response flow of a servlet or group of servlets. A filter is not a servlet; filters do not typically create a response to a request but, rather, either modify or inspect the request to a servlet or response from a servlet. Note that you not only can configure filters to act upon servlet requests, but can also apply them to the access of any resource (such as static files).

Like servlets, filters have a specification-defined lifecycle:

§ Filters are initialized by calling their init() method. The init() method is supplied with a FilterConfig object that allows the filter to access initialization parameters as well as reference to the ServletContext.
§ The doFilter() method of the filter is invoked during the request processing of a resource. It is in the doFilter() method that you can inspect the request, modify request headers, modify the response, or skip the processing of the underlying resource altogether.
§ The destroy() method is called when the filter is destroyed.


So what types of filters can you create? The servlet specification gives the following list of suggestions:

§ Authentication filters

§ Logging and auditing filters The first filter you will create in this chapter will log the access of a servlet and supply the elapsed execution time.
§ Image conversion filters Filters can very easily modify the output of a request, such as converting a JPEG image into GIF format.
§ Data compression filters Tomcat supplies the code for a compression filter (named CompressionFilter).
§ Tokenizing filters WML (Wireless Markup Language) is a perfect example of tokenizing; a tokenizing compiler converts tags into a single byte token in an effort to compress the response.
§ Filters that trigger resource access events You may want to log the fact that certain resources are being requested.
§ XSLT filters The last example in this chapter will illustrate the power of using filters to translate XML output into any number of target clients using XSL templates.

What makes a filter a filter?

You must implement the javax.servlet.Filter interface, which includes the init(), doFilter(), and destroy() lifecycle events, and then configure the filter within a web application to place itself into the process chain of a resource request.

Your First Filter

Let’s take a look at a very simple filter that will log the execution time of any requested resource:
package com.omh.filters;

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

/**
* Simple filter for measuring servlet response times
*/
public class ResponseTimerFilter
implements Filter
{
protected FilterConfig config;

public void init(FilterConfig config)
throws ServletException
{
// Save the config object
this.config = config;
}

public void destroy()
{
}

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException
{
// Save the start time
long startTime = System.currentTimeMillis();

// Invoke the next filter/servlet in the chain
chain.doFilter(request, response);

// Capture the elapsed time
long elapsed = System.currentTimeMillis() - startTime;

// Figure out what was requested. If we are not
// processing an HTTP request just default the
// name to servlet
String name = "servlet";
if (request instanceof HttpServletRequest)
{
name = ((HttpServletRequest) request).getRequestURI();
}

// Output the time
config.getServletContext().log(name +
" took " + elapsed + " ms");
}
}


The init() method simply saves a reference to the FilterConfig object (since we’ll use it later to access the ServletContext log() method). There is nothing to do in destroy(), since we don’t have anything to gracefully tear down when the servlet container is done with the filter, but we must provide an empty implementation in order to fully implement the Filter interface.
The doFilter() method is where all the action is found. For our simple ResponseTimeFilter, all we do is save the current clock time, call the next filter in the chain (which will ultimately invoke the requested servlet or resource), and log the elapsed time of the request.

After requesting any resource, the servlet container log file will contain something like the following:
2001-10-28 16:41:07 /jsdg-filters/Properties took 110 ms

In this case, I requested the Properties servlet using Tomcat 4.0. Note that we did nothing to modify the flow or content of the request or response, but this is certainly possible using filters (as we’ll see next).

To notify the servlet container that you have a filter, you must add a filter definition and filter mapping to web.xml:

Timing Filter
com.omh.filters.ResponseTimerFilter



Timing Filter
/*

The element defines the name and fully qualified class name of the filter, while defines a URL pattern that, when matched, will have the corresponding filter placed in its execution stream. A single servlet name can be specified instead, which we’ll use in the last example in the chapter. When using filters that overlap (meaning that more than one filter will be placed in the request chain), the filters will be applied in the same order in which they appear in web.xml.

Basics of Filters : Servlet Filters ( Your First Filter )

Overview

Filters are a powerful feature first introduced in version 2.3 of the Servlet API. Filters allow you to write a software component that can then be placed into the request and response flow of a servlet or group of servlets. A filter is not a servlet; filters do not typically create a response to a request but, rather, either modify or inspect the request to a servlet or response from a servlet. Note that you not only can configure filters to act upon servlet requests, but can also apply them to the access of any resource (such as static files).

Like servlets, filters have a specification-defined lifecycle:

§ Filters are initialized by calling their init() method. The init() method is supplied with a FilterConfig object that allows the filter to access initialization parameters as well as reference to the ServletContext.
§ The doFilter() method of the filter is invoked during the request processing of a resource. It is in the doFilter() method that you can inspect the request, modify request headers, modify the response, or skip the processing of the underlying resource altogether.
§ The destroy() method is called when the filter is destroyed.


So what types of filters can you create? The servlet specification gives the following list of suggestions:

§ Authentication filters

§ Logging and auditing filters The first filter you will create in this chapter will log the access of a servlet and supply the elapsed execution time.
§ Image conversion filters Filters can very easily modify the output of a request, such as converting a JPEG image into GIF format.
§ Data compression filters Tomcat supplies the code for a compression filter (named CompressionFilter).
§ Tokenizing filters WML (Wireless Markup Language) is a perfect example of tokenizing; a tokenizing compiler converts tags into a single byte token in an effort to compress the response.
§ Filters that trigger resource access events You may want to log the fact that certain resources are being requested.
§ XSLT filters The last example in this chapter will illustrate the power of using filters to translate XML output into any number of target clients using XSL templates.

What makes a filter a filter?

You must implement the javax.servlet.Filter interface, which includes the init(), doFilter(), and destroy() lifecycle events, and then configure the filter within a web application to place itself into the process chain of a resource request.

Your First Filter

Let’s take a look at a very simple filter that will log the execution time of any requested resource:
package com.omh.filters;

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

/**
* Simple filter for measuring servlet response times
*/
public class ResponseTimerFilter
implements Filter
{
protected FilterConfig config;

public void init(FilterConfig config)
throws ServletException
{
// Save the config object
this.config = config;
}

public void destroy()
{
}

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException
{
// Save the start time
long startTime = System.currentTimeMillis();

// Invoke the next filter/servlet in the chain
chain.doFilter(request, response);

// Capture the elapsed time
long elapsed = System.currentTimeMillis() - startTime;

// Figure out what was requested. If we are not
// processing an HTTP request just default the
// name to servlet
String name = "servlet";
if (request instanceof HttpServletRequest)
{
name = ((HttpServletRequest) request).getRequestURI();
}

// Output the time
config.getServletContext().log(name +
" took " + elapsed + " ms");
}
}


The init() method simply saves a reference to the FilterConfig object (since we’ll use it later to access the ServletContext log() method). There is nothing to do in destroy(), since we don’t have anything to gracefully tear down when the servlet container is done with the filter, but we must provide an empty implementation in order to fully implement the Filter interface.
The doFilter() method is where all the action is found. For our simple ResponseTimeFilter, all we do is save the current clock time, call the next filter in the chain (which will ultimately invoke the requested servlet or resource), and log the elapsed time of the request.

After requesting any resource, the servlet container log file will contain something like the following:
2001-10-28 16:41:07 /jsdg-filters/Properties took 110 ms

In this case, I requested the Properties servlet using Tomcat 4.0. Note that we did nothing to modify the flow or content of the request or response, but this is certainly possible using filters (as we’ll see next).

To notify the servlet container that you have a filter, you must add a filter definition and filter mapping to web.xml:

Timing Filter
com.omh.filters.ResponseTimerFilter



Timing Filter
/*

The element defines the name and fully qualified class name of the filter, while defines a URL pattern that, when matched, will have the corresponding filter placed in its execution stream. A single servlet name can be specified instead, which we’ll use in the last example in the chapter. When using filters that overlap (meaning that more than one filter will be placed in the request chain), the filters will be applied in the same order in which they appear in web.xml.

Thursday, December 4, 2008

Example Building : HelloWorld Servlet Code Example on Weblogic

HelloWorld Servlet Example on Weblogic

1. Directory Structure for your Helloworld servlet :



2. Code:

Note :- Place the source file in WEB-INF/src/test/ directory.

package test;

import java.io.*;

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

public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
out.println("Hello, world!");
out.close();
}
}

3. Configuration Files

Note :- Put the configuration files in WEB-INF directory.

Web.xml :-

















Weblogic.xml :- This file is optional for this example.But this is for reference.






4. Compile the servlet code and place in WEB-INF/classes/test/ directory
Make jar (name of jar file : test.jar ) file and upload it on weblogic.

5. URL for accessing the servlet is :
http://localhost:7001/test/hello/


Note :- For any questions you can leave your comments.

Wednesday, December 3, 2008

Basics Of Servlet- Make it easy....... ( Part - 1 )

1 What is a Servlet?

A servlet is a Java class that extends the functionality of web server dynamically. Web applications use servlets to create a request-response programming model.
In other words, Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet".

The javax.servlet and javax.servlet.http packages in the Java Servlet API provide classes, such as the GenericServlet and HttpServlet classes, to create servlets. The derived classes of the GenericServlet class are used to create protocol independent servlets whereas the HttpServlet class helps create servlets that work with the HTTP protocol.

Typical uses for HTTP Servlets include:
• Processing and/or storing data submitted by an HTML form.
• Providing dynamic content, e.g. returning the results of a database query to the client.
• Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

2. Servlets vs CGI

The traditional way of adding functionality to a Web Server is the Common Gateway Interface (CGI), a language-independent interface that allows a server to start an external process which gets information about a request through environment variables, the command line and its standard input stream and writes response data to its standard output stream. Each request is answered in a separate process by a separate instance of the CGI program, or CGI script (as it is often called because CGI programs are usually written in interpreted languages like Perl).

Servlets have several advantages over CGI:

• A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
• A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
• There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
• A Servlet can be run by a Servlet Engine in a restrictive Sandbox (just like an Applet runs in a Web Browser's Sandbox) which allows secure use of untrusted and potentially harmful Servlets.

3. The Basic Servlet Architecture

A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. In this tutorial we'll be discussing only HTTP Servlets which extend the javax.servlet.http.HttpServlet class.

4. Servlet LifeCycle

In order to initialize a Servlet, a server application loads the Servlet class (and probably other classes which are referenced by the Servlet) and creates an instance by calling the no-args constructor. Then it calls the Servlet's init(ServletConfig config) method. The Servlet should performe one-time setup procedures in this method and store the ServletConfig object so that it can be retrieved later by calling the Servlet's getServletConfig() method. This is handled by GenericServlet. Servlets which extend GenericServlet (or its subclass HttpServlet) should call super.init(config) at the beginning of the init method to make use of this feature. The ServletConfig object contains Servlet parameters and a reference to the Servlet's ServletContext. The init method is guaranteed to be called only once during the Servlet's lifecycle. It does not need to be thread-safe because the service method will not be called until the call to init returns.

A typical Servlet lifecycle :




When the Servlet is initialized, its service(ServletRequest req, ServletResponse res) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) so it should be implemented in a thread-safe manner. Techniques for ensuring that the service method is not called concurrently.
When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down) the destroy() method is called. There may still be threads that execute the service method when destroy is called, so destroy has to be thread-safe. All resources which were allocated in init should be released in destroy. This method is guaranteed to be called only once during the Servlet's lifecycle.

---------------------------Part II :- HelloWorld Servlet on Weblogic---------------------------