ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


O'Reilly Book Excerpts: Java Servlet & JSP Cookbook

Cooking with Java Servlets & JSP

Related Reading

Java Servlet & JSP Cookbook
By Bruce W. Perry

by Bruce W. Perry

Editor's note: The Java Servlet & JSP Cookbook offers hundreds of tips and techniques that Java web developers can put to use every day. If you're thinking about adding this book to your Java library, here's a sneak peek at three recipes we've extracted from the book, which we think will make that purchasing decision an easy one. In these samples, learn how to use the Java Plug-in HTML Converter tool to generate the tags for embedding an applet, how to configure a javax.sql.DataSource for use in a servlet with the Tomcat web container, and how to use the JSTL's XML and XSLT-related tags. Enjoy.

Recipe 17.2: Embedding an Applet in a JSP Using the HTML Converter

Problem

You want to use the Java Plug-in HTML Converter tool to generate the tags for embedding an applet.

Solution

Use the HTML Converter tool within htmlconverter.jar, which is located in the lib directory of the directory where you have the Java SDK installed.

Discussion

A busy developer can let the Java Plug-in HTML Converter tool produce the HTML tags that are responsible for loading Java applets. The Java Plug-in is a Java-based tool that allows applets to be run in the Sun Microsystems Java 2 runtime environment, rather than within the web browser's Java runtime environment. The Java Plug-in is installed on your machine when you install the JRE, including the installation of the SDK.

The HTML Converter tool will convert a specified JSP file that contains an applet HTML tag, replacing the applet tag with a more complex tag collection that allows most browsers to load the Java applet. The Converter leaves the rest of your JSP code untouched; it only replaces the JSP's applet tag.

Here is how to use the HTML Converter tool:

  1. Write the JSP file, adding an applet tag. Example 17-3 shows a JSP that embeds a Clock.class applet reference. This JSP, rather redundantly, dynamically writes a time string beneath the applet. I included this code to show that the Converter does not change the JSP code; it just alters the applet tag template text included with the JSP.

    Example 17-3. A JSP with an applet tag

    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
    
    <jsp:useBean id="date" class="java.util.Date" />
    
    <html>
    <head><title>A Clock in a JSP</title></head>
    <body>
    <h2>The time...</h2>
    <applet code="Clock.class" codebase="http://localhost:8080/home/applets">
    </applet>
    
    <br /><c:out value="$2004-02-25"/>
    
    </body>
    </html>
  2. Open a command-line window to the lib directory of your SDK installation, such as H:\j2sdk1.4.1_01\lib.

  3. Type java -jar htmlconverter.jar -gui. This command launches the Swing version of the HTML Converter tool. Figure 17-2 shows what the tool looks like.

    Figure 17-2
    Figure 17-2. The HTML Converter (GUI version)

    TIP: The HTML Converter can also be run from the command line. See the Java Plug-in Developer Guide for supported options: http://java.sun.com/j2se/1.4.1/docs/guide/plugin/.

  4. If you want to choose a back-up folder where the tool saves the old JSP file (with the applet tag), use the HTML Converter GUI window to choose this folder.

  5. Click the "Convert . . . " button with the JSP file specified in the top text field, and the Converter will overwrite the original file with additional object and embed tags.

Example 17-4 shows the code that replaced the applet tag in Example 17-3 (in bold font), as well as the code that the converter tool did not modify.

Example 17-4. The object and embed tags produced by the HTML Converter

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<jsp:useBean id="date" class="java.util.Date" />

<html>
<head><title>A Clock in a JSP</title></head>
<body>
<h2>The time...</h2>

<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<OBJECT 
    classid = 
    "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

    codebase = 
    "http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-
     i586.cab#Version=1,4,0,0"
    >

    <PARAM NAME = CODE VALUE = "Clock.class" >
    <PARAM NAME = CODEBASE VALUE = "http://localhost:8080/home/applets" >
    <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.4">
    <PARAM NAME = "scriptable" VALUE = "false">

    <COMMENT>
        <EMBED 
            type = "application/x-java-applet;version=1.4" 
            CODE = "Clock.class"
            JAVA_CODEBASE = "http://localhost:8080/home/applets"  
            scriptable = false 
            pluginspage = 
       "http://java.sun.com/products/plugin/index.html#download">
            <NOEMBED>
            
        </NOEMBED>
        </EMBED>
    </COMMENT>
