XML technologies / XSLT / Java and XSLT / Servlet basics and XSLT / Using the stylesheet cache

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

Two approaches avoided hardcoding absolute stylesheet paths. The first used ServletContext to load application resources through relative paths; the second used context initialization parameters.

Those were compile-time changes. Now consider dynamic loading. Class PersonalDataServlet locates two stylesheets and compiles them into instances of interface javax.xml.transform.Templates. This is fast, but keeps them in memory forever. Changes require stopping and restarting the servlet.

Integrating the stylesheet cache

A stylesheet cache was implemented in XSLT processing with Java. This example changes our PersonalDataServlet to use the cache instead of directly using Templates. Performance is nearly unchanged, but stylesheet edits appear immediately in the browser. Each request checks the file timestamp; changes create a new instance of Templates without a server restart.

The cache simplifies servlet PersonalDataServlet. Here is the revised code.

Example: Revised PersonalDataServlet.java using the stylesheet cache

package chap6;

import com.oreilly.javaxslt.util.StylesheetCache;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

/**
 * Eine Modifikation des PersonalDataServlets, das die
 * Klasse com.oreilly.javaxslt.util.StylesheetCache verwendet.
 */
public class PersonalDataServlet extends HttpServlet {
  private PersonalDataXML personalDataXML = new PersonalDataXML( );
  private String editXSLTFileName;
  private String thanksXSLTFileName;
  
  /**
   * Einmalige Initialisierung des Servlets.
   */
  public void init( ) throws UnavailableException {
    this.editXSLTFileName = getServletContext( ).getRealPath(
      "/WEB-INF/xslt/editPersonalData.xslt");
    this.thanksXSLTFileName = getServletContext( ).getRealPath(
      "/WEB-INF/xslt/confirmPersonalData.xslt");
  }
  
  /**
   * Bearbeitet HTTP GET-Anfragen, z.B. wenn der Nutzer eine
   * URL eingibt oder einen Link betätigt.
   */
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws IOException,
      ServletException {
    PersonalData personalData = getPersonalData(request);
    // Der dritte Parameter 'false' bewirkt, daß beim Anzeigen
    // der Seite keine Fehlermeldungen ausgegeben werden.
    showPage(response, personalData, false, this.editXSLTFileName);
  }
  
  /**
   * Bearbeitet HTTP POST-Anfragen, z.B. wenn der Nutzer den
   * Senden-Button betätigt, um seine Informationen abzuschicken.
   */
  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws IOException,
      ServletException {
    // Hole das Objekt personalData und beschreibe es mit den Informationen,
    // die der Nutzer übermittelt hat.
    PersonalData pd = getPersonalData(request);
    pd.setFirstName(request.getParameter("firstName"));
    pd.setLastName(request.getParameter("lastName"));
    pd.setDaytimePhone(request.getParameter("daytimePhone"));
    pd.setEveningPhone(request.getParameter("eveningPhone"));
    pd.setEmail(request.getParameter("email"));
        
    if (!pd.isValid( )) {
      // Zeige die Seite 'Ändern' mit einer Fehlermeldung
      showPage(response, pd, true, this.editXSLTFileName);
    } else {
      // zeige die Seite 'Bestätigung'
      showPage(response, pd, false, this.thanksXSLTFileName);
    }
  }
  
  /**
   * Eine Hilfsmethode, die die persönlichen Daten als HTML an den
   * Browser des Client schickt. Dabei wird ein XSLT-Stylesheet auf den
   * DOM-Baum angewendet.
   */
  private void showPage(HttpServletResponse response,
      PersonalData personalData, boolean includeErrors,
      String xsltFileName) throws IOException, ServletException {
    try {
      org.w3c.dom.Document domDoc =
        this.personalDataXML.produceDOMDocument(
        personalData, includeErrors);
      
      Transformer trans =
        StylesheetCache.newTransformer(xsltFileName);
      
      response.setContentType("text/html");
      PrintWriter writer = response.getWriter( );
      
      trans.transform(new DOMSource(domDoc), new StreamResult(writer));
    } catch (Exception ex) {
      showErrorPage(response, ex);
    }
  }
  
  /**
   * Falls ein Fehler auftritt, kann diese Methode den
   * Stack-Trace im Browser darstellen.
   */
  private void showErrorPage(HttpServletResponse response,
      Throwable throwable) throws IOException {
    PrintWriter pw = response.getWriter( );
    pw.println("<html><body><h1>Ein Fehler ist aufgetreten</h1><pre>");
    throwable.printStackTrace(pw);
    pw.println("</pre></body></html>");
  }
  
  /**
   * Eine Hilfsmethode, die das Objekt PersonalData aus der HttpSession ermittelt.
   */
  private PersonalData getPersonalData(HttpServletRequest request) {
    HttpSession session = request.getSession(true);
    PersonalData pd = (PersonalData) session.getAttribute(
          "chap6.PersonalData");
    if (pd == null) {
        pd = new PersonalData( );
        session.setAttribute("chap6.PersonalData", pd);
    }
    return pd;
  }
}

The main difference is dependence on class com.oreilly.javaxslt.util.StylesheetCache. Thus, add StylesheetCache.class to the WAR in the appropriate directory. Alternatively, package the cache in a JAR and copy it to TOMCAT_HOME/lib, as done in the book’s code.

Method init( ) saves the most code: only stylesheet filenames are stored instead of instances of Templates. The cache takes filenames and creates its own instances of Templates. Most other servlet changes follow from this.

Once the example runs, dynamic loading is easy to test. As before, copy chap6.war into TOMCAT_HOME/webapps. The first servlet request unpacks the WAR into TOMCAT_HOME/webapps/chap6. Go to TOMCAT_HOME/webapps/chap6/WEB-INF/xslt, and edit a stylesheet. Refresh the browser to see the changes.

If edits do not appear, older example files probably remain. Stop Tomcat and remove both chap6.war and directory chap6 from Tomcat’s directory webapps. Reinstall and retry.

   

 

 

 

back to top