Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

Search: 

  Tutorial: Filter code with Servlet 2.3 model - JavaWorld June 2001

Filter code with Servlet 2.3 model - JavaWorld June 2001

Tutorial Details:

Filter code with Servlet 2.3 model
Filter code with Servlet 2.3 model
By: By Jason Hunter
Discover freely available servlet filters you can use today
n "Servlet 2.3: New Features Exposed," I introduced the changes coming in the Servlet API 2.3 and gave a short tutorial on the new servlet filter model. In this follow-on article, I'll dig deeper into servlet filters and look at several filters you can download for free on the Web. For each filter, I'll examine what it does, how it works, and where you can get it.
You can use this article in two ways: to learn about some filters that are useful out of the box, or as an aid in writing your own filters. I'll start off with some simple examples and then move on to more advanced ones. At the end, I'll show you a file upload filter I wrote to support multipart requests.
Servlet filters
In case you aren't yet familiar, a filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually create a response. They are preprocessors of the request before it reaches a servlet, and/or postprocessors of the response leaving a servlet. As you'll see later in the examples, a filter can:
Intercept a servlet's invocation before the servlet is called
Examine a request before a servlet is called
Modify the request headers and request data by providing a customized version of the request object that wraps the real request
Modify the response headers and response data by providing a customized version of the response object that wraps the real response
Intercept a servlet's invocation after the servlet is called
You can configure a filter to act on a servlet or group of servlets. Zero or more filters can filter one or more servlets. A filter implements javax.servlet.Filter and defines its three methods:
void init(FilterConfig config) throws ServletException : Called before the filter goes into service, and sets the filter's configuration object
void destroy() : Called after the filter has been taken out of service
void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException : Performs the actual filtering work
The server calls init(FilterConfig) once to prepare the filter for service, then calls doFilter() any number of times for requests specially set up to use the filter. The FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. The server calls destroy() to indicate that the filter is being taken out of service. The filter lifecycle is now very similar to the servlet lifecycle -- a change recently made in the Servlet API 2.3 Public Final Draft #2. Previously the lifecycle involved a setFilterConfig(FilterConfig) method.
In its doFilter() method, each filter receives the current request and response, as well as a FilterChain containing the filters that still must be processed. In the doFilter() method, a filter may do what it wants with the request and response. (It could gather data by calling their methods, or wrap the objects to give them new behavior, as I'll discuss later.) The filter then calls chain.doFilter() to transfer control to the next filter. When that call returns, a filter can, at the end of its own doFilter() method, perform additional work on the response; for instance, it can log information about the response. If the filter wants to halt the request processing and gain full control of the response, it can intentionally not call the next filter.
Spot the slowdown
To really understand filters, you have to see them in action. The first filter we'll look at is simple but powerful; it records the duration of all requests. It's modeled loosely after the nondescriptively named ExampleFilter from the Tomcat 4.0 distribution. Here is the code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimerFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void destroy() {
config = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
long before = System.currentTimeMillis();
chain.doFilter(request, response);
long after = System.currentTimeMillis();
String name = "";
if (request instanceof HttpServletRequest) {
name = ((HttpServletRequest)request).getRequestURI();
}
config.getServletContext().log(name + ": " + (after - before) + "ms");
}
}
When the server calls init() , the filter saves a reference to the config in its config variable, which is later used in the doFilter() method to retrieve the ServletContext . When the server calls doFilter() , the filter times how long the request handling takes and logs the time once processing has completed. This filter nicely demonstrates before- and after-request processing. Notice that the parameters to the doFilter() method are not HTTP-aware objects, so to call the HTTP-specific getRequestURI() method requires a cast of the request to an HttpServletRequest type.
To use this filter, you must declare it in the web.xml deployment descriptor using the tag, as shown below:

timerFilter
TimerFilter

This notifies the server that a filter named timerFilter is implemented in the TimerFilter class. You can apply a registered filter to certain URL patterns or servlet names using the tag:

