JRun30TagLibraryTechBriefv2.pdf

JRun Tag Library
White Paper
Allaire Corporation
ii
JRun Tag Library White Paper
© 2000 Allaire Corporation. All rights reserved.
This manual, as well as the software described in it, is furnished under license and may be used
or copied only in accordance with the terms of such license. The content of this manual is
furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Allaire Corporation. Allaire Corporation assumes no
responsibility or liability for any errors or inaccuracies that may appear in this book.
Except as permitted by such license, no part of this publication may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, electronic, mechanical, recording,
or otherwise, without the prior written permission of Allaire Corporation.
ColdFusion and HomeSite are federally registered trademark of Allaire Corporation. Allaire,
Allaire Spectra, JRun, <CF_Anywhere>, the ColdFusion logo, the JRun logo, and the Allaire
logo are trademarks of Allaire Corporation in the USA and other countries. MacOS is a
trademark of Apple Computers Inc. Microsoft, Windows, Windows NT, Windows 95, Microsoft
Access, and FoxPro are registered trademarks of Microsoft Corporation. Java, JavaBeans,
JavaServer, JavaServer Pages, JavaScript, JDK, Java Servlets, Java Community Process and
Solaris are trademarks of Sun Microsystems Inc. UNIX is a trademark of The Open Group.
PostScript is a trademark of Adobe Systems Inc. All other products or name brands are the
trademarks of their respective holders.
Revision 1, August, 2000
Part number: AA-JRTAG-WP
JRun Tag Library White Paper
iii
Contents
Executive Summary..................................................................................................................... 5
History of Servlets and JSP ......................................................................................................... 6
Java Servlets — The Foundation.............................................................................................. 6
JSP 1.0 — A New Approach to Servlet Programming............................................................. 9
JSP 1.1 — Introducing Custom Tags ..................................................................................... 12
Conclusion.............................................................................................................................. 13
JRun Tag Library Design Principles.......................................................................................... 13
Tag Abstractions..................................................................................................................... 14
Ease of Use ............................................................................................................................. 14
Portability ............................................................................................................................... 14
Support for Industry Standards............................................................................................... 14
Vendor-Independent Hooks.................................................................................................... 14
JRun Tag Offerings.................................................................................................................... 15
JRun Tag Summary ................................................................................................................ 15
J2EE Technologies: JNDI and JavaMail Coding Examples .................................................. 16
Client-Side Form Processing: A Coding Example ................................................................. 17
Flow Control: A Coding Example.......................................................................................... 18
JSP Standard Tag Library Reference Implementation............................................................... 19
JSP Authoring Tools Support .................................................................................................... 19
JRun Studio ............................................................................................................................ 20
The Future of Tag-Based Programming .................................................................................... 21
Summary.................................................................................................................................... 22
White Paper
JRun Tag Library
Executive Summary
The JavaServer Pages (JSP) 1.1 specification provides a standard, XML-based
interface for defining a tag library within JSP. Tag libraries based on this interface
will provide for faster development than with traditional JSP code, and will open
JSP development to a broader audience of developers.
Allaire has released the JRun Tag Library with JRun 3.0 using these JSP tag
extensions. This library empowers developers to integrate Java 2 Enterprise
Edition (J2EE) functionality effortlessly into any HTML document without writing
a single line of Java code.
The JRun Tag Library enables a wide spectrum of functions, including:
•
Database queries
•
Transactions
•
Asynchronous message sending and receiving
•
E-mail processing
•
XML transformations
•
Java Naming and Directory Interface (JNDI) resource lookups
While sophisticated and powerful, JRun’s custom tags are very simple and elegant
mechanisms to generate presentation code for any Web browser, wireless device,
or PDA.
The JRun Tag Library is the industry’s most comprehensive, freely available tag
library. It is highly extensible and easy to use, ensuring a high level of productivity
among all participants involved with developing a Web application.
Allaire is an active member of the Java standards committees, and dedicated to the
ongoing evolution of JSP to include innovative new authoring and deployment
technologies. The JRun Tag Library has been submitted to Sun Microsystems for
consideration as the reference implementation for the standard tag library
extension.
6
JRun Tag Library White Paper
History of Servlets and JSP
Java Servlets — The Foundation
In 1998, Sun Microsystems first released the Java Servlet API. Soon afterwards,
Live Software (now part of the Allaire) released JRun, the first servlet engine
implementation other than the reference implementation provided by Sun.
Java has been very well received as an Internet programming language, mainly due
to its productivity, scalability and flexibility. Java programs are easier to develop
and test, taking a fraction of the time required to write a similar application in C++.
Java is a true object-oriented language with extensive support for component-based
development. It is platform independent and thrives in heterogeneous computing
environments like the Internet.
Java servlets refer to the part the language that deals with developing interactive
Web applications. There are numerous other technologies that provide similar
functionality, including Allaire’s ColdFusion Server, Microsoft Active Server
Pages (ASP), and CGI/perl. The primary advantages of Java servlets include
application portability across platforms and Web servers, browser compatibility,
efficient memory management, fast execution, and virtually unlimited
extensibility. The feature set includes session tracking, robust security, and
universal database access via JDBC.
A typical servlet performs interactive operations, such as searching databases for
some information provided by a user via an HTML form, and returns the results to
the client’s Web browser. In this section, a servlet is presented that searches a
database for a particular user’s appointment schedule. When the user presses the
Search! button (Figure 1), the servlet (Listing 2) is invoked.
Figure 1: A typical Web application
Listing 1 shows the corresponding HTML code for Figure 1.
Listing 1: HTML code that invokes a Java servlet
<HTML>
<HEAD><TITLE>Appointment Schedule</TITLE></HEAD>
<BODY>
<B>See your appointment schedule:</B><BR>
<FORM METHOD="GET" ACTION="/servlet/ViewAppointmentServlet">
Enter your Name: <INPUT TYPE="text" NAME="username"/><BR>
<INPUT TYPE="submit" VALUE="Search!"/>
</FORM>
</BODY>
</HTML>
Finally, the servlet code is written and compiled in Java. It is then placed on a Java
server, such as JRun 3.0. Listing 2 shows the servlet.
JRun Tag Library White Paper
Listing 2: A servlet that searches a database for a user’s appointment
schedule
import
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.sql.*;
java.util.*;
// A Servlet that checks a database for a user's appointment schedule.
// For illustrative purposes only, no robust error checking or
// user authentication.
public class ViewAppointmentServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
// the doGet() method is invoked by a remote user.
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// determine the parameters from the HTTP request.
String userName = req.getParameter("username");
// open output-stream to client for response.
resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());
// connect to database
Connection con = null;
try {
// Load your JDBC driver class file
Class.forName("MyDatabaseDriver");
// Connect to the ODBC "Appointments" datasource,
// no username or password.
con = DriverManager.getConnection("Appointments","", "");
// Create and Execute a query
String queryString = "";
queryString += ("SELECT Date, StartTime, EndTime, Name ");
queryString += ("FROM Appointments ");
queryString += ("WHERE UserName = '" +userName+ "' ");
queryString += ("ORDER BY StartTime;");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(queryString);
// create an HTML table.
out.println("<HTML>");
out.println("<HEAD><TITLE>Appointment Schedule</TITLE></HEAD>");
out.println("<BODY>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>Date</TD>");
out.println("<TD>Start Time</TD>");
out.println("<TD>End Time</TD>");
out.println("<TD>Name</TD>");
out.println("</TR>");
// iterate through the ResultSet.
while (rs.next()) {
out.println("<TR>");
out.println("<TD>" + rs.getString("Date") + "</TD>");
out.println("<TD>" + rs.getString("StartTime") + "</TD>");
out.println("<TD>" + rs.getString("EndTime") + "</TD>");
out.println("<TD>" + rs.getString("Name") + "</TD>");
out.println("</TR>");
7
8
JRun Tag Library White Paper
}
out.println("</TABLE></BODY></HTML>");
}
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
} // end of finally block
} // end of doGet()
//EOF
While servlets offer tremendous functionality, developers without Java
programming experience may find Java servlet coding clumsy for HTML-based
output. Shortcomings of programming Java servlets include:
•
A considerable amount of code is required to accomplish a common task
•
The code itself is not manageable when it includes large amounts of
presentation code.
Notice that all of the presentation logic (HTML code) is embedded within the
application logic (Java code). Thus, in order to make even the slightest change to
the presentation of the Web application’s output (Figure 2), the developer must
modify the Java source files directly, manually recompile them, and upload the
files to the server. The mingling of presentation and business logic represents poor
design practice. It limits code reusability and complicates the distribution of
development tasks between graphics/layout design and business logic
development.
Figure 2: Possible output for an appointment Web application
A typical e-commerce application consists of hundreds of pages of frequently
changing content. Typical roles of people involved with Web application creation
include content writers, layout editors, graphic artists, and software engineers. The
original servlet design paradigm requires that any modifications be performed on
the Java source files, and thus assumes that all project participants are proficient in
Java programming, which is often not the case. Sun Microsystems recognized this
limitation stating, “JSP technology should be viewed as the norm while the use of
JRun Tag Library White Paper
9
Servlets will most likely be the exception.” (Section 1.9, December 15, 1999, Draft
Release)
JSP 1.0 — A New Approach to Servlet Programming
JSP allows developers to write servlets inside out. Instead of writing Java code
natively and encapsulating HTML, as in a traditional servlet, JSP pages include
HTML natively and encapsulate the Java code. It is important to realize, however,
that the underlying servlet technologies remain largely unchanged.
A JSP file is simply an HTML file that allows snippets of Java code to be placed
within special <% %> tag delimiters. At run time, a page compiler evaluates the JSP
page and automatically generates a servlet. An oversimplified way to visualize this
page-compilation process is to scan through a JSP file visually, place any HTML
statements encountered into the out.println(“ … ”); method, and strip away the <%
%> tags. In the end, you are left with a Java file, which is then transparently
compiled into a servlet by the JSP server.
Using JSP, you can further separate presentation and business logic through
JavaBeans technology. For the purposes of this discussion, a JavaBean is a
standard Java class definition that performs a task. To qualify as a JavaBean, the
following minimum requirements must be fulfilled:
•
It must has private data members, each with its own pair of standard accessor
(get) and mutator (set) methods for every data member.
•
It must implement the java.io.Serializable interface.
The code in Listing 3 is the same Web application of the previous sections but
written slightly differently. It searches a database for an appointment schedule and
then outputs the results to a Web browser. However, the JSP programming
paradigm is used this time. The application consists of two files,
AppointmentBean.java (Listing 3), which is a JavaBean that contains the business
logic, and Appointments.jsp (Listing 5), which contains the presentation logic, as
well as some Java code required to coordinate with AppointmentBean.java. Listing
4 shows the HTML behind the form.
Listing 3: AppointmentBean.java, a JavaBean that queries a database
import java.io.*;
import java.sql.*;
import java.util.*;
// A JavaBean that searches a database. For use in JavaServer Pages.
// For illustrative purposes only, non-robust error checking and
// security measures.
public class AppointmentBean implements Serializable {
private String userName = "";
public AppointmentBean() {}
// only accessible through accessor
// and mutator methods.
// a no argument constructor
// Required accessor and mutator methods for the userName property
public String getUserName() {return userName;}
public void setUserName(String sz) {userName = sz;}
// Finds appointments for a particular user from a database
public ResultSet executeQuery() {
// connect to database
Connection con = null;
ResultSet rs = null;
10
JRun Tag Library White Paper
try {
// Load your JDBC Driver class file
Class.forName("MyDatabaseDriver");
// Connect to the ODBC "Appointments" datasource,
// no username or password.
con = DriverManager.getConnection("Appointments","", "");
// Create and Execute a query
String queryString = ("SELECT Date, StartTime, EndTime, PatientName");
queryString += (" FROM Appointments ");
queryString += ("WHERE UserName = '" +userName+ "' ");
queryString += ("ORDER BY StartTime;");
Statement stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
}
} // end of finally block
return rs; // the ResultSet is sent back to the JSP page context.
} // end of executeQuery
} //EOF
The JavaBean in Listing 3 performs a well-defined task. It has one method,
executeQuery(), which searches a database via JDBC and returns a ResultSet to
the caller. This JavaBean is used behind the scenes by the JSP file of Listing 5 to
handle the business logic of the application, that is, connecting to a database and
executing a query. In order to get things started, the HTML form in Listing 4
prompts the user for his or her name. Notice that it is the same form as Listing 1,
except that the Form’s ACTION invokes the Appointments.jsp file instead.
Listing 4: HTML code that invokes a JSP file
<HTML>
<HEAD><TITLE>Appointment Schedule</TITLE></HEAD>
<BODY>
<FORM METHOD="GET" ACTION="/Appointments.jsp">
Enter your Name: <INPUT TYPE="text" NAME="username"/><BR>
<INPUT TYPE="submit" VALUE="Search!"/>
</FORM>
</BODY>
</HTML>
The JSP file shown in Listing 5 looks very similar to a regular HTML file except
for some additional <% %> tags that contain Java code. Line numbers are added for
convenience. This file uses the JavaBean of Listing 3 to create dynamic Web
content.
Listing 5: Appointments.jsp, a JSP file that displays appointments
JRun Tag Library White Paper
11
1)
2)
3)
4)
<HTML>
<HEAD>
<TITLE>Appointment ScheduleTITLE>
</HEAD>
5)
6)
<%@ page language="java" import="java.sql.*,AppointmentBean" %>
<jsp:useBean id="apptbean" scope="session" class="AppointmentBean" />
7)
8)
<H3>Today's Appointments:</H3><BR>
<B>The following are your appointments:</B><BR>
9)
10)
11)
12)
13)
14)
15)
<TABLE>
<TR>
<TD><B>Date:</B></TD>
<TD><B>Start Time:</B></TD>
<TD><B>End Time:</B></TD>
<TD><B>Patient Name:</B></TD>
</TR>
16)
17)
18)
19)
20)
21)
22)
23)
<!-- Get the appointment information -->
<%! ResultSet rs; %>
<% apptbean.setUserName(request.getParameter("username"));
rs = apptbean.executeQuery(); %>
<%
while (rs.next())
{
%>
24)
25)
25)
27)
28)
29)
<TR>
<TD><B><%=
<TD><B><%=
<TD><B><%=
<TD><B><%=
</TR>
rs.getString("Date") %></B></TD>
rs.getString("StartTime") %></B></TD>
rs.getString("EndTime") %></B></TD>
rs.getString("PatientName") %></B></TD>
30) <%
31)
}
32)
rs.close();
33) %>
34) </TABLE>
35) </BODY>
36) </HTML>
The following paragraphs explain the code in Listing 5:
•
Line 5 (<%@ page language="java" import="java.sql.*,AppointmentBean" %>)
is a page directive that declares the language to be Java and imports the
necessary supporting class files. Note that JRun 3.0 has support for JavaScript
as the JSP scripting language, so one need not even learn Java to write JSP.
This would be accomplished by alternatively specifying
language="javascript".
•
Line 6 (<jsp:useBean
id="apptbean" scope="session"
class="AppointmentBean" />)
calls the constructor for the AppointmentBean of
Listing 3, the resulting object has session scope and will be referred to
throughout the JSP page (as well as this discussion) as apptbean.
•
Line 18 (<% apptbean.setUserName(request.getParameter("username"));) sets
the value of the apptbean.username property to whatever value was typed into
the HTML form’s “username” input when the submit button was pressed.
•
Line 19 invokes the apptbean.executeQuery(); method and associates the
return value to the ResultSet reference declared in Line 17.
•
Lines 20-23 and 30-33 utilize flow control statements to iterate through the
ResultSet object
12
JRun Tag Library White Paper
•
Lines 25-28 inline the return value of the getString(“…”) methods invoked on
the ResultSet object.
The JSP specification is quite helpful because it empowers software engineers to
architect a Web application framework that is more independent of the
presentation logic. Layout editors and Java programmers don’t necessarily work on
the same files. JavaBeans encapsulate the majority of business logic code needed
by the JSP page but still leave hooks behind. In addition, it requires a considerable
amount of code to accomplish a very common task.
While JSP’s separation of the presentation logic from the business logic was a
significant improvement over the servlet programming approach, placing Java
code fragments and JavaBean calls inside the HTML can be almost as awkward.
Further refinements were still needed to the JSP 1.0 specification.
JSP 1.1 — Introducing Custom Tags
The most recent JSP 1.1 specification, released in November or 1999, introduces
the idea of custom tags. This idea, while new to Java, has been central to Allaire’s
software architecture since the 1995 launch of ColdFusion, the first tag-based
Internet programming language. A custom tag can be thought of as combining the
advanced functionality of servlets with the ease of use and maintainability of
ColdFusion.
Internally, custom tags utilize developer-written tag handlers; JSP developers
simply code the custom tag, passing the appropriate attributes. As the JSP page
compiler parses through the JSP page and encounters a custom tag, it calls the
appropriate tag handler, such as doStartTag and doEndTag. Custom tags allow the
lengthy appointment-searching Web application to be rewritten as shown in Listing
6.
Listing 6: A JavaServer Page using the JRun Tag Library
1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15)
16)
17)
<%@ taglib uri="jruntags" prefix="customtag" %>
<customtag:sql datasrc="source" id="x">
SELECT Date, StartTime, EndTime, PatientName
FROM Appointments
Where UserName =’<%= request.getParameter("username") %>’
</customtag:sql>
<customtag:param id="x" type="allaire.taglib.QueryTable"/>
<TABLE>
<customtag:foreach group="<%= x %>">
<TR>
<TD><%= x.get("Date") %></TD>
<TD><%= x.get("StartTime") %></TD>
<TD><%= x.get("EndTime") %></TD>
<TD><%= x.get("Name") %></TD>
</TR>
</customtag:foreach>
</TABLE>
This program provides the same functionality shown in the preceding two
examples. Yet it is shorter, more elegant, and requires no Java code.The following
paragraphs explain the code in Listing 6:
•
Line 1 (<%@ taglib uri="jruntags" prefix="customtag" %>) instructs the page
compiler to use the jruntags library and will refer to them throughout the page
using the customtag prefix.
•
Line 2 (<customtag:sql datasrc="Appointments" id="x">) instructs the JSP
page compiler to invoke the sql tag (actually, the doStartTag method of the sql
tag), which is a class file in the jruntags library. (Remember that the customtag
JRun Tag Library White Paper
13
prefix refers to the jruntags library.) It then specifies the JRun data source as
being Appointments and declares that the ResultSet returned by the method call
be stored in a page variable (of unknown type) known as x. The variable x
exists throughout the context of the JSP page. Note that the data source must
have been defined as a JRun data source for the associated JRun server (using
the JMC). Alternatively, you can pass an instance of java.sql.DataSource.
•
Lines 3-5 contain the SQL query, wrapped between the opening and closing
<customtag:sql> tags. Note that <%= request.getParameter("username") %>
returns the value of the username parameter, which was originally entered in
the HTML form.
•
Line 6 (</customtag:sql> instructs the JSP page compiler to call the doEndTag
method of the sql tag.
•
Line 7 (<customtag:param id="x" type="allaire.taglib.QueryTable"/>) uses
the param tag to perform a type cast. The variable x is cast to a QueryTable
object, which is an enumeration object provided with the JRun Tag Library. In
general, the param tag defines scripting variables in different scopes (page,
request, session, or application) that can be accessed by other custom tags
from the pageContext object.
•
Lines 9-16 (<customtag:foreach group="<%= x %>">) use the foreach flow
control tag, which is considerably more elegant than littering opening and
closing braces, such as <% while rs.next) { %>, throughout the JSP page. The
tag directs that, for each row in the QueryTable object x, a new HTML table
row with columns for x.get("Date") (the date), x.get("StartTime") (the start
time), x.get("EndTime") (the end time), and x.get("Name") (the name) should
be printed out. Finally, upon encountering the closing </customtag:foreach>
tag, the page compiler will loop back to line 9 if there are more rows left in the
QueryTable object or continue to line 17 if there are no rows left to be
processed.
Conclusion
The JRun Tag Library abstracts Java functionality by defining an HTML-like, tagbased language that enables a more natural use of that functionality within JSP
pages. The Tag Library solves a problem that many JSP developers encounter:
writing multiple Java code fragments inside JSP pages makes them difficult to read
and maintain. The JSP custom tag approach solves this fundamental problem by
providing a tag-based look and feel that is familiar to any Web page designer,
regardless of his or her Java programming skill level. The JRun Tag Library
dramatically reduces the time required to author routine tasks like database access,
thus reducing time to market and lowering development costs. The high level of
abstraction also translates into reduced maintenance cost by virtue of having
substantially fewer lines of code to maintain.
JRun Tag Library Design Principles
The JSP 1.1 specification outlines certain practices that must be adopted when
developing custom tag libraries. The JRun Tag Library adheres to the following
design objectives, which comply with those recommended by the JSP 1.1
specification.
14
JRun Tag Library White Paper
Tag Abstractions
In order to maximize productivity, a tag extension library must provide
abstractions to all of the most commonly performed server-side tasks, including
database queries and ResultSet processing. Without tag extensions, a JSP
developer would be required to write JDBC code in a Java scriptlet or JavaBean to
perform the required database query. This would result in lengthy and error-prone
development cycles.
A tag library should be designed so that a JSP developer can perform common
tasks without writing any Java code. The J2EE specification outlines the most
commonly used Java APIs for Web application development. Therefore, it would
be natural to fill the gap between JSP and various J2EE APIs by using JSP tag
abstractions.
Ease of Use
The tag syntax must be simple and easy to understand. However, a tag abstraction
cannot cover every aspect that a particular Java API addresses. A custom tag
designer must strike a balance between providing tags that are broad enough to
cover the most important parts of an API while providing a simple and easy-tounderstand tag syntax.
Portability
The JSP specification ensures that JavaServer Pages will work exactly the same
way if deployed in JSP containers from different vendors. Since a standard tag
library is yet to be finalized, it is very important to design and implement a tag
library that strictly conforms to the official J2EE requirements for maximum
portability.
Support for Industry Standards
A tag library should be designed and implemented to be highly compatible with
existing standard Java APIs. This helps to ensure maximum portability.
Vendor-Independent Hooks
The Sun Microsystems Java model is based on different vendors trying to write the
best possible implementations for an agreed-upon specification, thus allowing for
best-of-breed solutions. As a result of this, some Java application servers perform
better in certain areas than the others.
Since custom tags execute on top of an application server infrastructure, it is very
important to define and implement a tag library so that custom tags can take full
advantage of an application server’s strengths. This also opens up competition
among application server vendors when such a tag library is used on these servers
because a custom tag could actually run faster on one server than on another.
Tag implementations should expose the real performance of an application server,
rather than attempt to satisfy the lowest common denominator of all Java
application servers. One example is to allow the use of database connection
pooling and ResultSet caching, if such features are available in a server.
JRun Tag Library White Paper
15
JRun Tag Offerings
JRun Tag Summary
The JRun Tag Library can be categorized into the following main areas:
•
J2EE technologies
•
Client-side form processing
•
Flow control
The following is a summary of the JRun Tag Library. Several examples from each
of the above tag categories will be discussed in detail. For more information
regarding the usage of a particular tag, consult the JRun Tag Library Reference,
which is included in the docs/pdf directory of JRun Server 3.0 as taglib.pdf. The
tag handler class files are included in a jruntags.jar file, which includes a Tag
Library Descriptor (TLD) file as specified in the JSP 1.1 specification. You can
find this .jar file in jruninstalldirectory/servers/lib. For more information on
coding your own tag library, refer to Developing Applications with JRun.
Tag Name
Description
Sql
Performs database queries
SqlParam
Used with SQL to construct SQL statements dynamically
SendMsg
Sends asynchronous messages
MsgParam
Used with sendmsg to set message properties
GetMsg
Receives asynchronous messages
Transaction
Supports distributed transactions
Jndi
Looks up objects and directories on a network (for example,
EJB, LDAP, and CORBA)
SendMail
Sends e-mail messages
MailParam
Used with sendmail to construct multipart e-mails
GetMail
Receives e-mail messages
Servlet
Invokes Java servlets
ServletParam
Used with servlet to set servlet attributes
Query2Xml
Converts database query results into XML documents
Xslt
Performs XSLT transformations
Form
Generates an HTML <form> with client-side JavaScript for
form validation
Input
Generates HTML <input> statements with client-side
JavaScript for input field validation
Select
Generates HTML <select> and <option> input types with
optional client-side JavaScript for selection validation
Param
Declares scripting variables
ForEach
Loops over an enumeration of objects
If
Performs conditional block execution
Switch
Performs conditional block execution similar to switch-case
construct in Java
16
JRun Tag Library White Paper
Tag Name
Description
Case
Used with switch to perform conditional block execution
J2EE Technologies: JNDI and JavaMail Coding Examples
The JRun Tag Library provides numerous tags for providing easy access to
advanced J2EE functionality, including SQL, JDBC, JNDI, and JavaMail.
Note
Refer to “JSP 1.1 — Introducing Custom Tags” for a complete example of
the sql database query tag. The sql tag will be one of the most widely used
custom tags.
In this section, the JNDI resource lookup will be presented. The code shown in
Listing 7 prints out all of the JDBC data sources available on a particular server.
Listing 7: Available JDBC data sources
1)
2)
3)
4)
5)
6)
<%@ taglib uri=”jruntags” prefix=”jrun” %>
<jrun:jndi action="list" name="java:comp/env/jdbc" id="obj"/>
<jrun:param id="obj" type="NameTable"/>
<jrun:foreach group="obj">
<%= obj.Name %>
</jrun:foreach>
The following paragraphs explain the code in Listing 7:
•
Line 2 performs the requested JNDI resource listing and stores the result in a
page context variable called obj.
•
Line 3 invokes the param tag, which causes the JSP compiler to cast obj into a
NameTable object. To help understand what is happening, the code generated by
the page compiler after processing Line 3 would look like this:
NameTable obj =(NameTable)PageContext.getAttribute(“obj”);
•
Lines 4-6 iterate through the NameTable object using the foreach tag.
It is difficult to imagine a Web-based application that doesn’t incorporate the use
of e-mail. Based on the JavaMail API, the JRun Tag Library offers sendmail and
getmail tags for sending and receiving of e-mails. Listing 8 shows an example of
this.
Listing 8: Sending E-Mail from a JSP Page
<%@ taglib uri=”jruntags” prefix=”jrun” %>
<jrun:sendmail host=”mail.yourserver.com”
sender=”[email protected]”
recipient=”[email protected]”
cc=”[email protected]”
subject=”The JRun Tag Library!”>
The JRun Tag Library makes sending and receiving e-mail easy!
</jrun:sendmail>
The code in Listing 8 sends the text that appears between opening and closing
sendmail tags to the addresses specified as parameters in the opening tag. A more
interesting example would be to combine sql and foreach tags to produce dynamic
database-driven data.
Listing 9: Database-driven e-mail using <sql> and <sendmail>
<%@ taglib uri=”jruntags” prefix=”jrun” %>
<jrun:sql datasrc="source" id="x">
JRun Tag Library White Paper
17
SELECT Name, Email FROM Customers
</jrun:sql>
<jrun:param id="x" type="allaire.taglib.QueryTable"/>
<jrun:foreach group="<%= x %>">
<jrun:sendmail host=”mail.yourserver.com”
sender=”[email protected]”
recipient=”<%= x.get("Email") %>”
subject=”The JRun Tag Library!”>
Dear <%= x.get("Name") %>,
The JRun Tag Library easily enables database-driven e-mailing!
</jrun:sendmail>
</jrun:foreach>
The code in Listing 9 queries a customer database for names and e-mail
addresses and then sends a personalized message to all customers.
Client-Side Form Processing: A Coding Example
A common task in Web application development is writing client-side form
validation in JavaScript. The JRun Tag Library includes custom tag helper classes
to achieve this task without the need for writing any client side validation scripts.
Listing 10 shows this (note the type and required attributes).
Listing 10: Replacing client-side validation with the JRun Tag Library
1)
<%@ taglib uri="jruntags" prefix="jrun" %>
2)
<jrun:form name="superform" action="someaction.jsp">
3)
Required First Name:
4)
5)
6)
7)
8)
9)
<jrun:input name="FirstName"
type=“text” required="true"/>
Credit Card:
<jrun:input name="CreditCardNumber"
type="creditcard"/>
Birthdate:
<jrun:input name="BirthDate"
type="date"/>
Number of Dependents: <jrun:input name="Dependents"
type="integer"/>
Social Security Card: <jrun:input name="SSN"
type="ssc"/>
Telephone Number:
<jrun:input name="Telephone"
type="phone" required="true"/>
<input type="submit" value="Search"/>
The following paragraphs explain the code in Listing 10:
•
In line 3, the FirstName text input is specified as being required
(required=”true”). Therefore, if the FirstName input field is left blank and the
user clicks Search, the Web browser will produce an error message as shown in
Figure 3.
Figure 3: JavaScript error, automatically generated by specifying
required="true"
18
JRun Tag Library White Paper
•
Lines 4 through 8 illustrate the various input types, such as integer, phone,
date, and credit card. The JRun Tag Library generates the JavaScript code
required to validate each type.
The actual error messages and actions performed when encountering an error can
easily be configured by using the input tag’s onError attribute to specify the name
of a JavaScript function to be called when the error is detected.
Flow Control: A Coding Example
The most powerful tag offering in the flow control category is the foreach tag.
The foreach tag greatly simplifies the common task of iterating through a
collection of objects. The most common data types representing a collection of
similar objects include the ResultSet object, the Enumeration object, any array of
objects that subclass the data type Object, and a linked list of objects used in
combination with an Iterator object to traverse the linked list.
Iterating over Data Types
Data type and
variable name
Java code necessary to iterate
through data type
<foreach> custom tag
java.sql.ResultSet rs
while (rs.next()) {
// process the ResultSet
}
<foreach group=”<%= rs %>”>
//process the ResultSet
</foreach>
java.util.Enumeration e
while (e.hasMoreElements()) {
// process the Enumeration
}
<foreach group=”<%= e %>”
item=”x”>
// process the Enumeration
</foreach>
java.lang.Object[] obj
for (int i=0;i<obj.length;i++) {
// process the object
}
<foreach group=”<%= obj %>”
item=”x”>
// process the object
</foreach>
java.util.Iterator i
while (i.hasNext()) {
// process current object.
// note: iterator must
// be advanced explicitly.
i.next()
}
<foreach group=”<%= i %>”
item=”x”>
// process current object
</foreach>
A primary benefit of the foreach tag is that it can handle all four cases, with the
same simple syntax.
The JRun Tag Library also offers if, case, and switch flow control tags. The
following example illustrates the use of the switch and case flow control tags.
Listing 11: A simple usage of tag-based flow control
1)
2)
3)
4)
<%@ taglib uri="jruntags" prefix="jrun" %>
<jrun:param id=”name” type=”String”/>
<jrun:switch>
<jrun:case expr='<%= name.equals(“Clement”) %>'>
Hi Clement!
5)
</jrun:case>
6)
<jrun:case expr='<%= name.equals(“Tom”) %>'>
Hi Tom!
7)
</jrun:case>
8)
<jrun:case expr='<%= name.equals(“Spike”) %>'>
Hi Spike!
9)
</jrun:case>
10) </jrun:switch>
The following paragraphs explain the code in Listing 11:
JRun Tag Library White Paper
19
•
Line 2 retrieves the name value stored in the implicit session object,
presumably placed there upon log-in.
•
Lines 4, 6, and, 8 perform a string comparison of the name variable against
several supplied names Clement, Tom, and Spike. If any of them return true,
the appropriate greeting message is printed out.
It is important to understand that the if, switch, and case tags don’t offer anything
that cannot be accomplished by using embedded JSP scriptlets that contain the
flow control statements made available by the Java programming language.
However, a tag-based page-flow control offers a more natural look and feel when
writing JSP pages, particularly for people who have little experience with Java
programming.
JSP Standard Tag Library Reference Implementation
The JRun engineering team has been approached by Sun Microsystems to provide
a complete JSP Tag Library reference implementation. The JRun Tag Library has
been submitted for review by Sun Microsystems’s Java Community Process panel.
The panel consists of several industry experts from many different companies who
have a deep understanding of the technology in question and have a strong
technical lead architect to work with them to create a first draft. Consensus is then
built using an iterative review process that allows an ever-widening audience to
participate and to see their comments and suggestions incorporated into successive
draft versions of the specification prior to its final release. This is the official
means of creating new Java software specifications, reference implementations,
and associated suite of compatibility tests. For more information, see Sun
Microsystems’s Java Specification Request (JSR).
JSP Authoring Tools Support
One of the most common complaints among JSP developers is the absence of
authoring tools. This is because traditional Integrated Development Environments
(IDEs) were meant for writing and debugging Java code and are therefore illequipped to deal with JSP’s HTML-based programming paradigm. Syntax is often
difficult to debug because pages compile outside of the page context, resulting in
seemingly random or useless HTTP error messages being reported to the browser
as shown in Figure 4.
20
JRun Tag Library White Paper
Figure 4: A typical ineffective JSP error message
Clearly this error-page gives no useful debugging information to the JSP developer
and is not an ideal development environment.
JRun Studio
Allaire Corporation is proud to announce JRun Studio, an integrated JSP
development environment. based on Homesite, Allaire’s award-winning HTML
editor.
JRun Tag Library White Paper
21
Figure 5: JRun Studio — An integrated JSP development environment
JRun Studio supports page compilation, debugging, and remote deployment
features. It is fully JSP 1.1 aware, supports color-coding of tags, and has numerous
JSP and JRun Tag Library wizards for assistance. It is currently the only such
product offering in the marketplace.
The Future of Tag-Based Programming
Using JRun 3.0’s Web-based JRun Management Console (JMC), administrators
can perform the majority of common server administration tasks through any Web
browser, including deploying EJBs, configuring JDBC data sources, and
connecting to external Web servers.
Allaire’s developers built the JMC using JSP. The significance of this is two-fold.
First, it provides a real-world demonstration of JSP’s possibilities. Second, it
demonstrates Allaire’s commitment and belief that JSP tags will become a
dominant technology in the future development of Web-based applications.
22
JRun Tag Library White Paper
Figure 6: The JRun Management Console — Written using JSP
Well written JSP custom tags are powerful and highly configurable, yet very easy
to use, thus ensuring the highest level of productivity among all the participants
involved in building an Internet application. Web applications developed using
well-defined custom tag libraries, such as the JRun Tag Library, will experience
dramatically faster time-to-market and lower ongoing site maintenance costs than
those developed using Servlets or JSP/JavaBean technologies.
Summary
J2EE provides a solid foundation for building Web applications at every level. As
the J2EE specification evolves, innovations like JSP and custom tag libraries
extend the power of core Java technologies to an ever-broader range of Web
applications and developers.
By 2003, IDC predicts the market for EJB development will balloon to $628
million worldwide and the general application server market will reach $2.3
billion. At the same time, Gartner Group predicts that less than 50 percent of the
market demand for efficient Java developers will be satisfied through 2001. The
demand for Java developers will continue to outstrip supply for the foreseeable
future.
The realization of Java’s full potential as a ubiquitous language for Web
development hinges not only on the fulfillment of Enterprise strength server
technology, but on the accessibility of that technology to the broad, diverse market
of Web developers.
JRun Tag Library White Paper
23
Allaire was founded on the principle of delivering the power of the Internet to the
mass market, and continues that tradition with JRun 3.0
The JRun 3.0 Tag Library makes J2EE functionality accessible to the entire Java
developer community and beyond. Drawing on Allaire’s experience in creating
and maintaining the industry’s first and leading extensible tag library and the
elegance and simplicity of a tag-based scripting environment, JRun 3.0 will serve
as the bridge between Web developers and the promises of J2EE.
JRun 3.0 Developer Edition is freely available for download at
http://www.allaire.com/products/jrun.