Enterprise Java Technologies Tech Tips Tips, Techniques, and Sample Code Welcome to the Enterprise Java Technologies Tech Tips for December 22, 2003. Here you'll get tips on using enterprise Java technologies and APIs, such as those in Java 2 Platform, Enterprise Edition (J2EE). This issue covers: * Introducing the J2EE 1.4 Platform * JavaServer Pages Standard Tag Library (JSTL) These tips were developed using Java 2, Enterprise Edition, v 1.4 SDK. You can download the SDK at http://java.sun.com/j2ee/1.4/download-dr.html. This issue of the Tech Tips is written by Mark Johnson, president of elucify technical communications (http://www.elucify.com/), and co-author of Designing Enterprise Applications with the J2EE Platform, 2nd Edition (http://java.sun.com/blueprints/guidelines/ designing_enterprise_applications_2e/). Mark Johnson runs an open forum for discussion of the tips at http://groups.yahoo.com/group/techtipsarchive/. You can view this issue of the Tech Tips on the Web at http://java.sun.com/developer/EJTechTips/2003/tt1222.html. See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms. You can download the sample archive for these tips at http://java.sun.com/developer/EJTechTips/download/ttdec2003.war. The context root for the application is ttdec2003, and the index.html welcome file indicates how to use the sample code. Any use of this code and/or information below is subject to the license terms at http://developers.sun.com/dispatcher.jsp?uid=6910008. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTRODUCING THE J2EE 1.4 PLATFORM On November 24, 2003, the Java Community Process committee voted unanimously to approve J2EE 1.4, the first major release of the platform in over two years. This latest release of the standardized, open platform for enterprise Java offers many new services, all of which are supported by the J2EE 1.4 SDK, now available for download. The SDK includes the J2EE 1.4 Application Server, Java 2 Platform, Standard Edition (J2SE) 1.4.2, and J2EE 1.4 code samples. You can download the entire SDK, or individually download the Application Server or the samples. The following tip presents an overview of some of the new features of the J2EE 1.4 platform. It also explains how to install the J2EE 1.4 SDK on Solaris, Windows, Linux, and Mac OS X. The overview doesn't cover everything that's new in the platform. For a more complete description of what's new in the J2EE 1.4 platform, see the J2EE v1.4 Application Server Release Notes (http://java.sun.com/j2ee/1.4/docs/relnotes/releasenotes.html). Support for Web Services The most important, and arguably most requested, feature of the J2EE 1.4 platform is end-to-end support for standards-based Web services. With J2EE 1.4, you can now make your J2EE components, such as enterprise beans and servlets, available as Web services, using SOAP (Simple Object Access Protocol) over HTTP. The J2EE 1.4 platform requires that application servers must comply with the WS-I Basic Profile 1.0, a specification that defines the transport and protocol behaviors of Web services. Compliance to WS-I ensures that Web services are interoperable. The key technologies that make Web services available in J2EE are: o Web Services for J2EE 1.1. Web Services for J2EE is the master plan for how individual J2EE technologies can be combined to create Web services. It defines the deployment contract between clients and service endpoints and their containers. A new deployment descriptor, webservices.xml, defines the deployment schema for each of these component types. Web Services for J2EE also defines the programming model (JAX-RPC), the use of JNDI to find objects that provide services, and security. Finally, it provides a new Handler object that developers can use to intercept and manipulate SOAP messages. o JAX-RPC 1.1 (Java API for XML-Remote Procedure Calls). JAX-RPC is a standardized remote procedure call interface that uses XML as a serialization protocol for method invocations and return values. JAX-RPC defines servlets and stateless session beans as service endpoints for XML Web services, based on SOAP and WSDL (Web Services Description Language). A service endpoint is the software component that actually implements the logic of a Web service. The client interface for JAX-RPC defines how remote calls to a Web service occur, and how arguments and return values (including collections) are serialized. JAX-RPC 1.1 also supports SSL-based authentication for secure Web services. o JAXR 1.0 (Java API for XML Registries). JAXR unifies different types of XML registries into a single model. Programmers use these registries to discover and look up services, and access their content and metadata. For example, you might use an application builder tool to access a registry on a particular server to find out what services that server offers, and design a SOAP client to use one of those services. JAXR also makes J2EE Web services available to external Web services clients. o SAAJ 1.2 (SOAP with Attachments API for Java). SAAJ handles transmitting SOAP messages between clients and Web services, using SOAP messages with MIME attachments. MIME attachments can be used to send either documents (for document-based Web services) or arguments with large amounts of data (for RPC-style Web services). SAAJ also defines a Document Object model for SOAP messages with attachments. It allows users control over how SOAP messages are encoded, and provides automation hooks for repetitive or complex tasks. o JAXP 1.2 (Java API for XML Parsing). This package unifies the various ways XML can be parsed and processed. Classes that perform the parsing can be switched at deploy-time or at runtime. SAX 2.0, DOM Level 2, and XSLT are included in JAXP 1.2. Web-Tier Enhancements Not all Web-tier enhancements in the J2EE 1.4 platform have to do with Web services. Existing core technologies are being updated, too. The big news in the Web tier in the J2EE 1.4 platform is in JSP (JavaServer Pages) technology version 2.0. JSTL, the JavaServer Pages Standard Tag Library, offers a wide array of general purpose tags that can greatly ease Web-tier development. JSTL also defines a new expression language that can be used to write expressions stored in Web-tier JavaBeans components in any scope. This month's second tip (see "JavaServer Pages Standard Tag Library (JSTL)") shows how to use several of these tags. Another major enhancement to JSP pages is the ability to define custom tags simply. Before JSP 2.0, defining a custom tag required writing a class that implemented the Tag interface. JSP 2.0 still offers that option, but also allows a custom tag to be defined as a JSP page fragment (defined in a JSP file), and then used in multiple places. Enterprise JavaBeans 2.1 Another important feature in J2EE 1.4 is EJB 2.1, which provides several new enhancements. These include: o Stateless session beans can be used as Web service endpoints. o A new Timer service that can be configured to periodically call an enterprise bean's ejbTimeout() method. You can take advantage of this service to periodically execute business logic. o Additions to EJB-QL, such as an ORDER BY clause for ordering result sets, and new aggregate functions (AVG, MAX, MIN, SUM, and COUNT). o Message-driven beans can now receive messages of any type, not just JMS messages (as was the case in the previous version). Now connectors can communicate directly with MDBs, using adapters that translate messages from an external system to calls on an MDB. Enterprise Java BluePrints for the J2EE 1.4 platform The Java BluePrints sample applications are an integral part of the J2EE platform. The sample applications demonstrate best practices for application design and development, providing working examples of how to use J2EE technology. The J2EE 1.4 SDK developer's release includes AdventureBuilder, the new J2EE sample application for Web services. It also includes the existing Java Pet Store and wireless gaming sample applications. Other Changes Some other important changes to the platform include: o Java Authorization Contract for Containers (JACC) 1.0: allows freedom of choice in choosing security and role-based authorization providers o Java Deployment API 1.1: separates deployment tools from the server o Java Message Service (1.1) enhancements o J2EE Connectors 1.5: includes full support for asynchronous, bidirectional, multithreaded connectors o J2EE Deployment 1.1: includes deployment descriptors defined in XML Schema instead of as a (backward-compatible) DTD o J2EE Management 1.0: manages enterprise resources, from Java and non-Java tools o New releases of JavaMail (1.3), Java Transaction API (JTA version 1.01B), and JDBC 3.0 Installing the Server Installing the new server code is simple with with the new GUI-based installer. The supported operating systems are: o Solaris SPARC 8 o Solaris SPARC 9 o Windows 2000 Pro SP3+ o Windows XP Pro SP1+ o Windows 2000 Server SP3+ o Windows Server 2003 o Linux Red Hat 8 In addition to the supported Linux Red Hat, many other Linux distributions should work with little or no modification. The major requirement for Linux installation is the Java 2 runtime, version 1.4.1 or better. To install the server code in any of the supported operating systems: 1. Download the appropriate package from http://java.sun.com/j2ee/1.4/download-dr.html 2. Run the downloaded executable It is possible to run the J2EE 1.4 SDK on Macintosh OS X or Darwin, although they are not officially supported. You must have root access to install on OS X or Darwin, and your Java Environment (JRE) must be version 1.4.1 or better. To install the J2EE 1.4 SDK on OS X or Darwin, do the following: 1. Download the Linux release of the SDK from http://java.sun.com/j2ee/1.4/download-dr.html. The file you download will be an ELF binary. 2. Use the unzip command-line utility to unzip the archive into an empty directory. You must use unzip -- programs such as StuffIt will not work. At the prompt ('$'), enter: $ unzip j2eesdk-1_4-dr-linux-eval 3. Start the installer. Enter: $ java -cp package/PackageFormat.jar:. appserv The installer will start and will install the SDK. You might need to occasionally resize a window if you can't read its contents. 4. The installation program will ask you for the location of Java. Enter: /Library/Java/Home The installer will prompt with a warning that the server requires JDK 1.4.2. Java 2 version 1.4.1 will work properly, so select . 5. After installation, you must perform a few extra steps. The first step is to change some permissions in the imq/bin directory of the installation. Enter: $ chmod a+x /Users/yourname/SUNWappserver/imq/bin where yourname is your user name. (This procedure assumes that you installed the server in /Users/yourname.) 6. The final step requires root access. The server looks for java and javac in /Library/Java/Home/jre/bin which does not yet exist. You must create this directory, and create symbolic links to the binaries for these programs. Enter: $ sudo mkdir -p /Library/Java/Home/jre/bin $ cd /Library/Java/Home/jre/bin $ sudo ln -s /Library/Java/Home/bin/java java $ sudo ln -s /Library/Java/Home/bin/javac javac The sudo program will request your password the first time you run it. If you are not an administrator, you must log on as root or su to root to complete these tasks. 7. Installation is now complete. To start the application server, enter: $ cd /Users/yourname/SUNWappserver/bin $ asadmin start-domain - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - JAVASERVER PAGES STANDARD TAG LIBRARY (JSTL) For several years, people have been writing their own custom tags to implement display logic in their JSP pages. Several popular tag libraries have been built that perform iterations, process XML, call auxiliary functions, and access Web-tier JavaBeans. There's a lot of overlap in the functionality of these libraries, yet they are incompatible with one another. To help overcome these incompatibilities, the Java Community Process has come to consensus on a common set of logic and display tags. These tags are generally useful for creating views in Web applications. The new tag set is called JSTL, the JavaServer Pages Standard Tag Library. JSTL is not a required part of the J2EE 1.4 platform, and so application server vendors are not required to support it. Nevertheless, it is included with the J2EE 1.4 SDK from Sun, and other vendors are also likely to support it. JSTL is not all that new -- JSTL 1.0 has been available for J2EE 1.3 containers for quite some time. The JSTL 1.1 maintenance release upgrades JSTL to take advantage of new features in JSP 2.0 and the J2EE 1.4 platform. This tip explains how to use several of the new JSTL tags. To use these tags, you first need to understand the new JSP Expression Language (EL). JSP Expression Language The basic idea underlying JSTL is that most data formatted by a JSP page is available in the JSP page's state. The state includes: o Objects in page, request, session, or application scope o Request parameters o JSP implicit objects such as pageContext o HTTP headers, cookies, and request parameters o Servlet context initialization parameters A complete list of the data available for use by a JSP page appears on the page titled "Expression Language" (http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html) in the "Implicit Objects" section of the J2EE 1.4 Tutorial. User-defined JavaBeans (either classic JavaBeans or references to Enterprise Beans) can be bound to state variables in any scope. You only need to use the tag if you're creating new beans on that page with a scriptlet. Otherwise, you can access any beans by name in EL expressions. The JSP 2.0 expression language uses the JavaBeans naming scheme to navigate between connected beans. The language also defines a syntax for expressions that can be used in any JSP tag. The JSP page compiler evaluates as an expression anything in a JSP page between the delimiters ${ and }. The easiest way to explain how JSP expressions work is by example, so let's look at an example in the sample code that accompanies this tip. Sample Code The sample code is a Web application that uses two classic JavaBeans. The ColorScheme JavaBean is a Map that has color names as its keys, and ColorBean objects as its values. A ColorBean has a name (by which it is registered in the ColorScheme), and red, green, and blue color components. ColorScheme is derived from javax.util.TreeMap. Iterating over the ColorScheme retrieves all of its ColorBeans in order by name. ColorBean is derived from java.awt.Color, so all of its inherited methods (and therefore, JavaBeans properties) are available from JSP EL. The welcome page of the application, index.jsp, populates a ColorScheme object with several hundred ColorBean objects. The data for the objects comes from a text file (rgb.txt) in the Web archive. The data in the files has the following format: R G B Name 240 248 255 AliceBlue A scriptlet at the top of index.jsp initializes the ColorScheme bean, and stores it in session state under the name "scheme", as follows: <% // Open a stream to the init file InputStream stream = application.getResourceAsStream("/rgb.txt"); // Get a reference to the scheme bean ColorScheme colorScheme = (ColorScheme)pageContext.findAttribute( "scheme"); // Load colors from stream try { colorScheme.load(stream); } catch (IOException iox) { throw new JspException(iox); } %> (Note that this application would be better off using a tag file -- a new JSP 2.0 feature -- instead of a scriplet. Tag files will be covered in a subsequent edition of the Enterprise Java Technologies Tech Tips.) The code above is a typical use of the body of a tag to initialize the bean that the tag creates. Other JSP pages can format the data in the scheme bean after index.jsp has initialized it and placed it in session scope. A JSP page that prints the size of the ColorScheme collection might look something like this: <% ColorScheme scheme = (ColorScheme)session.getAttribute("scheme"); out.println("The current color scheme has " + scheme.size() + " colors."); %> Using JSTL and the JSP expression language, this task is much simpler, as well as more readable. The sample page Count.jsp does it this way: <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> The current color scheme has ${fn:length(scheme)} colors. The first line defines the prefix fn for tags in the JSTL functions package (see the Tutorial for more information on this package). The second line is template text that includes an expression ${fn:length(scheme)}. At runtime, the JSP page replaces this expression with the length of the scheme object. Because scheme is a Map, length returns the number of items in the map. The length function works for all Collection types. A more interesting example is the sample page ListColorNames.jsp, which lists the names of all of the colors in the ColorScheme bean: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> This is a list of the names of all of the colors in the current color scheme:
  1. ${entry.key}
The <%@taglib%> line defines c as the prefix for JSTL Core tags. The rest of the page defines an ordered list. It uses to iterate over all of the entries in the scheme collection. The forEach tag works for all Collection classes. It successively assigns the page variable whose name is given in the var attribute to each of the values in the collection. When the value of the expression in the forEach tag's items attribute is a java.util.Map, the variable named in var is set to items of type java.util.Map.Entry. In this case, the iterator variable is called entry, so the name of the key is retrieved using the expression ${entry.key}. You'll see in the next example that the value for each entry could be accessed using the expression ${entry.value}. This is because a java.util.Map.Entry object has methods getKey and getValue, and the expression language follows the JavaBeans naming convention. In general, an expression such as ${a.b.c.d} in a JSP EL expression is executed in code as a.getB().getC().getD(). Expressions of this type are shorthand for successive calls to JavaBeans property accessors. The sample page ShowColors.jsp actually shows the colors contained in the scheme, as follows: This table demonstrates all of the colors in the current scheme. This example uses the as before. The two tags set the page attributes color and name to the hex representation of the color, and the color's name, respectively. Following the JavaBeans naming convention, the line: is equivalent to the Java code ColorBean cb = (ColorBean)entry.getValue(); pageContext.setAttribute("color", cb.getRgbHex()); The color and name variables are used in the template text to create the table rows in the JSP page output. There is no tag, because the value of an EL variable can always be referenced as an expression, like ${color}. The final sample page, ColorNameGrid.jsp, shows even more of the power of JSTL tags. It demonstrates how to use JSTL tags to: o Access request parameters o Perform conditional output two different ways o Use EL comparison and operators o Use EL arithmetic functions ColorNameGrid.jsp prints the names of all of the colors in the ColorScheme as a multi-column table. The number of columns can range from 1 to 10, indicated by the request parameter cols. Out-of-range values produce an error message. The code for the ColorNameGrid.jsp page looks like this: This is a grid of the names of all of the colors in the current color scheme:

NameSample TextColor Swatch Hex CodeOpposite Color
${name} ${name} ${name} ${color} ${name}
${entry.key}
${cols} is an unreasonable number of columns.

Click here to try again. The first tag retrieves the request parameter cols, and places it in a page attribute (also called cols), as shown here: (This page could have done without the cols page attribute, using ${param['cols']} everywhere. Defining the page attribute makes the page a bit more readable.) The next tag initializes the col page attribute to the value 1. This variable will be used to break columns. The tag works somewhat like an if-else statement in Java. The tags work like if and else if statements, and the tag works like a final else. The tag contains a series of tags, each of which has a test attribute that contains an expression. The body of the first tag whose test expression evaluates to true, is evaluated and included in the output. If none of the test expressions evaluate to true, the body of the tag is evaluated and directed to output instead. In this case, the test expression for the first tag is a logical expression: The cols variable used here is the page attribute defined in the first tag discussed above. If the number of columns requested is between 1 and 10, the page produces a table of colors. Otherwise (in the tag), the pages displays a complaint: ${cols} is an unreasonable number of columns.

Click here to try again. Inside the body of the first tag is the code that creates the table. The tag iterates over all of the colors in the table, assigning the page attribute color to each ColorBean in the ColorScheme: Each color name is printed in the color it represents, using an expression (${color.rgbHex}) to get the color's hex representation from the color bean. At the end of the loop, the col variable is incremented, so that line breaking works properly: Finally, the loop forces a line break each time it comes to the end of a column, using an arithmetic expression and the tag . These examples merely scratch the surface of what JSTL tags can do. JSTL tags exist for processing URLs, forwarding requests, including content from other Web resources, processing XML, creating internationalized context, executing SQL queries, and more. Use the powerful new tools in JSTL to supercharge your JSP development efforts. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RUNNING THE SAMPLE CODE Download the sample archive for these tips (from http://java.sun.com/jdc/EJTechTips/download/ttdec2003.war). The application's context root is ttdec2003. The downloaded war file also contains the complete source code for the sample. You can deploy the application archive (ttdec2003.war) on the J2EE 1.4 Application Server using the deploytool program or the admin console. You can also deploy it by issuing the asadmin command as follows: asadmin deploy install_dir/ttdec2003.war Replace install_dir with the directory in which you installed the war file. You can access the application at http://localhost:8000/ttdec2003. For a J2EE 1.4-compliant implementation other than the J2EE 1.4 Application Server, use your J2EE product's deployment tools to deploy the application on your platform. . . . . . . . . . . . . . . . . . . . . . . . IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies: http://www.sun.com/share/text/termsofuse.html http://www.sun.com/privacy/ http://developers.sun.com/dispatcher.jsp?uid=6910008 * FEEDBACK Comments? Send your feedback on the Enterprise Java Technologies Tech Tips to: http://developers.sun.com/contact/feedback.jsp?category=sdn * SUBSCRIBE/UNSUBSCRIBE Subscribe to other Java developer Tech Tips: - Core Java Technologies Tech Tips. Get tips on using core Java technologies and APIs, such as those in the Java 2 Platform, Standard Edition (J2SE). - Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME). To subscribe to these and other JDC publications: - Go to the JDC Newsletters and Publications page, (https://softwarereg.sun.com/registration/developer/en_US/subscriptions), choose the newsletters you want to subscribe to and click "Update". - To unsubscribe, go to the subscriptions page, (https://softwarereg.sun.com/registration/developer/en_US/subscriptions), uncheck the appropriate checkbox, and click "Update". - To use our one-click unsubscribe facility, see the link at the end of this email: - ARCHIVES You'll find the Enterprise Java Technologies Tech Tips archives at: http://developer.java.sun.com/developer/EJTechTips/index.html - Copyright 1994-2004 Sun Microsystems, Inc. All rights reserved. 901 San Antonio Road, Palo Alto, California 94303 USA. This document is protected by Copyright 1994-2004 Sun Microsystems, Inc. in the United States and other countries.