XML technologies / XSLT / Java and XSLT / Further techniques / Servlet filters

(Excerpt from “Java und XSLT” by Eric M. Burke)

Version 2.3 of the Java Servlet specification introduces the feature filter. A filter is an object that intercepts requests to a servlet, JSP or static file in a web application. It can modify requests and responses before they reach the underlying resource or client. Filters are declared in the deployment descriptor, so they can be integrated without modifying existing application code.

Overview

Servlet filters support logging, user authentication, data compression, encryption and XSLT transformations. Several filters can be chained, each performing a specific task. This book focuses on XSLT transformations. The following figure illustrates the general architecture.

Servlet filters

Figure: Servlet filters

The interface javax.servlet.Filter must be implemented by every filter. It defines these methods:

void init(FilterConfig config)
void destroy( )
void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

The methods init( ) and destroy( ) are identical to the servlet methods init( ) and destroy( ). init( ) is called when the filter loads. Its parameter FilterConfig provides access to ServletContext and a list of initialization parameters. The code in “ A servlet filter for XSLT transformations ” demonstrates this. The method destroy( ) is called when the filter terminates, allowing it to release resources.

The method doFilter( ) runs when a client request arrives. The filter belongs to a FilterChain established by the servlet container, allowing filters to be chained. To reject a request, a filter can simply do nothing. Otherwise it must pass control to the next chain element:

chain.doFilter(req, res);

That element may be another filter, a servlet or a JSP. The filter need not know which.

Calling doFilter(req, res) passes control to the next chain element. To modify a request or response, the filter must modify ServletRequest or ServletResponse respectively. Unfortunately both are interfaces whose implementations vary by servlet container. Moreover, their interfaces do not allow their values to be changed.

Servlet API version 2.3 solves this by introducing wrapper classes that allow requests and responses to be modified. These are the following classes:

  • javax.servlet.ServletRequestWrapper

  • javax.servlet.ServletResponseWrapper

  • javax.servlet.http.HttpServletRequestWrapper

  • javax.servlet.http.HttpServletResponseWrapper

Each wraps a request or response and delegates every method to the wrapped object. To change behavior, subclass one and override one or more methods. A custom filter might look like this:

public class MyFilter implements Filter {
     public void doFilter (ServletRequest req, ServletResponse res,
              FilterChain chain) throws IOException, ServletException {
         // umschließe die Anfrage und die Antwort
         MyRequestWrapper reqWrap = new MyRequestWrapper(req);
         MyResponseWrapper resWrap = new MyResponseWrapper(res);
                
         // gib die Wrapper an das nächste Element weiter
         chain.doFilter(reqWrap, resWrap);
     }
}

Here the request and response are modified by MyRequestWrapper and MyResponseWrapper respectively. This suffices for many simple filters, but modifying response content is harder. Consider the method getOutputStream( ) of javax.servlet.ServletResponse:

public interface ServletResponse {
  ServletOutputStream getOutputStream( ) throws IOException;
  ... weitere Methoden
}

javax.servlet.ServletResponseWrapper defines the same method as follows:

public class ServletResponseWrapper implements ServletResponse {
  private ServletResponse response;
  
  public ServletResponseWrapper(ServletResponse response) {
    this.response = response;
  }
  
  // die Default-Implementierung verwendet die umschlossene Antwort
  public ServletOutputStream getOutputStream( ) throws IOException {
    return this.response.getOutputStream( );
  }
  
  ... weitere Methoden verhalten sich entsprechend
}

To modify the response sent to the client browser, the wrapper subclass must override getOutputStream( ):

public class MyResponseWrapper extends ServletResponseWrapper {
  
  public ServletOutputStream getOutputStream( ) throws IOException {
    
    // Der ServletOutputStream der Basisklasse kann nicht zurückgegeben
    // werden, weil wir nicht auf die Ausgabe zugreifen dürfen. Deshalb wird
    // eine eigene Unterklasse von ServletOutputStream zurückgegeben:
    return new MyServletOutputStream( );
  }
}

