Skip Navigation Links
Accueil
Java Standard EditionExpand Java Standard Edition
Java EE 5Expand Java EE 5
Visual Basic .Net 2005Expand Visual Basic .Net 2005
Visual C++ .Net 2005Expand Visual C++ .Net 2005
Visual C# .Net 2005Expand Visual C# .Net 2005
Cours ASP .Net 2.0Expand Cours ASP .Net 2.0
PostgresqlExpand Postgresql
LinuxExpand Linux
Visual Studio 2008Expand Visual Studio 2008
ASP 3.0 ClassiqueExpand ASP 3.0 Classique
Cours Javascript - DOM - DHTMLExpand Cours Javascript - DOM - DHTML
Cours AjaxExpand Cours Ajax
VBAExpand VBA
AssembleurExpand Assembleur
PerlExpand Perl
MembresExpand Membres
L'auteur du site
Nouveautés sur le site
Contacts
Plan du site
Accueil > Java EE 5 > Les filtres Java (javax.servlet.Filter)
____________________________________________________________________________________________________
Connexion

LES FILTRES EN JAVA (javax.servlet.filter)

1/6/2008

Testé sur Tomcat 5.5.17

Au démarrage de Tomcat, un fichier texte « localhost.2008-06-01 », se trouvant dans C:\Program Files\Apache Software Foundation\Tomcat 5.5\logs, est créé.

Dans Tomcat 5.5.17, il existe une application servlets-examples. Dans le web.xml de cette application web (qui se trouve dans son dossier WEB-INF), il y a ceci :

Created with colorer-take5 library. Type 'xml'

<filter>
        <filter-name>Path Mapped Filter</filter-name>
        <filter-class>filters.ExampleFilter</filter-class>

    <init-param>
        <param-name>attribute</param-name>
        <param-value>filters.ExampleFilter.PATH_MAPPED</param-value>

    </init-param>
    </filter>

Et ceci un peu plus loin :
Created with colorer-take5 library. Type 'xml'

 <!-- Define filter mappings for the defined filters -->
(…)
<filter-mapping>
        <filter-name>Path Mapped Filter</filter-name>
    <url-pattern>/servlet/*</url-pattern>

    </filter-mapping>


On prendra cet exemple pour comprendre les filtres. D’autres filtres sont déclarés dans cet exemple, qui se déclenchent selon un certain contexte, mais nous n’en parlerons pas pour l’instant.

La balise <filter> est la déclaration du filtre nommé « Path Mapped Filter », et dont la classe est « filters .ExampleFilter ».

La classe ExampleFilter se trouve dans le répertoire WEB-INF/classes/filters de notre application. Cette classe fait partie d’un package appelé « filters ».

La balise <filter-mapping> effectue le mapping entre un filtre et un modèle d’url (par exemple, cela peut être aussi une servlet, le nom de la servlet est alors dans une balise maServlet. On rappelle qu’on définit une servlet dans le fichier web.xml, en faisant
<servlet>
<servlet-name>maServlet</servlet-name>
<servlet-class>monPackage.maClasse</servlet-class>
</servlet>

ce qui effectue une sorte de mapping entre un nom « logique » de servlet, et sa classe.

Dans le cas du mapping entre un filtre et un modèle d’url, ce qui est notre cas ici, on rajoute
une balise <url-pattern> :
<url-pattern>/servlet/*</url-pattern>

La racine ici est relative à l’application web courante, cela veut dire qu’ici, toutes les url du type http://127.0.0.1:8080/servlets-examples/servlet/* sont valides. Vous pouvez créer un dossier « servlet » dans votre dossier « servlets-example », et y mettre vos pages.

Chaque url de cette forme, entraînera l’exécution du filtre « Path Mapped Filter », qui est de la classe filters.ExampleFilter.
On note qu’il est possible de passer en paramètre au filtre des valeurs, avec la balise <init-param> :
Created with colorer-take5 library. Type 'xml'

 <init-param>
        <param-name>attribute</param-name>
        <param-value>filters.ExampleFilter.SERVLET_MAPPED</param-value>

    </init-param>

Ici, on donne à notre classe de filtre, un paramètre, appelé « attribute », et qui a pour valeur «filters.ExampleFilter.PATH_MAPPED» . Nous pourrons récupérer cette valeur, correspondant à la clé « attribute », dans notre classe de filtre (nous verrons comment).

Regardons maintenant le code de la classe ExampleFilter :

Created with colorer-take5 library. Type 'java'

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0

*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package filters;


import java.io.IOException;
import javax.servlet.Filter;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
* Example filter that can be attached to either an individual servlet
* or to a URL pattern. This filter performs the following functions:
* <ul>

* <li>Attaches itself as a request attribute, under the attribute name
* defined by the value of the <code>attribute</code> initialization

* parameter.</li>
* <li>Calculates the number of milliseconds required to perform the
* servlet processing required by this request, including any

* subsequently defined filters, and logs the result to the servlet
* context log for this application.
* </ul>
*

* @author Craig McClanahan
* @version $Revision: 267129 $ $Date: 2004-03-18 11:40:35 -0500 (Thu, 18 Mar 2004) $

*/

public final class ExampleFilter implements Filter {


// ----------------------------------------------------- Instance Variables


/**
* The request attribute name under which we store a reference to ourself.
*/
private String attribute = null;


/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/

private FilterConfig filterConfig = null;


// --------------------------------------------------------- Public Methods


/**
* Take this filter out of service.

*/
public void destroy() {

this.attribute = null;

this.filterConfig = null;

}


/**
* Time the processing that is performed by all subsequent filters in the

* current filter stack, including the ultimately invoked servlet.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating

* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs

*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)

throws IOException, ServletException {

// Store ourselves as a request attribute (if requested)
if (attribute != null)

request.setAttribute(attribute, this);

// Time and log the subsequent processing
long startTime = System.currentTimeMillis();

chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();

filterConfig.getServletContext().log
(this.toString() + ": " + (stopTime - startTime) +

" milliseconds");

}


/**
* Place this filter into service.
*

* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;
this.attribute = filterConfig.getInitParameter("attribute");

}


/**
* Return a String representation of this object.
*/
public String toString() {

if (filterConfig == null)
return ("InvokerFilter()");

StringBuffer sb = new StringBuffer("InvokerFilter(");
sb.append(filterConfig);

sb.append(")");
return (sb.toString());

}

}



Cette classe implémente l’interface javax.servlet.Filter , dont le code source est le suivant :

Created with colorer-take5 library. Type 'java'

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0

*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;

import java.io.IOException;

    /** 
    * A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.

        * <br><br>
    * Filters perform filtering in the <code>doFilter</code> method. Every Filter has access to 
    ** a FilterConfig object from which it can obtain its initialization parameters, a

    ** reference to the ServletContext which it can use, for example, to load resources
    ** needed for filtering tasks.

    ** <p>
    ** Filters are configured in the deployment descriptor of a web application
    ** <p>

    ** Examples that have bee