timerFilter
/*

This configures the filter to operate on all requests to the server (static or dynamic), just what we want for our timing filter. If you connect to a simple page, the log output might look like this:
2001-05-25 00:14:11 /timer/index.html: 10ms
In Tomcat 4.0 beta 5, you'll find the log file under server_root/logs/ .
Download the WAR file for this filter at http://www.javaworld.com/jw-06-2001/Filters/timer.war .
Who's on your site, and what are they doing?
Our next filter is a clickstream filter written by the folks at OpenSymphony . This filter tracks user requests (a.k.a. clicks) and request sequences (a.k.a. clickstreams) to show a site administrator who's visiting her site and what pages each visitor has accessed so far. It's an open source library, under the LGPL license.
Inside the clickstream library you'll find a ClickstreamFilter class that captures request information, a Clickstream class that operates like a struct to hold data, and a ClickstreamLogger class that captures session and context events to glue everything together. There's also a BotChecker class that determines if a client is a robot (using simple logic, like "Did they request robots.txt?"). To view the data, the library provides a clickstreams.jsp visitor summary page and a supporting viewstream.jsp visitor detail page.
We'll look first at the ClickstreamFilter class. All these examples are slightly modified from the original, for formatting and to fix portability issues, which I'll discuss later.
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class ClickstreamFilter implements Filter {
protected FilterConfig filterConfig;
private final static String FILTER_APPLIED = "_clickstream_filter_applied";
public void init(FilterConfig config) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Ensure that filter is only applied once per request.
if (request.getAttribute(FILTER_APPLIED) == null) {
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
HttpSession session = ((HttpServletRequest)request).getSession();
Clickstream stream = (Clickstream)session.getAttribute("clickstream");
stream.addRequest(((HttpServletRequest)request));
}
// pass the request on
chain.doFilter(request, response);
}
public void destroy() { }
}
The doFilter() method gets the user session, obtains the Clickstream from the session, and adds the current request data to the Clickstream . It uses a special FILTER_APPLIED marker attribute to note if the filter was already applied for this request (as might happen during request dispatching) and to ignore any follow-on filtering action. You might wonder how the filter knows that the clickstream attribute will be present in the session. That's because the ClickstreamLogger places it there when the session is created. Here is the ClickstreamLogger code:
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ClickstreamLogger implements ServletContextListener,
HttpSessionListener {
Map clickstreams = new HashMap();
public ClickstreamLogger() { }
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("clickstreams", clickstreams);
}
public void contextDestroyed(ServletContextEvent sce) {
sce.getServletContext().setAttribute("clickstreams", null);
}
public void sessionCreated(HttpSessionEvent hse) {
HttpSession session = hse.getSession();
Clickstream clickstream = new Clickstream();
session.setAttribute("clickstream", clickstream);
clickstreams.put(session.getId(), clickstream);
}
public void sessionDestroyed(HttpSessionEvent hse) {
HttpSession session = hse.getSession();
Clickstream stream = (Clickstream)session.getAttribute("clickstream");
clickstreams.remove(session.getId());
}
}
The logger receives application events and uses them to bind everything together. On context creation, the logger places a shared map of streams into the context. This allows the clickstreams.jsp page to know what streams are currently active. On context destruction, the logger removes the map. When a new visitor creates a new session, the logger places a new Clickst


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Filter code with Servlet 2.3 model - JavaWorld June 2001

View Tutorial:
Filter code with Servlet 2.3 model - JavaWorld June 2001

Related Tutorials:

Displaying 1 - 50 of about 3759 Related Tutorials.

Response Filter Servlet Example
Response Filter Servlet Example Response Filter... of response filter in  Java Servlet. Filter reads own initial parameters and adds... when the web container creates an instance of the filter. The code then gets
 
Logging Filter Servlet Example
Logging Servlet Example Logging Filter Servlet... Filter This example illustrates how one can write Logging Filter servlet.... Filters are very important in servlet access and handling due to number of reasons
 
IP Filter Example
by a servlet container used to pass information to a filter during initialization...;{} } Here is the source code of CallIpFilter Servlet. import ... (IPFilterExample) and Servlet (CallIpFilter) in web.xml <filter>   
 
Difference between Servlet 2.5 and Servlet 2.4
-name>FilterName</filter-name> <servlet-name>FilterName</servlet...;filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>*</servlet-name> </filter-mapping>   
 
Servlet Tutorials Links
a short tutorial on the new servlet filter model. In this follow-on article, I'll.... What is servlet: Servlets are modules of Java code... community by storm. Now, with the introduction of Version 2.3 of the Servlet API
 
Filter Files in Java
Filter Files,Java Filter File,Java File Filter Example,File Filter Source Code in Java Filter Files in Java  ...; Introduction The Filter File Java example code provides the following
 
Setting a Filter on a Logger Handler in Java
to 20 with the help of logMessn() method. Descriptions of code: Filter... Setting a Filter on a Logger Handler in Java Setting a Filter on a Logger Handler in Java     
 
Servlet Training Overview
Understanding the multithreaded servlet model Understanding...; Filter and Servlet          ... Filter mapping to a URL pattern Declaring Filter mapping to a servlet
 
Features of Servlet 2.5
;/filter-name> <servlet-name>FilterName</servlet-name> <...;filter-name>FilterName</filter-name> <servlet-name>*</servlet...;servlet-mapping> or <filter-mapping> there used to be only one <url
 
Send Redirect in Servlet
with the status code. Then the browser sees the status code and look for that servlet... Send Redirect in Servlet 1 Send Redirect in Servlet           
 
Spring Context Loader Servlet
before load-on-startup servlets. Many Servlet 2.3 containers already enforce... with this servlet. Servlet 2.3 containers known to work with bootstrap listeners.... Servlet 2.3 containers known not to work with bootstrap listeners are: BEA WebLogic
 
Setting a Filter on a Logger Handler in Java
to 20 with the help of logMessn() method. Descriptions of code: Filter... Setting a Filter on a Logger Handler in Java Setting a Filter on a Logger Handler in Java     
 
Post Message In servlet
Post Message In servlet Post Message In servlet... to servlet. In the following program, you will learn how to post massage.  Code Description: The following program uses getOutputStream() method
 
Open Source Business Model
Open Source Business Model Open Source Business Model What is the open source business model It is often confusing to people.... The open source business model relies on shifting the commercial value away from
 
Sharing a Table Model between JTable Components
Sharing a Table Model between JTable Components Sharing a Table Model between JTable Components    ...; In this section, you will learn how to share a table model between JTable components
 
Quintessential Servlet
way of code written for an organizations servlet. The word "... Quintessential Servlet Quintessential Servlet...;  Example program for Quintessential servlet Quintessential servlet
 
Servlet Context
; In the servlet code we will write this as ServletContext context = getServletContext... Servlet Context Servlet Context... with the servlet container. There is only one ServletContext for the entire web application
 
Displaying Date in Servlet
Servlet Date Example,Displaying Date in Servlets,How to Display Date using Java Servlet Displaying Date in Servlet... the Date class of the java.util package.  As we know that the our servlet
 
Rainfall Model Questions
Java: Rainfall Model Questions Java NotesRainfall Model Questions Name ______________________________ This is part of the code to implement the model that was used
 
Accessing Date In Servlet
Accessing Date in Servlets,Date Example in Servlet,Source Code to Display Date in Java Servlets Accessing Date In Servlet... package.  As we know that the our servlet extends the HttpServlet
 
GUI-Model Rainfall program
Java: GUI-Model Rainfall program Java NotesGUI-Model Rainfall program This is an example serves.... Show an example of separating the GUI from the model. Show an example
 
Use Log in Servlet Context
Use Log in Servlet Context Use Log in Servlet Context...;  This section illustrates you how to use log in Servlet Context. We are providing you an example. In the given example, an object of Servlet Context
 
developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0
is the code of our servlet. /* * SessionTestServlet.java... developing a Session Bean and a Servlet and deploy the web application... through Servlet        
 
Open Source E-mail
is an open-source, server-side junk mail filter package for businesses... platform that includes full source code for complete control.    ... RTP and RTSP protocols. Based on the same code base as QuickTime Streaming
 
J2ME Servlet Example
. For your help we provide to you the source code of the servlet and web.xml... J2ME Servlet Example J2ME Servlet Example...; This is the simple servlet tutorial. In this tutorial we shows you
 
A simple example of log4j for Servlet
to create a log in a Servlet. Description of the code: Logger.getLogger... A simple example of log4j for Servlet A simple example of log4j for Servlet      
 
Show Parameter In Servlet
Show Parameter In Servlet Show Parameter In Servlet           ... is described below. Code Description: Here, in this example, you will also see
 
Hit Counter Servlet Example
Hit Counter Servlet Example Hit Counter Servlet... times the servlet is accessed. When first time servlet (CounterServlet) runs...;   Here is the source code of CounterServlet.java
 
Context attributes in Servlet
Context attributes in Servlet Context attributes in Servlet           ... Attributes in Servlet. All Servlets belong to one servlet context. A Servlet
 
Design patterns interview questions2
;       Q9. What is Intercepting Filter... and responses. For ex. Servlet filters. Q10. What is Front Controller pattern? Ans. It manages and handles requests through a centralized code. This could either
 
Send Redirect in Servlet
with the status code. Then the browser sees the status code and look for that servlet which... Send Redirect in Servlet Send Redirect in Servlet... of our servlet, then there we should use sendRedirect() method.  In send
 
Insert Image into Database Using Servlet
is the mapping code that you can put in web.xml file: <servlet> <servlet... Insert  Image into Database Using Servlet Insert  Image into Database Using Servlet  
 
Check if parameter exists in servlet request
Check if parameter exists in servlet request Check if parameter exists in servlet request   ...; In this example we will see how to check is parameter exists in servlet request
 
Servlet Interview Questions
Servlet Interview,servlet questions,Servlet Interview Questions,Servlet Servlet Interview Questions  ...; Collection of large number of Servlet Interview Questions. These questions
 
Servlet Interview Questions
Servlet Interview,servlet questions,Servlet Interview Questions,Servlet Servlet Interview Questions  ...; Collection of large number of Servlet Interview Questions. These questions
 
Context Log Example Using Servlet
Context Log Example Using Servlet Context Log Example Using Servlet      ... about how to use of Context Log in servlet. Context Log is used to write specified
 
Code Management
Code Management Code Management... and in the source code as headers.        ... Synchronizer is a free Eclipse plugin code generation tool to be used with the Hibernate
 
Time Updater in Servlet
Time Updater in Servlet Time Updater in Servlet...;  In this program we are going to make one program on servlet which... to you.  To make this servlet firstly we need to make a class named
 
A Holistic counter in Servlet
A Holistic counter in Servlet A Holistic counter in Servlet          ... a such a servlet which will count the number it has been accessed and the number
 
How to get client's address in a servlet
How to get client's address in a servlet How to get client's address in a servlet     ... code to get client's address in a servlet. In this example we have used
 
Ajax Code Libraries and Tools
Ajax Code Libraries and Tools,Ajax Code,Ajax tools,Ajax example Ajax Code Libraries and Tools     ...;          Code
 
Use of Cookie in Servlet
Use of Cookie in Servlet Use of Cookie in Servlet... in Servlet. The cookie class provides an easy way  for servlet to read... the same Web site. A servlet uses the getCookies() method of HTTPServletRequest
 
DSL Filter
DSL Filter DSL Filter   ... through using standard telephone line connection, while DSL filter is a peripheral... filter, also known as micro filter is an analog low-pass filter device
 
Check if parameter exists in servlet request
; </BODY> </HTML>   Step 2:Source code of Servlet...;} } Step 3:Source code of Servlet... of Employee using Servlet. We create four file employee.jsp, viewdata.jsp
 
Presentation-Model Structure
Java: Presentation-Model Structure Java NotesPresentation-Model Structure Previous - Big Blob, Next... the user interface from the model (business logic, domain, ...). This provides a huge
 
Simple Counter In Servlet
Servlets Counter Example,Simple Counter in Java Servlet,Free Counter Example Using Java Servlet Simple Counter in Servlet... on counter which will keep track how many times the servlet has been accessed. 
 
Write date servlet and test on tomcat
Display the current date with a Servlet Display the current date with a Servlet     ...;         This servlet program
 
Simple Web Application using Servlet
Simple Web Application using Servlet Simple Web Application using Servlet      ... developed a simple web application in Servlet . In this application user can add
 
Java server Faces Books
servlet 2.3 and JSP 1.2 standards: real-world insight, advanced techniques... JavaServer Faces, or JSF, brings a component-based model to web application development that's similar to the model that's been used in standalone GUI
 
Create XML File using Servlet
Create XML File using Servlet Create XML File using Servlet        ...(); Step 1: Create a Servlet "XmlServlet.java"
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.