ServletOutputStream is an abstract class with no methods for modifying its content. Instead, subclasses of ServletOutputStream must be written to access output and make the required changes. This makes modifying servlet responses complicated.

Filters for XSLT transformations

We have introduced filter concepts without much detail. The next example uses a filter for XSLT transformations and should clarify these topics.

Our goal is a servlet filter performing XSLT transformations. XML input comes from a servlet, JSP or static XML file. The filter intercepts XML before it reaches the browser, transforms it and sends the result to the browser.

The next example shows the first of three classes, a subclass of ServletOutputStream that intercepts output and buffers it in a byte array. XML data stays in this buffer until transformed.

Example: BufferedServletOutputStream.java

package com.oreilly.javaxslt.util;

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

/**
 * Ein selbstgeschriebener ServletOutputStream, der die Daten in einem Puffer
 * zwischenspeichert und sie nicht gleich an den Client weiterleitet.
 *
 * @author Eric M. Burke
 */
public class BufferedServletOutputStream extends ServletOutputStream {
  // der Puffer
  private ByteArrayOutputStream bos = new ByteArrayOutputStream( );
  
  /**
   * @return den Inhalt des Puffers.
   */
  public byte[] getBuffer( ) {
    return this.bos.toByteArray( );
  }
  
  /**
   * Diese Methode muß für eigene ServletOutputStreams definiert werden.
   */
  public void write(int data) {
    this.bos.write(data);
  }
  
  // BufferedHttpResponseWrapper ruft diese Methode auf
  public void reset( ) {
    this.bos.reset( );
  }
  
  // BufferedHttpResponseWrapper ruft diese Methode auf
  public void setBufferSize(int size) {
    // es gibt keine Möglichkeit, die Größe eines ByteArrayOutputStream zu ändern
    this.bos = new ByteArrayOutputStream(size);
  }
}

The class BufferedServletOutputStream extends ServletOutputStream. The only abstract method in ServletOutputStream is write( ). Our class must therefore define it. Instead of sending data to the client, it writes it to a ByteArrayOutputStream. The remaining methods, reset( ) and setBufferSize( ), are needed by the class in the next example.

Example: BufferedHttpResponseWrapper.java

package com.oreilly.javaxslt.util;

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

/**
 * Ein Response-Wrapper, der die Ausgabe in einem Puffer speichert.
 */
public class BufferedHttpResponseWrapper extends HttpServletResponseWrapper {
  private BufferedServletOutputStream bufferedServletOut
    = new BufferedServletOutputStream( );
  
  private PrintWriter printWriter = null;
  private ServletOutputStream outputStream = null;
  
  public BufferedHttpResponseWrapper(HttpServletResponse origResponse) {
    super(origResponse);
  }
  
  public byte[] getBuffer( ) {
    return this.bufferedServletOut.getBuffer( );
  }
  
  public PrintWriter getWriter( ) throws IOException {
    if (this.outputStream != null) {
      throw new IllegalStateException(
        "Die Servlet-API verbietet den Aufruf von getWriter( )"
        + "nachdem getOutputStream( ) aufgerufen wurde.");
    }
    
    if (this.printWriter == null) {
      this.printWriter = new PrintWriter(this.bufferedServletOut);
    }
    return this.printWriter;
  }

  public ServletOutputStream getOutputStream( ) throws IOException {
    if (this.printWriter != null) {
      throw new IllegalStateException(
        "Die Servlet-API verbietet den Aufruf von getOutputStream( )"
        + "nachdem getWriter( ) aufgerufen wurde.");
    }
    
    if (this.outputStream == null) {
      this.outputStream = this.bufferedServletOut;
    }
    return this.outputStream;
  }

  // überschreibe die Methoden, die mit dem Antwort-Puffer zu tun haben