</OBJECT>

<!--
<APPLET CODE = "Clock.class" JAVA_CODEBASE =
    "http://localhost:8080/home/applets">
</APPLET>
-->


<!--"END_CONVERTED_APPLET"-->


<br /><c:out value="$2004-02-25"/>

</body>
</html>

WARNING: Users may have trouble loading the applet in their browsers if they have several installed versions of the Java Plug-in. This occurs when users steadily upgrade their JRE or Java SDK versions, which install the corresponding version of the Java Plug-in. The simplest solution in these cases is to uninstall the old Java Plug-ins.

See Also

The Java Plug-in technology page: http://java.sun.com/products/plugin/; Recipe 17.1 on embedding a Java applet using the jsp:plugin standard JSP action.

Recipe 21.2: Configuring a DataSource in Tomcat

Problem

You want to configure a javax.sql.DataSource for use in a servlet with the Tomcat web container.

Solution

Create a resource element in Tomcat's server.xml file and an associated resource-ref element in the web.xml deployment descriptor.

Discussion

Tomcat makes it easy to set up a connection pool so that servlets and JSPs can efficiently share database connections. In web sites that have many simultaneous users, a connection pool improves efficiency by sharing existing database connections, rather than creating a new connection and tearing it down every time an application has to use the database.

Another benefit of configuring a connection pool is that you can change the database system that a servlet or JSP is using without touching the Java code, because the database resource is configured outside of the servlet or JSP.

Here are the steps for configuring a DataSource with Tomcat:

  1. Create a Resource and a ResourceParams element in server.xml, or in the XML file that you have placed in Tomcat's webapps directory. These elements describe the JNDI object you are creating in order to provide your servlets or JSPs with a DataSource.

  2. Add a resource-ref element to web.xml, which allows the components in the associated web application to access the configured DataSource.

Example 21-2 shows the Resource and a ResourceParams elements in server.xml. This example describes a DataSource that connects with an Oracle 8i database.

Example 21-2. The resource element in server.xml

<Resource name="jdbc/oracle-8i-athletes" scope=
  "Shareable" type="javax.sql.DataSource" auth=
    "Container" description="Home Oracle 8i Personal Edition"/>

    <ResourceParams name="jdbc/oracle-8i-athletes">

      <parameter>
          <name>driverClassName</name>
          <value>oracle.jdbc.driver.OracleDriver</value>
      </parameter>

      <parameter>
          <name>url</name>
          <value>jdbc:oracle:thin:@192.168.0.2:1521:ORCL</value>
      </parameter>

          <parameter>
          <name>username</name>
          <value>scott</value>
      </parameter>

          <parameter>
          <name>password</name>
          <value>tiger</value>
      </parameter>

</ResourceParams>

Create a Resource and ResourceParams element for each database that your application uses. Example 21-3 shows the resource-ref element associated with the Resource specified by Example 21-2.

Example 21-3. A resource-ref element specifies a DataSource in web.xml

<!-- top of web.xml file -->
<resource-ref>

    <res-ref-name>jdbc/oracle-8i-athletes</res-ref-name>

    <res-type>javax.sql.DataSource</res-type>

    <res-auth>Container</res-auth>

</resource-ref>
<!-- rest of web.xml file -->

The JNDI path to this DataSource, which you use in a JNDI lookup (see the next recipe), is jdbc/oracle-8i-athletes.

TIP: The servlet 2.4 API does not require the web.xml elements such as resource-ref to appear in a specific order. The servlet 2.3 API specifies the order these elements must appear in with a Document Type Definition (DTD). See Chapter 1.

See Also

The JDBC specification: http://java.sun.com/products/jdbc/download.html; Recipe 21.3 on using a DataSource in a servlet with Tomcat; Recipe 21.4-Recipe 21.6 on configuring and using DataSources with servlets and JSPs on WebLogic; Recipe 21.7 and Recipe 21.8 on calling stored procedures from servlets and JSPs; Recipe 21.9 on converting a java.sql.ResultSet object to a javax.servlet.jsp.jstl.sql Result; Recipe 21.10 and Recipe 21.11 on using transactions in servlets and JSPs; Recipe 21.12 on finding out information about a ResultSet.