  public void flushBuffer( ) throws IOException {
    if (this.outputStream != null) {
      this.outputStream.flush( );
    } else if (this.printWriter != null) {
      this.printWriter.flush( );
    }
  }

  public int getBufferSize( ) {
    return this.bufferedServletOut.getBuffer( ).length;
  }

  public void reset( ) {
    this.bufferedServletOut.reset( );
  }

  public void resetBuffer( ) {
    this.bufferedServletOut.reset( );
  }

  public void setBufferSize(int size) {
    this.bufferedServletOut.setBufferSize(size);
  }
}

BufferedHttpResponseWrapper extends HttpServletResponseWrapper and overrides every method affecting the Writer or OutputStream to the client. This gives full control over the response before returning it to the browser.

The Servlet API allows either getWriter( ) or getOutputStream( ) to be called, but not both. The response wrapper must support both because we cannot know which will be needed. This part of the filter API seems to need improvement.

Warning:
The Servlet specification documents very little of this. Hopefully that will change before this book appears. Few examples yet show interception and modification of responses. This should change as more containers support Servlet 2.3.

The next example shows the most important class: the actual filter performing XSLT transformations.

Example: A servlet filter for XSLT transformations

package com.oreilly.javaxslt.util;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
 * Eine Hilfsklasse, die die Servlet-Filter-API 2.3 verwendet,
 * um ein XSLT-Stylesheet auf eine Servlet-Antwort anzuwenden.
 *
 * @author Eric M. Burke
 */
public class StylesheetFilter implements Filter {
  private FilterConfig filterConfig;
  private String xsltFileName;
  
  /**
   * Diese Methode wird einmalig beim Laden des Filters aufgerufen.
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    
    // xsltPath könnte z.B. den String "/WEB-INF/xslt/a.xslt" beinhalten
    String xsltPath = filterConfig.getInitParameter("xsltPath");
    if (xsltPath == null) {
      throw new UnavailableException(
        "der Parameter xsltPath muß angegeben werden."
        + "Bitte prüfen Sie den Anwendungsdeskriptor.");
    }
  
    // konvertiere den relativen Pfad in einen physischen Pfad
    this.xsltFileName = filterConfig.getServletContext( )
      .getRealPath(xsltPath);
  
    // prüfe, ob die Datei existiert
    if (this.xsltFileName == null ||
        !new File(this.xsltFileName).exists( )) {
      throw new UnavailableException(
        "Kann Stylesheet nicht finden: " + this.xsltFileName, 30);
    }
  }

  public void doFilter (ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
        
    if (!(res instanceof HttpServletResponse)) {
      throw new ServletException("Dieser Filter unterstützt nur HTTP");
    }
        
    BufferedHttpResponseWrapper responseWrapper =
      new BufferedHttpResponseWrapper((HttpServletResponse) res);
    chain.doFilter(req, responseWrapper);
        
    // Tomcat 4.0 benutzt manchmal gepufferte Instanzen seiner Implementierung
    // von HttpServletResponse. Dies geschieht z.B., wenn der reload( )-Button
    // des Webbrowsers wiederholt betätigt wird. In diesem Fall werden
    // die Ausgaben jedoch nie in den OutputStream von
    // BufferedHttpResponseWrapper geschrieben, d.h. das
    // XML-Ausgabefeld bleibt leer. Der folgende Code behebt diesen
    // Mangel:
        
    byte[] origXML = responseWrapper.getBuffer( );
    if (origXML == null || origXML.length == 0) {
      // Tomcat soll seine zwischengespeicherten Daten zum Client schicken
      chain.doFilter(req, res);
      return;
    }

    try {
      // führe die XSLT-Transformation aus
      Transformer trans = StylesheetCache.newTransformer(
        this.xsltFileName);
        
      ByteArrayInputStream origXMLIn = new ByteArrayInputStream(origXML);
      Source xmlSource = new StreamSource(origXMLIn);
      
      ByteArrayOutputStream resultBuf = new ByteArrayOutputStream( );
      trans.transform(xmlSource, new StreamResult(resultBuf));
      
      res.setContentLength(resultBuf.size( ));
      res.setContentType("text/html");
      res.getOutputStream().write(resultBuf.toByteArray( ));
      res.flushBuffer( );
    } catch (TransformerException te) {
      throw new ServletException(te);
    }
  }
  /**
   * Das Gegenstück zur Methode init( )
   */
  public void destroy( ) {
    this.filterConfig = null;
  }
}

The filter requires the stylesheet name as an initialization parameter. This line reads it from the deployment descriptor:

String xsltPath = filterConfig.getInitParameter("xsltPath");

Passing the stylesheet as a parameter allows any XSLT transformation. The filter can apply to a servlet, JSP or static file, so XML input is not fixed either.

The method doFilter( ) illustrates another weakness of the current filter API:

if (!(res instanceof HttpServletResponse)) {
    throw new ServletException("Dieser Filter unterstützt nur HTTP");
}

No HTTP-specific filter interface exists, so custom filters must use the operator instanceof and casts to ensure that only HTTP requests are filtered.

Next, the filter creates the buffered response wrapper and passes it to the next chain element:

BufferedHttpResponseWrapper responseWrapper =
        new BufferedHttpResponseWrapper((HttpServletResponse) res);
chain.doFilter(req, responseWrapper);

This intercepts XML output for transformation. One more trick is needed for Tomcat 4.0 before transforming it:

byte[] origXML = responseWrapper.getBuffer( );
if (origXML == null || origXML.length == 0) {
   // veranlasse Tomcat, seine zwischengespeicherten Daten zum Client zu schicken
   chain.doFilter(req, res);
   return;
}

See the comment in “ A servlet filter for XSLT transformations ” for details. Tomcat caches its response when a user repeatedly requests the same static file. Without this check, the byte array origXML would be empty. (This was hard to discover. The specification is unclear here, so other containers may behave differently.)

The filter uses JAXP to perform the transformation and send its result to the original servlet response.

The corresponding deployment descriptor follows.

Example: Deployment descriptor for the filter

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd">
<web-app>
    <filter>
        <filter-name>xsltFilter</filter-name>
        <filter-class>com.oreilly.javaxslt.util.StylesheetFilter</filter-class>
        <init-param>
            <param-name>xsltPath</param-name>
            <param-value>/WEB-INF/xslt/templatePage.xslt</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>xsltFilter</filter-name>
        <url-pattern>/home.xml</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>xsltFilter</filter-name>
        <url-pattern>/company.xml</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>xsltFilter</filter-name>
        <url-pattern>/jobs.xml</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>xsltFilter</filter-name>
        <url-pattern>/products.xml</url-pattern>
    </filter-mapping>
</web-app>  

The descriptor’s opening lines show that filters require version 2.3 of the web application DTD.

The initialization parameter is then specified inside the element <filter>. It names the stylesheet for this filter instance. Multiple <filter> elements may use the same filter class with different filter names, allowing one filter to serve different configurations.

The descriptor then defines explicit mappings. Here the filter applies to static XML files, but it could just as easily apply to a servlet or JSP.

Final remarks on filters

Filters allow different stylesheets to transform XML from many sources. Changing stylesheets requires only changing the deployment descriptor. One interesting approach is to produce pure XML with JSP and transform it using a filter into XHTML data for the client.

Filters also have disadvantages and are often not the best solution. Their API requires Servlet 2.3, and many existing containers do not support them. For XSLT transformations a ServletOutputStream must be written to intercept the response, and downcasts are necessary because no HTTP-specific filter class exists. Some containers may buffer responses for performance, requiring workarounds for a reliable implementation.

Finally, this approach is slower. XML must be converted to text and buffered in memory before transformation, which is slower than sending SAX events or a DOM tree directly to the XSLT processor. Producing XML and transforming it in a servlet avoids the extra conversion required by a filter.

   

 

 

 

back to top