Recipe 23.5: Using the XML Transform Tags

Problem

You want to use the JSTL's XML and XSLT-related tags.

Solution

Use the various XML tags after declaring the tag library with the proper taglib directive (uri attribute of http://java.sun.com/jstl/xml for JSTL 1.0 or http://java.sun.com/jsp/jstl/xml for JSTL 1.1).

Discussion

A number of web site teams may already have devised stylesheets for transforming XML into HTML. In addition, you may want to separate most of the XML transformation responsibilities from JSPs, so that JSPs focus only on presenting the transformed information. The JSTL provides XML-related tags to easily integrate stylesheets into JSPs. Example 23-4 is an Extensible Stylesheet Language (XSL) document that converts an XML file into HTML. The stylesheet provides a conversion of an Ant build file similar to the one described in Recipe 23.3.

Example 23-4. The stylesheet for transforming an XML file

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="html"/>

<xsl:template match="/">

    <html><head><title>List of build.xml targets
    </title></head><body bgcolor="white"><h2>Build.xml targets</h2>

    <xsl:apply-templates />

    </body></html>

</xsl:template>

<xsl:template match="/project">

<dl>
    <xsl:for-each select="./target">

      <dt><b>
      <xsl:value-of select="@name" /></b>&#xA0;</dt>

       <xsl:if test="@depends">
       <dd>depends=<xsl:value-of select="@depends" />&#xA0;</dd>

       </xsl:if>     
   
    </xsl:for-each><!--end for-each -->
</dl>

</xsl:template>
        
<xsl:template match="text( )">
    <xsl:value-of select="normalize-space( )" />
</xsl:template>
    
 </xsl:stylesheet>

How do you apply this XSL file to the build.xml file to produce a readable format? Example 23-5 uses the x:transform tag to associate a stylesheet with an XML file. First, the JSP has to import both the stylesheet of the prior example and the XML file this stylesheet transforms by using the c:import tag. The c:import tag imports the resource specified by its url attribute and stores it in a variable (e.g., buildXml) that the x:transform tag can access.

Example 23-5. A JSP displays the result of an XSL transformation

<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="x" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<c:import url="http://localhost:8080/home/build.xml" var="buildXml" />

<c:import url="/WEB-INF/xslt/chap23.xsl" var="xslt" />

<x:transform xml="${buildXml}" xslt="${xslt}" />

The x:transform tag makes the transformation process very easy, once you've put together a valid stylesheet file. The x:transform tag's xml attribute specifies the XML file that the x:transform tag handler transforms by applying a stylesheet. The code specifies the stylesheet to use in the transformation with the x:transform tag's xslt attribute.

NOTE: The xml and xslt attributes of x:transform resolve the variables that represent the stylesheet and the XML file by using the EL, as in:

${buildXml}

Figure 23-3 shows the result of running the JSP of Example 23-5. In short, x:transform provides your very own XSLT processor for use in the JSP.

Figure 23-3
Figure 23-3. A JSP shows transformed XML content

See Also

The Jakarta Project's Taglibs site: http://jakarta.apache.org/taglibs/index.html; the Sun Microsystems JSTL information page: http://java.sun.com/products/jsp/jstl/; Recipe 23.2 on using the core tags; Recipe 23.3 on using the various XML-related tags; Recipe 23.5 on using the formatting tags; Recipe 23.6 and Recipe 23.7 on the JSTL's SQL features; Recipe 23.9-Recipe 23.14 on using the EL to access scoped variables, request headers and parameters, cookies, and JavaBean properties.

Check back here next week for more recipes from Java Servlet & JSP Cookbook. Excerpts will cover accessing an EJB from a servlet on WebLogic and connecting to Amazon Web Services (AWS) with a servlet or JSP.

Bruce W. Perry is an independent software developer and writer, and the author of Java Servlet & JSP Cookbook and just-published Ajax Hacks.


Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.