Previous     Contents     Index     Next     
iPlanet Application Server Developer's Guide



Chapter 3   Presenting Application Pages with JavaServer Pages


This chapter describes how to use JavaServer Pages (JSPs) as page templates in an iPlanet Application Server web application.

This chapter contains the following sections:



Introducing JSPs

JSPs are browser pages in HTML or XML. They also contain Java code, which enables them to perform complex processing, conditionalize output, and communicate with other application objects. JSPs in iPlanet Application Server are based on the JSP 1.1 specification. This specification is accessible from install_dir/ias/docs/index.htm; install_dir is where the iPlanet Application Server is installed.

In an iPlanet Application Server application, JSPs are the individual pages that make up an application. You can call a JSP from a servlet to handle the user interaction output, or, since JSPs have the same application environment access as any other application component, you can use a JSP as an interaction destination.



How JSPs Work



JSPs are made up of JSP elements and template data. Template data is anything not in the JSP specification, including text and HTML tags. For example, the minimal JSP requires no processing by the JSP engine and is a static HTML page.

The iPlanet Application Server compiles JSPs into HTTP servlets the first time they are called. This makes them available to the application environment as standard objects and enables them to be called from a client using a URL.

JSPs run inside a Java process on the server. This process, called a JSP engine, is responsible for interpreting JSP specific tags and performing the actions they specify in order to generate dynamic content. This content, along with any template data surrounding it, is assembled into an output page and is returned to the caller.

The response object contains a calling client reference; this is where a JSP presents the page it creates. If a JSP is called from a servlet using the RequestDispatcher interface's forward() method, forward() provides the response object as a JSP parameter. If a JSP is invoked directly from a client, the server managing the relationship with the caller provides the response object.

In either case, the page is automatically returned to the client through the response object reference without any additional programming.

You can create JSPs that are not part of any particular application. These JSPs are considered part of a generic application. JSPs can also run in the iPlanet Web Server and other web servers, but these JSPs have no access to any application data, therefore their use is limited.

JSPs and other application components can be updated at runtime without restarting the server, making it easy to change an application's look and feel without stopping service. For more information, see Appendix B "Runtime Considerations."



Designing JSPs



This section describes decisions to consider when writing JSPs. Since JSPs are compiled into servlets, servlet design considerations are also relevant to JSPs. For more information about design considerations for servlets, see Chapter 2 "Controlling Applications with Servlets."

A page's information can loosely be categorized into page layout elements, which consist of tags and information pertaining to the page structure, and page content elements, which consist of the actual page information sent to the user.

You can design a page layout with the design as any browser page, interleaving content elements where needed. For example, one page element might be a welcome message (for example, "Welcome to our application!") at the top of the page. You can personalize this message with a call to the user's name after authentication (for example, "Welcome to our application, Mr. Einstein!").

Since page layout is more or less a straightforward task, the design decisions must relate to the way the JSP interacts with the application and how it is optimized.

This section contains the following subsections:


Choosing a Component

The first task is to decide on a JSP or a servlet. If the main feature is the page layout with little processing involved for page generation, use a JSP alone for the interaction.

Think of JSPs and servlets as opposite sides of the same coin. Each can perform all the tasks of the other, but each is designed to excel at one task at the expense of the other. Servlets are strong in processing and adaptability, and since they are Java files, you can take advantage of integrated development environments while writing them. However, performing HTML output from them involves many cumbersome println statements that must be coded by hand. Conversely, JSPs excel at layout tasks because they are simply HTML files and can be created with HTML editors, though performing computational or processing tasks with them is awkward. Choose the right component for the job at hand.

For example, the following component is presented as both a JSP and a servlet for comparison. This component performs no complex content generation activities, and works best as a JSP:

JSP:

<html><head><title>Feedback</title></head><body>
<h1>The name you typed is: <% request.getParameter("name"); %>.</h1>
</body></html>

Servlet:

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

public class myServlet extends HttpServlet {
   public void service (HttpServletRequest req,
                      HttpServletResponse res)
            throws ServletException, IOException
   {
   response.setContentType("text/html");
   PrintWriter output = response.getWriter();
   output.println("<html><head><title>Feedback</title></head>"
               + "<body>\n"
               + "<h1>The name you typed is:"
               + req.getParameter("name") + ".</h1>"
               + "</body></html>";
   }
}

For more information about servlets, see Chapter 2 "Controlling Applications with Servlets."


Designing for Ease of Maintenance

Each JSP can call or include any other JSP. For example, you can create a generic corporate banner, a standard navigation bar, and a left-side column table of contents, where each element is in a separate JSP and is included for each page built. The page can be constructed with a JSP functioning as a frameset, dynamically determining the pages to load into each subframe. A JSP can also be included when the JSP is compiled into a servlet or when a request arrives.


Designing for Portability

JSPs can be completely portable between different applications and different servers. A disadvantage is that they have no particular application data knowledge, but this is only a problem if they require that kind of data.

One possible use for generic JSPs is for portable page elements, such as navigation bars or corporate headers and footers, which are meant to be included in other JSPs. You can create a library of reusable generic page elements to use throughout an application, or even among several applications.

For example, the minimal generic JSP is a static HTML page with no JSP-specific tags. A slightly less minimal JSP might contain some Java code that operates on generic data, such as printing the date and time, or that makes a change to the page's structure based on a standard value set in the request object.


Handling Exceptions

If an uncaught exception occurs in a JSP file, iPlanet Application Server generates an exception, usually a 404 or 500 error. To avoid this problem, set the errorPage attribute of the <%@ page%> tag.



Creating JSPs



JSPs are created in basically the same way as static HTML files are. You can use an HTML editor to create pages and edit the page layout. You make a page a JSP by inserting JSP-specific tags into the raw source code where needed.

The following sections describe how to use JSP-specific tags in HTML files to create JSPs, including JSP elements, directive elements, scripting elements, and action elements.

This section contains the following subsections:


General Syntax

JSPs that adhere to the JSP 1.1 specification follow XML syntax for the most part, which is similar, but stricter than HTML. In other words, tags are demarcated with < and >, constructs have a start tag (<tag>) and end tag (</tag>), and tags are case-sensitive, such that <tag> is different from <Tag> or <TAG>.

In general, you insert JSP tags inline in the file where needed, in the same way as standard HTML tags. For example, if the request contains a parameter name that contains the user name, a welcome sentence could look like this:

<p>Hello, <%= request.getParameter("name"); %>.</p>


JSP Tags

JSP tags use the<jsp:tag> form, a form taken from XML. Some tags (particularly scripting tags) have a shortcut use in HTML files, generally starting with <% and ending with %>.



Note

These shortcuts are not valid for XML files.



Empty elements or tag constructs that have nothing between the start and end tags can be shortened to one tag ending with />. Some examples:

An include tag with no body:

<jsp:include page="/corporate/banner.jsp"></jsp:include>

A shorter form of an include tag with no body:

<jsp:include page="/corporate/banner.jsp" />

White space is not usually significant, although you must put a space character between the opening tag and any attributes. For example, <%= myExpression %> is valid, but <%=myExpression %> is not.


Escape Characters

Attributes in which difficulty with nested single and double quotes exist use the following escape characters:

  • ` is quoted as \`

  • " is quoted as \"

  • %> is quoted as %\>

  • <% is quoted as <\%


Comments

There are two JSP comment types:

  • JSP page comments that document what the page is doing

  • Document generated comments sent to the client


JSP Comments
A JSP comment is contained within <%-- and --%>, and can contain anything except the text --%>. The following example, therefore is incorrect:

<%-- anything but a closing --%> ... --%>

An alternative way to place a comment in a JSP is to use a Java comment. For example:

<% /** this is a comment ... **/ %>


Generating Comments in Client Output
Use the HTML and XML comment syntax to generate comments to the requesting client in the response output stream, as shown in the following example:

<!-- comments ... -->

The JSP engine treats comments as uninterpreted template text. If the generated comment has dynamic data, obtain it through expression syntax, as shown in the following example:

<!-- comments <%= expression %> more comments ... -->


Directives

Use directives to set preferences within a JSP. Each directive has a number of attributes that affect the behavior or state of the JSP.

<%@ directive { attr="value" }* %>

The valid directives are:


<%@ page%>

The page directive sets the JSP page level preferences.


Syntax
<%@ page language="java"
         extends="className"
         import="className{,+}"
         session="true|false"
         buffer="none|sizeInKB"
         autoFlush="true|false"
         isThreadSafe="true|false"
         info="text"
         errorPage="jspUrl"
         isErrorPage="true|false"
         contentType="mimeType{;charset=charset}"
%>


Attributes
Table 3-1 shows the valid attributes.


Table 3-1    JSP page Directives

Attribute

Valid Values

Description

language  

java  

Default: java. Scripting language for this JSP. Currently, iPlanet Application Server only supports java.  

extends  

valid Java class name  

Defines a specific superclass for this JSP. This restricts the JSP engine in many ways and should be avoided if possible.  

import  

comma-separated list of valid Java class names  

Types and classes available to other methods in this JSP. This is identical to the import statement in a Java class.

The import directive is also the only directive that can appear more than once in a JSP file.  

session  

true or false  

Default: true. Indicates the page must participate in an HTTP session. If language=java and session=true, this option creates an implicit variable called session which points to or creates a session of type javax.servlet.http.HttpSession  

buffer  

none or buffer size in kilobytes  

Defines an output buffer. If set to none, all output is written directly to the output stream (a PrintWriter object). If a size is provided, then either the buffer is flushed or an exception is raised when it is filled with output. The behavior is determined by the autoFlush attribute.  

autoFlush  

true or false  

Determines behavior when the output buffer is full. If true, output is flushed to the output stream when the buffer is full. If false, an exception is raised when the buffer is full.  

isThreadSafe  

true or false  

Default: false. Indicates the thread safety level in the page. The value determines the JSP engine behavior: if true, multiple requests are made to the JSP instance simultaneously, otherwise multiple requests are handled serially. For the most part, ensure your JSP is thread-safe regardless of this setting, as this setting has no effect on shared objects such as sessions or contexts.  

info  

text  

A string inside the translated page which is obtained from the page's Servlet.getServletInfo() method.  

errorPage  

valid URL for a JSP error page  

Error page for this JSP; must be a JSP. Any Throwable object thrown but not caught by the original page is forwarded to the error page. The error page has an implicit variable called exception that contains a reference to the un-caught exception. Note that if autoFlush=true and the initial JspWriter contents have been flushed to the ServletResponse output stream (for example, if part of the page has already been sent to the client), any subsequent attempt to invoke an error page may fail.  

isErrorPage  

true or false  

Default: false. Indicates whether the current JSP page is the possible target of another JSP page's errorPage. If true, the implicit variable exception is defined and its value is a reference to the offending Throwable from the source JSP page in error.  

contentType  

content type, optionally with charset  

Default:
text/html;charset=ISO-8859-1
Defines the MIME type and character encoding for the response. Values are either of the form TYPE or
TYPE;charset=CHARSET
 


Examples
<%@ page errorpage="errorpg.htm" %>
<%@ page import="java.io.*,javax.naming.*" %>


<%@ include%>

The include directive enables other JSP inclusions (or static pages) when the JSP is compiled into a servlet. The resource is treated as a part of the JSP.

Another way to include other resources is to use the <jsp:include> action, which includes resources at request time. For more information on file inclusion, see "Including Other Resources."


Syntax
<%@ include file="file" %>


Attributes
Table 3-2 shows the valid attribute.


Table 3-2    JSP include Directive

Attribute

Valid Values

Description

file  

Valid URL (absolute) or URI (relative path)  

The file to be included.  

The file attribute is either relative to the current JSP, or absolute to the application's context root. For relative file attributes, the file name should not begin with a slash (`/'). For absolute file attributes, the file name should begin with a slash (`/').


Example
If who.jsp is in the application MyApp (typically located in install_dir/ias/APPS/MyApp) and who.jsp contains the following tag:

<%@include file="/add/baz.jsp"%>

then the system tries to include the file baz.jsp from install_dir/ias/APPS/MyApp/add/baz.jsp.

If baz.jsp contains the following tag:

<%@include file="who.jsp"%>

then the system also includes the file install_dir/ias/APPS/MyApps/add/who.jsp.


<%@ taglib... %>

The tag library directive enables custom tag creation. For more information on creating custom tags, see "Value-added Features."


Syntax
<%@ taglib uri="uriToTagLibrary" prefix="prefixString" %>


Attributes
Table 3-3 shows the valid attributes.


Table 3-3    JSP <taglib> Directive

Attribute

Valid Values

Description

uri  

Valid URI (relative path)  

The URI is either an absolute (from the application's context root) or a relative reference to a .tld XML file, describing the tag library. The URI can be an alias that is unaliased by the <taglib> entry in the web application JSP descriptor. For more information, see JSP v1.1 specification section 5.2.  

prefix  

String  

A custom tag prefix.  


Example

Consider the following JSP file, who.jsp, in the application MyApp, and a corresponding XML deployment descriptor file with a web application section as follows:

<taglib>
   <taglib-uri> http://www.mytaglib.com/spTags </taglib-uri>
   <taglib-location> /who/add/baz.tld</taglib-location>
<taglib>

The JSP file contains the following:

<%@ taglib uri="http://www.mytaglib.com/spTags" prefix="mytags" %>
<mytags:specialTag attribute="value"> ... </mytag:specialTag>

The JSP engine looks inside the web app descriptor to find a matching tag library location for http://www.mytaglib.com/spTags. The engine locates /who/add/baz.tld, and therefore looks for an XML file install_dir/ias/APPS/MyApp/who/add/baz.tld. This is the tag library descriptor file that describes the tags used in the file.

The URI or tag library location (if the URI is aliased) can also be relative. In this case, the .tld file is searched for relative to the current directory. For more details, see JSP v1.1 specification, section 5.2.


Scripting Elements

Scripting elements are made up of the following tags:

There are several implicit objects available to scripts, including the request and response objects. For more information about implicit objects, see "Implicit Objects."


Declarations <%! ... %>

The declarations element defines valid variables used throughout the JSP. Declare anything legal in Java, including methods, as long as the declaration is complete. Nothing appears in the output stream as a result of a declaration.


Syntax
<%! declaration %>


Example
<%! int i=0; %>
<%! String scriptname="myScript"; %>
<%! private void myMethod () { ... } %>


Expressions <%= ... %>

The expressions element evaluates variables. The expression value is substituted where the expression occurs. The result appears on the output stream.

The result of the expression must be either a String or an expression whose result can be cast to a String.


Syntax
<%= expression %>


Example
<p>My favorite color is <%= userBean.favColor %>.</p>


Scriptlets <%...%>

The scriptlets element defines code blocks for execution and any legal code can appear here.


Syntax
<% script %>


Example
<% int balance = request.getAttribute("balance");
   if (balance < LIMIT) {
      println (UNDERLIMIT_ALERT);
   }
   String balString = formatAsMoney(balance);
%>
Your current balance is <%= balance %>.


Actions

Actions perform activities, such as including other JSPs or specifying required plug-ins, creating or loading a Java bean, or setting or retrieving bean properties.

Some actions allow request time expressions as parameters, allowing you to set values for these attributes dynamically for the request. The attributes that allow expressions as parameters are the value and name attributes of <jsp:setProperty> and the page attribute of <jsp:include> and <jsp:forward>.

Standard actions are described as follows:


<jsp:useBean>

The <jsp:useBean> action tries to find a Java bean with the given name (id) and scope. If the bean exists, it is made available, otherwise this action creates it using the provided name, scope, and type and class information. A variable called name, specified with the attribute id="name", is made available to the JSP so to access the object if the action succeeds.

<jsp:useBean> can be an empty tag, as in <jsp:useBean ... />, or it can contain other actions and close with the end tag </jsp:useBean>. Other actions that normally appear here are <jsp:setProperty> actions that set properties in the (possibly newly created) bean. Template text, other scripts or declarations, and so on are treated normally. Note that the <jsp:useBean> tag body is executed only once, when the bean is created.

The <jsp:useBean> action must specify a unique id="name" attribute. If the action succeeds in creating or accessing an object, this name makes the object available to scripting tags further down in the JSP.


Syntax
<jsp:useBean id="name" scope="scope"
            class="className" |
            class="className" type="typeName" |
            beanName="beanName" type="typeName" |
            type="typeName">
// optional body
</jsp:useBean>


Attributes
Table 3-4 shows the valid attributes.


Table 3-4    <jsp:useBean> Attributes

Attribute

Description

id  

Unique identifying object name.  

scope  

The object lifecycle is one of the following:

  • page: object is valid for this page only, even if the request encompasses more than one page. The object is not forwarded to other pages.

  • request: object is bound to the request object (retrieved with getAttribute(name) where name is the object's id), and is available for the life of the request.

  • session: object is bound to the session object (retrieved with getValue(name) where name is the object's id) and is available wherever the session is available for the session life. A session must be active for this JSP in order to use this scope.

  • application: object is bound to the ServletContext (retrieved with getAttribute(name) where name is the object's id) and is available for the application existence, unless it is specifically destroyed.

 

class  

Valid bean classname, used to instantiate the bean if it does not exist. If type is specified, class must be assignable to type. Both beanName and class cannot be specified for the same bean.  

beanName  

Valid bean name in the form of, a.b.c (classname) or a/b/c (resource name). Both beanName and class cannot be specified for the same bean. The beanName attribute can be an expression, evaluated at request time.  

type  

Defines the bean variable type. This attribute enables the variable type to be distinct from the implementation class specified. The type is required to be either the class itself, a class superclass, or an interface implemented by the class specified. If unspecified, the value is the same as the class attribute value.  


Examples
This example shows a bean creation or a bean access that already exists, called currentUser of type com.iplanet.myApp.User:

<jsp:useBean id="currentUser" class="com.iplanet.myApp.User" />

In this example, the object is present in the session. If so, it is given the local name wombat with WombatType. A ClassCastException is raised if the object is the wrong class and an InstantiationException is raised if the object is not defined.

<jsp:useBean id="currentUser"
         type="com.iplanet.myApp.User"
         scope="session" />

For more information, see "Examples."


<jsp:setProperty>

The <jsp:setProperty> action sets the bean property values. It can be used both inside and outside of a <jsp:userBean> tag body to set the bean properties. The property values may be determined with an expression or directly from the request object.


Syntax
<jsp:setProperty name="beanName"
               property="propertyName"
               param="requestParameter" | value="value"
</jsp:setProperty>


Attributes
Table 3-5 shows the valid attributes.


Table 3-5    <jsp:setProperty> Attributes

Attribute

Description

name  

Bean name in which to set a property. The name must be defined previously in the file with <jsp:useBean>.  

property  

The bean property name whose value is set. The property must be a valid bean property. If property="*" then the tag iterates over the request object parameters, matching parameter names and value type(s) to property names and setter method type(s) in the bean, setting each matched property to the matching parameter value. If a parameter has an empty value, the corresponding property is not modified. Note that any previous value for the parameter persists.  

param  

The request object parameter name whose value is given to a bean property. If you omit param, the request parameter name is assumed to be the same as the bean property name. If the param is not set in the request object or if it has an empty value, the <jsp:setProperty> action has no effect. A <jsp:setProperty> action cannot have both param and value attributes.  

value  

The value to assign to the given property. This attribute can accept an expression as a value; the expression is evaluated at request time. A <jsp:setProperty> action cannot have both param and value attributes.  


Examples
In this example, the name and permissions properties are set:

<jsp:useBean id="currentUser" class="com.iplanet.myApp.User" >
   <jsp:setProperty name="currentUser"
                  property="name"
                  param="name">
   <jsp:setProperty name="currentUser"
                  property="permissions"
                  param="permissions">
</jsp:useBean>

This example sets the property name value to the corresponding request parameter also called name:

<jsp:setProperty name="myBean" property="name" param="name" />

<jsp:setProperty name="myBean" property="name"
            value="<%= request.getParameter(\"name\" %>)" />


<jsp:getProperty>

A <jsp:getProperty> action places the bean property value, converted to a string, into the output stream.


Syntax
<jsp:getProperty name="beanName"
            property="propertyName">


Attributes
Table 3-6 shows the valid attributes.


Table 3-6    <jsp:getProperty> Attributes

Attribute

Description

name  

Bean name from which to retrieve a property. The name must be defined previously in the file with <jsp:useBean>.  

property  

The bean property name whose value to retrieve. The property must be a valid bean property.  


Examples
<jsp:getProperty name="currentUser" property="name" />


<jsp:include>

In the current page, a <jsp:include> action includes the specified page at request time, preserving the current page context. Using this method, the included page is written to the output stream.

An additional method for including other resources is the <%@ include%> directive, which includes the resource at compile time. For more information on file inclusion, see "Including Other Resources."


Syntax
<jsp:include page="URI" flush="true|false"/>


Attributes
Table 3-7 shows the valid attributes.


Table 3-7    <jsp:include> Attributes

Attribute

Description

page  

Includes either an absolute or relative page reference. For absolute references, this field begins with a slash ("/"), and is rooted at the application's context root. For relative references, this field is relative to the JSP file performing the include, and may contain an expression to be evaluated at request time.  

flush  

Determines whether to flush the included page to the output stream.  


Examples
<jsp:include page="/templates/copyright.html" flush="true" />


<jsp:forward>

The <jsp:forward> action allows the current request to be dispatched at runtime to a static resource, a JSP page, or a Java servlet in the current page's context, terminating the current page's execution. This action is identical to the RequestDispatcher interface's forward() method.


Syntax
<jsp:forward page="URL" />


Attributes
Table 3-8 shows the valid attributes.


Table 3-8    <jsp:forward> Attributes

Attribute

Description

page  

Valid URL pointing to the page to include. This attribute may contain, at request time, an expression to evaluate. The evaluation must be a valid URL.  

   

 


Note

If the page output is unbuffered (with <% page buffer="none" %>) and data has already been written to the output stream, this tag results in a runtime error.



   


Examples
<jsp:forward page="/who/handleAlternativeInput.jsp" />

The following element shows how to forward a static page based on a dynamic condition.

<% String whereTo = "/templates/"+someValue; %>
<jsp:forward page="<%= whereTo %>" />


<jsp:plugin>

The <jsp:plugin> action enables a JSP author to generate HTML that contains the appropriate browser dependent constructs (object or embed) to instruct the browser to download (if required) an appropriate Java plug-in and execute an Applet or JavaBean component. The <jsp:plugin> tag attributes provide the element presentation configuration data.

The <jsp:plugin> tag is replaced by either the appropriate <object> or <embed> tag for the requesting user agent and is sent to the response output stream.

There are two related actions that are only valid within a <jsp:plugin> action:

  • <jsp:params> sends a parameter block to the Applet or JavaBean component. Individual parameters are set with:

       <jsp:param name="name" value="value">

    The section ends with </jsp:params>. The names and values are component dependent.

  • <jsp:fallback> indicates the browser content if the plugin cannot be started (either because object or embed is not supported, or due to some problem). The tag body is presented to the browser when a failure of the surrounding <jsp:plugin> occurs. For example:

       <jsp:plugin ...>
          <jsp:fallback><b>Plugin could not be
          started!</b></jsp:fallback>
       </jsp:plugin>

If the plug-in starts, but the Applet or JavaBean cannot be found or started, a plug-in specific message is sent to the user, often as a popup window reporting a ClassNotFoundException.


Syntax
<jsp:plugin type="bean|applet"
         code="objectCode"
         codebase="objectCodebase"
         { align="alignment" }
         { archive="archiveList" }
         { height="height" }
         { hspace="hspace" }
         { jreversion="jreversion" }
         { name="componentName" }
         { vspace="vspace" }
         { width="width" }
         { nspluginurl="URL" }
         { iepluginurl="URL" } >
         { <jsp:params
               <jsp:param name=" paramName" value="paramValue" />
            </jsp:params> }
         { <jsp:fallback> fallbackText </jsp:fallback> }
</jsp:plugin>


Attributes
The <jsp:plugin> tag takes most of its attributes from the HTML <applet> and <object> tags (<applet> is defined in HTML 3.2 and is deprecated, <object> is defined in HTML 4.01). Refer to the official HTML 4.01 specification where these tags are described:

http://www.w3.org/TR/REC-html40/

Table 3-9 shows the valid attributes.


Table 3-9    <jsp:plugin> Attributes 

Attribute

Description

type  

Identifies the component type, bean or applet.  

code  

As defined by the HTML specification.  

codebase  

As defined by the HTML specification.  

align  

As defined by the HTML specification.  

archive  

As defined by the HTML specification.  

height  

As defined by the HTML specification.  

hspace  

As defined by the HTML specification.  

jreversion  

Identifies the JRE specification version number the component requires to operate. Default: 1.1  

name  

As defined by the HTML specification.  

vspace  

As defined by the HTML specification.  

title  

As defined by the HTML specification.  

width  

As defined by the HTML specification.  

nspluginurl  

URL where the JRE plug-in can be downloaded for Netscape Navigator, default is implementation-defined.  

iepluginurl  

URL where the JRE plug-in can be downloaded for Microsoft Internet Explorer, default is implementation-defined.  


Examples
<jsp:plugin type="applet"
         code="Tetris.class"
         codebase="/html" >
   <jsp:params>
      <jsp:param name="mode" value="extraHard"/>
   </jsp:params>

   <jsp:fallback>
      <p> unable to load Plugin </p>
   </jsp:fallback>
</jsp:plugin>


Implicit Objects

The JSP 1.1 specification defines some objects that are available implicitly for every JSP. You can refer to them from anywhere in a JSP without previously defining them (for example, with <jsp:useBean>).

Table 3-10 shows the objects available implicitly for every JSP.


Table 3-10    Implicitly Available Objects for Every JSP  

Object

Description

Scope

Java type

request  

The request that triggered this JSP's execution.  

request  

protocol dependent subtype of javax.servlet.ServletRequest, for example, javax.servlet.HttpServletRequest  

response  

The request response (for example, the page and its path returned to the caller).  

page  

protocol dependent subtype of javax.servlet.ServletResponse, for example, javax.servlet.HttpServletResponse  

pageContext  

The JSP page context.  

page  

javax.servlet.jsp.PageContext  

session  

The session object (if any) created for or associated with the caller.  

session  

javax.servlet.http.HttpSession  

application  

This JSP's servlet context, from the servlet's configuration object through getServletConfig(),
getContext().
 

application  

javax.servlet.ServletContext  

out  

An object that writes to the output stream.  

page  

javax.servlet.jsp.JspWriter  

config  

This JSP's servlet configuration object (ServletConfig).  

page  

javax.servlet.ServletConfig  

page  

This page's class instance that is processing the current request.  

page  

java.lang.Object  

exception  

For error pages only, the uncaught Throwable exception that caused the error page to be invoked.  

page  

java.lang.Throwable  

For example, you can refer to the request object with one of the request parameters as <%= request.getParameter("param"); %>.



Programming Advanced JSPs



This section provides instructions for using advanced programing techniques and includes the following subsections:


Including Other Resources

An important JSP feature is the ability to dynamically include other page generating resources or their results at runtime. You can include static HTML page content or process a separate JSP and include its results in the output page.

For example, corporate headers and footers can be included on each page by creating page stubs containing just the included elements. Note that it is possible to include entire pages on a conditional basis, providing more flexibility than simply inserting flat navigation bars or corporate headers.

There are two ways to include a resource in a JSP:

  • the <%@ include%> directive:

       <%@ include file="filename" %>

  • the <jsp:include> action:

       <jsp:include page="URI" flush="true|false" />

If you include a resource with the <%@ include%> directive, the resource is included when the JSP is compiled into a servlet, and is treated as part of the original JSP. If the included resource is also a JSP, its contents are processed along with the parent JSP. For more information, see "Directives."

If you include a resource with the <jsp:include> action, the resource is included when the JSP is called. For more information, see "Actions."

The following example shows how each page portion is a separate resource, while access is from a single JSP. The source code for this example page shows both methods for including resources: static resources are included with the <jsp:include> action, and dynamic resources are included with the <%@ include%> directive.




afterLogin.jsp
<html><head><title>Sample Corporate Page</title></head><body>

<p align="left"><jsp:include page="corpHead.htm" flush="true" /></p>
<%@ include file="navBar.jsp" %>
<hr size="3">

<table border=0><tr>
<td width="25%"><%@ include file="appToc.jsp" %></td>
<td width="75%"><%@ include file="appToc.jsp" %></td>
</tr></table>

<hr>
<p align="left"><jsp:include page="corpFoot.htm" flush="true" /></p>
</body></html>


Using JavaBeans

JSPs support several tags to instantiate and access JavaBeans. Beans perform computations to obtain a result set and are stored as bean properties. JSPs provide automatic support for creating beans and for examining their properties.

Beans themselves are separate classes created according to the JavaBean specification. For information about JavaBeans, see:

http://java.sun.com/beans

It is common in beans to have getter and setter methods to retrieve and set bean properties. Getter methods are named getXxx(), where Xxx is a property called xxx (the first letter is capitalized for the method name). If you have a corresponding setter called setXxx(), the setter must be the same parameter type as the getter return value.

This supports standard JavaBeans, not EJBs. To access EJBs from a JSP, see "Accessing Business Objects." In the JSP 0.92 specification, the request and response objects were accessed through "implicit beans." This support has changed in the JSP 1.1 specification; several objects, including the request and response objects, are available implicitly, with varying degrees of scope. For more information, see "Implicit Objects."


Accessing Business Objects

Because JSPs are compiled into servlets at runtime, they have access to all server processes, including EJBs. You access beans or servlets in the same way you would access them from a servlet, as long as the Java code is embedded inside an escape tag.

The method described here for contacting EJBs is identical to the method used from servlets. For more information about contacting EJBs, see "Accessing Business Logic Components."

This example shows a JSP accessing an EJB called ShoppingCart by importing the cart's remote interface and creating a cart handle with the user's session ID:

<%@ import cart.ShoppingCart %>;
...
<% // Get the user's session and shopping cart
   ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());

   // If the user has no cart, create a new one
   if (cart == null) {
      cart = new ShoppingCart();
      session.putValue(session.getId(), cart);
   } %>
...
<%= cart.getDataAsHTML() %>

This example shows JNDI looking up a proxy, or handle, for the cart:

<% String jndiNm = "java:/comp/ejb/ShoppingCart";
   javax.naming.Context initCtx;
   Object home;
      try {
         initCtx = new javax.naming.InitialContext;
      } catch (Exception ex) {
         return null;
      }
      try {
         java.util.Properties props = null;
         home = initCtx.lookup(jndiNm);
      }
      catch(javax.naming.NameNotFoundException e)
      {
         return null;
      }
      catch(javax.naming.NamingException e)
      {
         return null;
      }
      try {
         IShoppingCart cart = ((IShoppingCartHome) home).create();
            ...
      } catch (...) {...}
%>
...
<%= cart.getDataAsHTML() %>



Note

You must provide an EJB method to convert raw data to a format acceptable to the page, such as getDataAsHTML(), as shown above.





Deploying JSPs



There are two ways the iPlanet Application Server deploys JSPs, as either unregistered or registered JSPs.


Unregistered JSPs

Unregistered JSPs are deployed by copying them to the corresponding directory structure (applicationName/moduleName), in the AppPath. These JSPs are invoked using the URL access as follows:

http://server:port/AppPrefix/ModuleName/JSPFileName

For more information, see "Invoking JSPs."


Registered JSPs

The iPlanet Application Server allows JSPs to be registered with GUIDs, using XML. This allows JSPs to use iPlanet Application Server value-added features such as load balancing. This is done using XML files with the <jsp-file> entry as detailed in the Servlet 2.2 specification.

The following XML files are a deployment descriptor example for a registered JSP. This is the web.xml file:

<?xml version="1.0" ?>
<!DOCTYPE web-app>
<web-app>
   <display-name> An Example Registered JSP File </display-name>
   <servlet>
      <servlet-name>JSPExample</servlet-name>
      <jsp-file>JSPExample.jsp</jsp-file>
   </servlet>
   <servlet-mapping>
      <servlet-name>JSPExample</servlet-name>
      <url-pattern>/jspexample</url-pattern>
   </servlet-mapping>
</web-app>

This is the ias-web.xml file:

<?xml version="1.0" ?>
<ias-web-app>
   <servlet>
      <servlet-name>JSPExample</servlet-name>
      <guid>{aaaabbbb-A456-161A-8be4-0800203942f2}</guid>
   </servlet>
</ias-web-app>

In this example, the JSP is registered with the GUID specified in the ias-MyApp.xml file. Although this example indicates that the servlet name is JSPExample, it does not mean that the .jsp extension is required. It is possible for the servlet name to be JSPExample.jsp instead.

This JSP is accessed from a URL by using one of the following examples:

  • http://server:port/AppPrefix/ModuleName/JSPExample

  • http://server:port/AppPrefix/ModuleName/JSPExample.jsp (use if the servlet-name entry in the XML file is JSPExample.jsp)



Invoking JSPs

A JSP is invoked programmatically from a servlet or by addressing it directly from a client using a URL. You can also include JSPs. For more information, see "Including Other Resources."


Calling a JSP With a URL

JSPs can be called using URLs embedded as links in the application pages. This section describes how to invoke JSPs using standard URLs.


Invoking JSPs in a Specific Application

JSPs that are part of a specific application are addressed as follows:

http://server:port/AppPrefix/ModuleName/jspName?name=value

Table 3-11 shows each URL section.


Table 3-11    URL Sections

URL element

Description

server:port  

Address and optional web server port number handling the request.  

AppPrefix  

Indicates to the web server that the URL is for an iPlanet Application Server application. The request is routed to the iPlanet Application Server executive server. Configure this using the registry entry SSPL_APP_PREFIX.  

moduleName  

The name of the web module (these names are unique across the server).  

jspName  

The JSP's file name, including the .jsp extension.  

?name=value...  

Optional name=value parameters to the JSP. These are accessible from the request object.  

For example:

http://www.mycompany.com/BookApp/OnlineBookings/directedLogin.jsp

Using a generic application for a JSP has the same requirements and restrictions as using a generic application for a servlet. There must be an application called Default with a registered XML file. Any URL request to access a servlet or JSP with the /servlet/ entry is sent to the generic application Default. For more information about this requirement, see "Invoking Generic Application Servlets."


Invoking JSPs in a Generic Application

JSPs that are not part of a specific application are addressed as follows:

http://server:port/servlet/jspName?name=value

Table 3-12 shows each URL section.


Table 3-12    URL Sections

URL element

Description

server:port  

Address and optional web server port number handling the request.  

servlet  

Indicates to the web server that the URL is for a generic servlet object.  

jspName  

The JSP's name, including the .jsp extension.  

?name=value...  

Optional name=value parameters to the JSP. These are accessible from the request object.  

For example:

http://www.Who.com/servlet/calcMort.jsp?rate=8.0&per=360&bal=180000


Invoking a JSP From a Servlet

A servlet can invoke a JSP in one of two ways:

  • The include() method in the RequestDispatcher interface calls a JSP and waits for it to return before continuing.

  • The forward() method in the RequestDispatcher interface hands JSP interaction control.

For more information about these methods, see "Delivering Client Results."

For example:

public class ForwardToJSP extends HttpServlet
{
   public void service(HttpServletRequest req,
                     HttpServletResponse res)
   throws ServletException, IOException
   {
      RequestDispatcher rd = req.getRequestDispatcher("/test.jsp");
      rd.forward(req, res);
   }
}



JSP 1.1 Tag Summary



The following sections summarize the JSP 1.1 tags.


Directives

<%@ page|include|taglib { attr="value" }* %>

   attr: page language="java"
               extends="className"
               import="className{,+}"
               session="true|false"
               buffer="none|sizeInKB"
               autoFlush="true|false"
               isThreadSafe="true|false"
               info="text"
               errorPage="jspUrl"
               isErrorPage="true|false"
               contentType="mimeType{;charset=charset}"

            include file="filename"

         taglib uri="uriToTagLibrary"
            prefix="prefixString"

For more information, see "Directives."


Expressions

<%= expression %>

For more information, see "Scripting Elements."


Scriptlets

<% scriptlet %>

For more information, see "Scripting Elements."


Comments

<%-- comment --%>                     JSP comment, not passed to client
<!-- comment -->                     standard HTML comment, passed to client
<% /** comment **/ %>                      Java comment, encapsulated in scriptlet, passed to client

For more information, see "Comments."


Bean-Related Actions

<jsp:useBean id="name" scope="scope"
            class="className" |
            class="className" type="typeName" |
            beanName="beanName" type="typeName" |
            type="typeName">
// optional body
</jsp:useBean>

<jsp:setProperty name="beanName"
               property="propertyName"
               param="requestParameter" | value="value"
</jsp:setProperty>

<jsp:getProperty name="beanName"
            property="propertyName">

For more information, see "Actions."


Other Actions

<jsp:include page="relativeUrl"
            flush="true|false" />

<jsp:forward page="URL" />

<jsp:plugin type="bean|applet"
            code="objectCode"
            codebase="objectCodebase"
            { align="alignment" }
            { archive="archiveList" }
            { height="height" }
            { hspace="hspace" }
            { jreversion="jreversion" }
            { name="componentName" }
            { vspace="vspace" }
            { width="width" }
            { nspluginurl="URL" }
            { iepluginurl="URL" } >
            { <jsp:params
               <jsp:param name=" paramName" value="paramValue" />
               </jsp:params> }
         { <jsp:fallback> fallbackText </jsp:fallback> }
</jsp:plugin>

For more information, see "Actions."



Modifying Custom Tags for JSP 1.1



iPlanet Application Server custom tags may need to be modified for JSP 1.1 for the following reasons:

  • The .tld files do not conform to the DTD at:

    http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd

    For example, every reference to the prefix attribute must be changed to shortname.

  • The following DOCTYPE element is missing:

    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

These modifications are necessary if you want to use the JSP command-line compiler. For more information about this compiler, see "Compiling JSPs: The Command-Line Compiler."



Compiling JSPs: The Command-Line Compiler



As of Service Pack 3, iPlanet Application Server uses the Jasper JSP compiler from Apache Tomcat 3.2 to compile JSP 1.1 compliant source files into servlets. All of the features available in this version of Jasper are available in the iPlanet Application Server environment.



Note Jasper has been modified to meet the requirements of iPlanet Application Server, so you should use only the Jasper version provided with iPlanet Application Server. Other versions will not work with iPlanet Application Server.



Developers can use the JSP compiler to perform syntax checks of JSP files prior to deployment. Deployers can also benefit from the JSP compiler by precompiling JSP files into WAR files before the WAR files are deployed to the application server.

The jspc command line tool is located under install_dir/ias/bin (make sure this directory is in your path). The format of the jspc command is as follows:

jspc [options] jsp_files

The jsp_files can be one of the following:

files

One or more JSP files to be compiled.

-webapp dir

A directory containing a web application. All JSPs in the directory and its subdirectories are compiled. You cannot specify a WAR, JAR, or ZIP file; you must first deploy it to an open directory structure using iasdeploy.

The basic options for the jspc command are:

-q

Enables quiet mode (same as -v0). Only fatal error messages are displayed.

-d dir

Specifies the output directory for the compiled JSPs. Package directories are automatically generated based on the directories containing the uncompiled JSPs. The default top-level directory is the directory from which jspc is invoked.

-p name

Specifies the name of the target package for all specified JSPs, overriding the default package generation performed by the -d option.

-c name

Specifies the target class name of the first JSP compiled. Subsequent JSPs are unaffected.

-uribase dir

Specifies the URI directory to which compilations are relative. Applies only to JSP files listed in the command, and not to JSP files specified with -webapp.

This is the location of each JSP file relative to the uriroot. If this cannot be determined, the default is /.

-uriroot dir

Specifies the root directory against which URI files are resolved. Applies only to JSP files listed in the command, and not to JSP files specified with -webapp.

If this option is not specified, all parent directories of the first JSP page are searched for a WEB-INF subdirectory. The closest directory to the JSP page that has one is used.

If none of the JSP's parent directories have a WEB-INF subdirectory, the directory from which jspc is invoked is used.

-webinc file

Creates partial servlet mappings for the -webapp option, which can be pasted into a web.xml file.

-webxml file

Creates an entire web.xml file for the -webapp option.

-ieplugin class_id

Specifies the Java plugin COM class ID for Internet Explorer. Used by the <jsp:plugin> tags.

The advanced options for the jspc command are:

-v[level]

Enables verbose mode. The level is optional; the default is 2. Possible level values are:

  • 0 - fatal error messages only

  • 1 - error messages only

  • 2 - error and warning messages only

  • 3 - error, warning, and informational messages

  • 4 - error, warning, informational, and debugging messages

-dd dir

Specifies the literal output directory for the compiled JSPs. Package directories are not made. The default is the directory from which jspc is invoked.

-mapped

Generates separate write calls for each HTML line and comments that describe the location of each line in the JSP file. By default, all adjacent write calls are combined and no location comments are generated.

-die[code]

Causes the JVM to exit and generates an error return code if a fatal error occurs. If the code is absent or unparsable it defaults to 1.

-webinc file

Creates partial servlet mappings for the -webapp option, which can be pasted into a web.xml file.

-webxml file

Creates an entire web.xml file for the -webapp option.

-ieplugin class_id

Specifies the Java plugin COM class ID for Internet Explorer. Used by the <jsp:plugin> tags.

When a JSP is compiled, a package is created for it. The package is located in install_dir/ias/APPS/appName/moduleName/WEB-INF/compiled_jsp/. (If the code is deployed as an individual module, the moduleName is modules.) The package name should start with jsp.APPS, which is the default package prefix name in iPlanet Application Server.

Use the basic options of jspc when compiling the JSP for iPlanet Application Server. iPlanet Application Server does not use the standard Jasper naming conventions, so you must specify the generated file name, class name (-c), package (-p) and directory (-d).

For example, to precompile fortune.jsp to fotune.java, use these commands:

cd install_dir/ias/APPS/fortune/fortune

jspc -d WEB-INF/compiled_jsp -p jsp.APPS.fortune -c fortune fortune.jsp

The fortune.java file and its respective class are generated in the following directory:

install_dir/ias/APPS/fortune/fortune/WEB-INF/compiled_jsp/jsp/APPS/fortune

The package name of the fortune.class file is jsp.APPS.fortune, because fortune is the package name of the JSP and iPlanet Application Server uses jsp.APPS as a prefix.



Note iPlanet Application Server 6.5 supports debugging of the compiled servlet code using Forte For Java Enterprise Edition 3.0. However, you cannot debug the uncompiled JSP pages.



Additional documentation for the JSP compiler is on the Jakarta site:

http://jakarta.apache.org/tomcat-4.0/jakarta-tomcat-4.0/jasper/doc/jspc.html



Value-added Features



The following sections summarize the iPlanet value-added features:


Custom Tag Extensions

The JSP 1.1 specification has support for a user defined custom tags protocol. Although the specification does not mandate any tags, as a value-added feature the iPlanet Application Server contains custom tags that follow the JSP 1.1 defined tag extension protocol. For more information, see the JSP 1.1 specification, Chapter 5.

Some tags provide LDAP and database query support, while others provide support for conditionals inside JSPs because the specification provides no primitive support.

To support JSP page caching, the iPlanet Application Server ships with a Cache tag library. For details, see "JSP Page Caching."

The other tags included with the iPlanet Application Server are for internal use only, to support converting GX tags. These tags are used in generating JSP 1.1 pages from JSP 0.92 pages (which supported GX tags), and should not be used externally.

The following tag libraries are introduced by the iPlanet Application Server:

  • Query

  • LDAP

  • Conditional

  • Attribute

For examples of the custom tag extensions, see the samples in the install_dir/ias/ias-samples/iastags/ directory.


Database Query Tag Library

The query tag library supports row set declarative declarations in JSP pages, along with loops to loop through a result set and a display tag for displaying column values. The following sections describe the query tag library.


useQuery Tag
The useQuery tag declares a result set to use. The useQuery tag defines what query is being made and what available fields are for use. If the result set the useQuery wants to save to is already in the scope, the tag body is skipped, and although the row set is created it is ignored.

If the result set does not exist, the created row set is exported using the useQuery tag's id attribute of the specified scope, which defaults to request. Either the specified command is used, or a query located in the queryFile is loaded. The loaded query file name is either the name located in the queryName attribute, or, if none is specified, the tag's id attribute value is used. Once the row set is initialized, it may be executed if the execute tag is specified. Note that you must execute a query to use the field tag outside of a loop.

If the query is loaded from a file rather than specified in the command attribute, the file is loaded and cached by the QueryLoader class. The two attributes queryFile and queryName work in conjunction. The queryFile locates the query file. If the attribute value is a relative path, it is looked up in the RDBMS.path.query path. If this variable is not set, the iPlanet Application Server specific GX.path.query property is used. If the file is not located relative to the JSP, the query file should look something like the following examples:

query name1 [using (ODBC, cdx, iplanet)] is select *
from Who, add where :whereClause
/* :whereClause is an example of a bindOnLoad, named parameter */

query name2 is select * from Who, add where Who.x = add.y and Who.name = :name
/* :name is an example of a named parameter */

A blank line (without spaces, tabs, and so on) separates queries which are named using the query ... is construct.


Syntax
<rdbm:useQuery id="export_name" scope="[page|request|session|application]" command="select * from..."="Who.gxq" queryName="firstQuery"
execute="[true|false]" dataSourceName="jdbc/..." url="odbc:...">...</rdbm:useQuery>


param Tag
The param tag sets a parameter on a row set. The parameter name can be either an index or the actual parameter name as saved in the dictionary. Note that bindOnLoad parameters must exist in the useQuery tag body before any non-bindOnLoad parameters. The parameter value is either the value stored in the value attribute or the param tag body contents. Because JSP 1.1 tags don't generally nest (<%= ... %> being the notable exception), the only way to bind a parameter to a value from another query is to place a field tag within the param tag body and have the param tag use its body as the value, which is why you can place the value in the tag's body.

param tags may exist within a useQuery tag, in which case they set the parameters directly against their parent query, or before a loop tag re-executes the row set, in which case the parameter is set on the row set that the useQuery tag exported.


Syntax
<rdbm:param query="query-declaration-export-name" name="name-of-parameter" value="value" bindOnLoad="[true|false]" type="[String|Int|Double|Float|BigDecimal|Date|Boolean|Time|Timesta mp"
format="java-format-string for dates">value</rdbm:param>


loop Tag
The loop tag loops through the result set contents. The query attribute is used to locate the result set or an enclosing useQuery tag. The start attribute is used to indicate the loops's starting position. start may either refer to a parameter or to an attribute, which is looked up using PageContext.findAttribute(), or to a constant integer value. The value indicates which record number to start on, or last, which causes the row set to be scrolled to the end, and then back max rows. The max attribute is used to indicate the maximum number of records to display. If execute is specified, then the row set is executed before looping begins.


Syntax
<rdbm:loop id="export_name" scope="[page|request|session|application]" query="query-declaration-export-name" start="[request-parameter-name|request-attribute-name|last|constant ]"
max="integer-maximum-number-of-rows" execute='{true|false]">...</rdbm:loop>


field Tag
The field tag displays a particular result set column. The query attribute locates the enclosing useQuery tag or a previous useQuery tag's exported result set. The name attribute identifies the column name to display. The format attribute allows the formatting of strings, numbers, or dates into the appropriate type. The urlEncode attribute can be used to encode the strings. If the column is null, the field tag body is output.


Syntax
<rdbm:field query="query-declaration-export-name" name="field name"
format="format for doubles" urlEncode="{false/true}">default value</rdbm:field>


close Tag
The close tag releases system resources. The resource attribute locates the exported query resource (result set) and calls close().


Syntax
<rdbm:close resource="query-declaration-export-name"/>


execute Tag
The execute tag executes the identified query.


Syntax
<rdbm:execute query="query-declaration-export-name"/>


goRecord Tag
The goRecord tag executes the specified query and moves the result set to the record indicated by the start attribute. start may either refer to a parameter, or to an attribute, or to a constant. If the start attribute is last, the result set is moved to the last record.


Syntax
<rdbm:goRecord query="query-declaration-export-name" execute="{false/true}" start="[request-parameter-name|request-attribute-name|last|constant ]">
default start</rdbm:goRecord>


Example
The following tags produce the output display at the end of the example.

<HTML>
<BODY>
<%@ taglib prefix="rdbm" uri="rdbmstags6_0.tld" %>
<h2>Now let us see</h2>
<rdbm:useQuery id="a" queryFile="dbms/queries.gxq"
   dataSourceName="jdbc/cdx">
</rdbm:useQuery>
<rdbm:useQuery id="b" queryFile="dbms/queries.gxq"
   dataSourceName="jdbc/cdx">
</rdbm:useQuery>

<table border=1 cellPadding=3>
<tr><th>name</th><th>phone</th><th>Titles Owned</th></tr>
<rdbm:loop id="loop1" query="a" max="5" execute="true">
   <tr>
   <td><rdbm:field query="a" name="name"/></td>
   <td><rdbm:field query="a" name="phone"/></td>
   <td>
      <rdbm:param query="b" id="owner" type="Int">
      rdbm:field query="a" name="id"/></rdbm:param>
         <table border=1 cellPadding=3 width="100%">
         <tr><th>title</th><th>price</th><th>artist</th></tr>
         <rdbm:loop id="loop2" query="b" max="5"execute="true">
         <tr>
         <td><rdbm:field query="b" name="title"/></td>
         <td><rdbm:field query="b" format="$#,###.00"name="price"/>
         </td>
         <td><rdbm:field query="b" name="artist"/></td>
         </tr>
         </rdbm:loop>
         </table>
   </td>
   </tr>
   </rdbm:loop>
   </table>
   </td>
   </tr>
</rdbm:loop>
</table>
<rdbm:close resource="a"/>
<rdbm:close resource="b"/>
</BODY>
</HTML>

Here are the results:




LDAP Tag Library

One unfortunate aspect of LDAP connections is that they are likely to be request-specific, that is, the current user may be the only user authenticated to read the LDAP attributes of that user's data. Because of this, an additional LDAPAuthenticate/Authorize tag is required so mappings between current user and connection to perform LDAP searches are programmable. When the LDAP server is remote and a general authorization-capable login is not available, the LDAPAuthenticate tag is used. The following sections describe the LDAP tag library.


authenticate Tag (also called connection)
The authenticate tag works in the LDAPTagSearch context. The LDAPTagSearch is either retrieved from the PageContext using findAttribute and the query attribute name, or by finding a parent useQuery tag and getting its LDAPTagSearch. The url and password attributes are used for LDAPConnection authentication, which the LDAPTagSearch holds onto. If the url attribute has parameters (that is, if the attribute has :Who values in it after the standard ldap://server:portNumber/ LDAP URL section), then the authenticate tag body needs to contain param tags for each parameter. If the password attribute is unspecified, then the authenticate tag body should contain a password tag as well. At the end of the tag, the tag attempts to authenticate the LDAPTagSearch.


Syntax
<ldap:[authenticate|connection] query="name of ldap exported query" url="ldap://..." password="..."> </ldap:[authenticate|connection]>


authorize Tag
The authorize tag works in the LDAPTagSearch context. The LDAPTagSearch is either retrieved from the PageContext using findAttribute and the query attribute name, or by finding a parent useQuery tag and getting its LDAPTagSearch. The dn attribute is used to authorize the LDAPConnection, which the LDAPTagSearch holds onto. If the dn attribute has parameters (that is, if the attribute has :Who values in it), then the authorize tag body needs to contain param tags for each parameter. At the end of the tag, the tag attempts to authorize the LDAPTagSearch.


Syntax
<ldap:authorize query="name of ldap exported query" dn="distinguished name for the user to authorize against"> </ldap:authorize>


param Tag
The param tag sets the LDAP URL parameters. LDAP URLs are specified in the url and dn attributes of the authorize tag and in the url attribute of the field and useQuery tags.

A URL param is any Java level identifier with a prepended ":", similar to the query parameters in a .gxq file. For example:

ldap://iplanet.com:389/uid=:user,ou=People,dc=iplanet,dc=com

All parameters must be resolved by the end of the field, authenticate, authorize, or useQuery tags. Note that 389 is not a tag because it's before the LDAP URL DN section and isn't a Java level identifier.

The param tag body becomes the parameter value as named by the name attribute, assuming no value is specified in the param tag itself.


Syntax
<ldap:param name="parameter name in authenticate userDN or query url" query="name of ldap exported query" value="...">default value</ldap:param>


password Tag
The password tag sets the authenticate tag password. Like the param tag, the password tag body becomes the password value, assuming that no value is specified as a password tag attribute. The password tag is legal only inside the authenticate tag.


Syntax
<ldap:password query="name of ldap exported query" value="...">default value</ldap:password>


useQuery Tag
The useQuery tag describes the URL used to search the LDAP repository. At the end of its body, an LDAPTagSearch is placed into the context at the level indicated by scope using the name indicated by id. The url property contains the URL of a query that a loop tag loops through or that a field tag displays. This is because the loop tag cannot specify parameter mappings except in the body - which is too late for the loop to determine if there are any results. The field tag can already specify a URL and doesn't need to reference a query, though it can.

The URL can also be loaded from a query file. The two attributes queryFile and queryName work in conjunction. The queryFile locates the query file. If the attribute value is a relative file specification, the file is searched for in the LDAP.path.query path. If this variable is not set, then the iPlanet Application Server specific GX.path.query property is used instead. The file is not located relative to the JSP. The query file should look something like the following example:

query name1 is
ldap://directory:389/dc=com?blah

query name2 is
ldap://directory:389/dc=org?blah

A blank line (without spaces, tabs, etc.) separates the queries, which are named using the query ... is construct.


Syntax
<ldap:useQuery id="exported LDAPTagSearch" scope="[page|request|session|application]" url="ldap://... queryFile="filename for ldap query" queryName="name of the query in the ldap query file" connection="classname of an LDAPPoolManager" authorize="distinguished name for the user to authorize against">...</ldap:useQuery>


loopEntry Tag
The loopEntry tag loops through a series of LDAPEntries resulting from a search that returns multiple entries. The query attribute points to an exported LDAPTagSearch (for more information, see "useQuery Tag"). The start and end tags work as specified in the query's loop tag. If the useVL attribute is true, then an {id}_contentCount value is exported, which corresponds to the VirtualListResponse contentCount. On each pass through the loop, the current LDAPEntry is exported at the scope specified using the id specified. The pre and jump attributes correspond to the beforeCount and jumpTo parameters in the VirtualListControl constructor. If the loop is using a VirtualListControl and if the useVL attribute is set, then a VirtualListControl is used to position the returned entries window. The actual public draft URL for VirtualList is located here.


Syntax
<ldap:loop[Entry] id="name of attribute to export loop'd value" scope="[page|request|session|application]" query="name of ldap exported query" start="request variable name" max="number" pre="number of records before jump" jump="value of sort to jump to" useVL="true/false"> </ldap:loop[Entry]>


loopValue Tag
The loopValue tag loops through a multi-value LDAPEntry attribute or the first LDAPEntry in an LDAPSearchResults. The query attribute points to an exported LDAPTagSearch (for more information, see "useQuery Tag"). If this is not specified, then the entry attribute points to an exported entry as specified by a containing loop tag. One or the other must be specified. It is an error to specify both. The attribute tag names the multi-value attribute. The start and end tags work as specified in the query's loop tag. On each pass through the loop, the current LDAPAttribute value is exported at the specified scope using the specified id.


Syntax
<ldap:loopValue id="name of attribute to export loop'd value" scope="[page|request|session|application]" query="name of ldap exported query" entry="name of ldap exported entry from loopEntry" attribute="name of attribute to loop through" start="..." max="..."> </ldap:loopValue>


field Tag
The field tag prints out the value of a single value attribute as specified in the query, url, or entry attributes, and the attribute attribute. If no value exists, the field tag body is passed. The field tag body is only evaluated if the url has parameters (and hence, there are parameter bindings in the body that need to be evaluated and set), or if the mapped value is null. If the attribute name is $DN$, then the distinguished entry name is returned as the field value.


Syntax
<ldap:field query="name of query to use" entry="name of ldap exported entry from loopEntry" url="ldap://..." attribute="name of attribute to display"> </ldap:field>


sort Tag
The sort tag works in conjunction with the useQuery tag, setting a sort order for the enclosing query. The query attribute identifies the enclosing useQuery tag (or an exported LDAPTagSearch, if the sort tag occurs outside of the useQuery tag's body). The order attribute specifies the sort order, as described by the LDAPSortKey constructor's keyDescription parameter. The useQuery tag supports multiple sorts. Sorts are prioritized in the order specified.


Syntax
<ldap:sort query="name of ldap exported query" order="..."/>


close Tag
The close tag releases resources back to the system. The resource attribute locates the exported query resource (LDAPTagSearch) and calls close() on it. This call abandons any executing SearchResults and releases the connection to the connection pool (or calls disconnect() on the connection, if the connection doesn't come from a pool; the connection can come from the authenticate tag).


Syntax
<ldap:close resource="name of ldap exported query"/>


Example
The following example uses both LDAP and switch tags. It is assumed that the switch tags are mostly self describing.

<HTML>
<BODY>
<%@ taglib prefix="cond" uri="condtags6_0.tld" %>
<%@ taglib prefix="ldap" uri="ldaptags6_0.tld" %>
<%@ taglib prefix="attr" uri="attribtags6_0.tld" %>

<cond:parameter name="user">
   <cond:exists>
      <ldap:query id="c" url="ldap://localhost:389/uid=:user,
          ou=People,dc=iplanet,dc=com?cn,mailalternateaddress,mail">
         <cond:parameter name="password">
            <cond:exists>
               <ldap:authenticate query="c"
                  url="ldap://localhost:389/dc=
                     com??sub?(uid=:user)">
                  <ldap:param name="user">
                     <attr:getParameter name="user" />
                  </ldap:param>
                  <ldap:password>
                     <attr:getParameter name="password" />
                  </ldap:password>
               </ldap:authenticate>
            </cond:exists>
         </cond:parameter>
      <ldap:param name="user"><attr:getParameter name="user" />
      </ldap:param>
   </ldap:query>
   <h2>Hello
   <ldap:field query="c" attribute="cn">

No Contact Name for <attr:getParameter name="user" /> in LDAP!

   </ldap:field></h2>
   <p>

Your main email is:
   <blockquote>
   <ldap:field query="c" attribute="mail"/>
   </blockquote>

Your alternate email addresses are as follows:

<ul>
<ldap:loopValue id="Who" scope="request" query="c" attribute="mailalternateaddress">
<li><attr:get name="foo" scope="request"/>
</ldap:loopValue>
</ul>
<cond:ldap name="c">
<cond:authenticated>
<p>

Your employee number is:
<ldap:field attribute="employeenumber" query="c">
They removed the employee numbers from ldap -- not good!

</ldap:field>
</cond:authenticated>
<cond:else>
<cond:parameter name="password">
<cond:exists>Your specified password is incorrect. Please retry!</cond:exists>
<cond:else>To see your employee id, please specify a 'password' parameter in the url along with your user name!<p></cond:else>

</cond:parameter>
</cond:else>
</cond:ldap>
<p>
<ldap:close resource="c"/>
</cond:exists>
<cond:else>

To see your employee information, please specify a 'user' parameter in the url!

<p>
</cond:else>
</cond:parameter>
</body></html>
Would produce one of the following results:




Conditional Tag Library

The cond tag family supports switch and case tags, allowing a special case when a row set is at the end, when a user is given management-only information types, when a user has requested high bandwidth content, and so on.

However, for ease of use and better readability, the following equivalents can be used:

  1. <cond:role> ... </cond:role>

  2. <cond:rowset name="rowset name"> ... </cond:rowset>

  3. <cond:ldap name="ldap connection name"> ... </cond:ldap>

  4. <cond:attribute name="attribute name"> ... </cond:attribute>

  5. <cond:parameter name="parameter name | $REMOTE_USER$"> ... </cond:parameter>

  6. <cond:else> ... </cond:else>

  7. <cond:equals value="..."> ... </cond:equals>

  8. <cond:equalsIgnoreCase value="..."> ... </cond:equalsIgnoreCase>

  9. <cond:exists> ... </cond:exists>

  10. <cond:notEmpty> ... </cond:notEmpty>

  11. <cond:executeNotEmpty> ... </cond:executeNotEmpty>

  12. <cond:isLast> ... </cond:isLast>

  13. <cond:Connected> ... </cond:connected>

  14. <cond:authenticated> ... </cond:authenticated>

Some ways may be more expressive than you really require. For example:

<cond:parameter name="Who"> ... </cond:parameter>

is the same as:

<cond:switch><cond:value><%= request.getParameter("Who") %></cond:value> ... </cond:switch>

Additionally, one might assume that:

<cond:rowset value="rowset name">
<cond:exists> ... </cond:exists></cond:rowset>

would be the same as:

<cond:rowset value="rowset name">
<cond:case operation="="> ... </cond:case></cond:rowset>

Always consider, if the increased expressiveness is worth the trade-off in possible user confusion.

The root tags are described next.


switch Tag
The switch tag defaults to a straight value comparison. However, it is more likely to be used as a RowSet type switch to replace some callbacks that DBRowSet contains. The switch tag keeps track of whether a particular case statement has fulfilled the switch statement and only exports its body to the content page.


Syntax
<cond:switch type="[value|role|rowset|ldap|attribute|parameter]" value="constant value, role name, rowset name, etc."> ... </cond:switch>


case Tag
The case tag contains an operation and (possibly) a second operand, and is used to determine if the case statement fulfills the switch tag. Note that if a case and switch combination are used where a value is required and no value is specified, a value is obtained from an enclosing cond:dynamicValue tag. This allows the case tag to implement only the tag interface, which allows more efficient JSP building. The case tag body is not evaluated unless the case statement fulfills an as yet unfulfilled switch statement.

If no operation is specified, the operation is assumed to be else - that is, to fulfill the switch regardless. If no operation is specified and the switch type is role, the operation assumes it is equals.

Note that certain case operations make sense only in certain switch types. For example:

  • The isLast and notEmpty tags are useful for both ldap (query or entry) and RowSet switch types.

  • The executeNotEmpty operation makes sense only for RowSet switch types.

  • The connected and authenticated operations make sense only for ldap switch types.

  • The "=, <, >" etc. operations make sense only when comparing numerical values. The switch and case values are converted to doubles (if necessary), and their values are compared.

  • The equals and equalsIgnoreCase operations make sense only when comparing strings, although equals is called against the switch value equals method - which might be implemented by an object to compare itself to a string (the case value, always). notEmpty also makes sense for strings as a check when a parameter has specified a non-zero length setting.


Syntax
<cond:case operation="[=|<|>|<=|>=|!=|<>|><|=>|=<|~=|equals|equalsIgnoreCase|e lse|exists|notEmpty|executeNotEmpty|isLast|connected|authenticated| {method-name}]"
value="..."></cond:case>


value Tag
The value tag body is evaluated and passed to the value tag's parent. The parent implements the IValueContainingTag, which both switch and dynamicValue do. You can also specify the value in a value tag attribute. But then, if you do that, it is better to put the value in the switch or case directly.


Syntax
<cond:value value="blah">default value</cond:value>


Dynamic Value Tag
The dynamicValue tag body should have at least two elements. One is a value tag, which builds the dynamic interest value. The second is a case tag, whose value attribute is extracted from the enclosing dynamicValue instance. The dynamicValue tag does have a value tag, as follows:

<cond:attribute name="Who">
   <cond:dynamicValue value="10">
      <cond:case operation="<">less than ten</cond:case>
   <cond:case operation="=">equal to ten</cond:case>
      <cond:case operation=">">greater than ten</cond:case>
   </cond:dynamicValue>
</cond:attribute>

There are no machine equivalents to comparison bits in the status register, therefore the operation performs three (3) times.


Syntax
<cond:dynamicValue value="blah"> ... <cond:value/> ... <cond:*case*/> ... </cond:dynamicValue>


Example
The following example shows how a switch might be used. The three links at the end produce the three different output types:

<%@ taglib prefix="cond" uri="condtags6_0.tld" %>

<cond:parameter name="showHeader">
   <cond:equalsIgnoreCase value="true">
      h2>Now let us see</h2>
   </cond:equalsIgnoreCase>
   <cond:dynamicValue>
      <cond:value value="false"/>
      <cond:equalsIgnoreCase>
         I'm not showing a header. Nope, not me!
      </cond:equalsIgnoreCase>
   </cond:dynamicValue>
   <cond:else>
      showHeader not specified or illegal value
   </cond:else>
</cond:parameter>

The possible outputs are as follows:




Attribute Tag Library

The following sections provide information on the attribute tag library.


getAttribute Tag
The getAttribute tag prints the named attribute's value, which is retrieved from the specified scope. If no scope is specified, findAttribute() is used to find the attribute. If no value is found, the tag body is printed instead. The format is used as the query:field tag.


Syntax
<attr:getAttribute name="attributeName" scope="[|page|request|session|application]" format="...">default value</attr:getAttribute>


setAttribute Tag
The setAttribute tag sets the named attribute's value in the specified scope. If no scope is specified, page is assumed. The value is either the value specified in the value attribute, or if none is specified, the tag body is used.


Syntax
<attr:setAttribute name="attributeName" value="..." scope="[page|request|session|application]">value</attr:setAttribute >


getParameter Tag
The getParameter tag prints the named parameter's value. If no parameter value exists, the tag body is printed instead. The format attribute is used as the query:field tag.


Syntax
<attr:getParameter name="parameterName" format="urlEncode">default value</attr:getParameter>


Get Remote User Tag
The getRemoteUser tag prints the servlet's remote user name.


Syntax
<attr:getRemoteUser>default value</attr:getRemoteUser>


Example
For more information, see the examples in "LDAP Tag Library" and "Conditional Tag Library."


JSP Load Balancing

Servlets can be load balanced because each servlet has a GUID associated with it. You simply distribute the servlet across all the iPlanet Application Server instances. However, JSPs are converted by iPlanet Application Server into servlets at runtime and initially have no individual GUIDs associated with them. This makes load balancing and failover of JSPs impossible when they are called directly from the browser (as opposed to being called through a servlet).

iPlanet Application Server 6.5 supports load balancing of JSPs individually. To obtain load balancing and failover capabilities for JSPs called directly from the browser, follow these steps:

  1. In the XML descriptor, assign a GUID to each JSP you want to load balance. For details about assigning GUIDs to JSPs, see "Registered JSPs."

  2. In iPlanet Application Server, JSPs are run using the system servlets JSPRunner and JSPRunnerSticky. These servlets are registered at the time of installation. Use the Administration Tool to make these system servlets distributed across the servers you want to include in the load balancing.

  3. Check the servlet component properties of System_JSPRunner and System_JSPRunnerSticky. Make sure that all the servers across which JSPs are to be load balanced are listed correctly.

  4. Load balance the JSP just you would a servlet, through the administrative tool. Distribute the JSPs across the servers you want to include in the load balancing.

  5. Restart the web server.

For details about distributing application components and changing component properties, see the Administrator's Guide.


JSP Page Caching

A new feature called JSP caching aids in compositional JSP development. This provides functionality to cache JSPs within the Java engine, thereby allowing a master JSP to include multiple JSPs (for example, a portal page). Each can be cached using different cache criteria. Think of a portal page containing a window to view stock quotes, another to view weather information, and so on. The stock quote window can be cached for 10 minutes, the weather report window for 30 minutes, and so on.

Note that JSP caching is in addition to results caching. A JSP can be composed of several JSPs, each having separate cache criteria. The composed JSP can be cached in the KXS using the results caching with a GUID. For more information, see "Registered JSPs."



Note If you use your own request object in a JSP (extended from HttpServletRequest) and use the Jasper JSP compiler, the JSP caching provided by CacheLib.tld is not supported for that JSP.



JSP caching uses the custom tag library support provided by JSP 1.1. A typical cacheable JSP page looks like this:

<%@ taglib prefix="ias" uri="CacheLib.tld"%>
<ias:cache>
<ias:criteria timeout="30">
<ias:check class="com.iplanet.server.servlet.test.Checker"/>
<ias:param name="y" value="*" scope="request"/>
</ias:criteria>
</ias:cache>
<%! int i=0; %>
<html>
<body>
<h2>Hello there</h2>
I should be cached.
No? <b><%= i++ %></b>
</body>
</html>

The <ias:cache> and </ias:cache> tags delimit the cache constraints. The <ias:criteria> tag specifies the timeout value and encloses different cache criteria. Cache criteria are expressed using any or both tags, <ias:check> and <ias:param>. The tag syntax is as follows:

  • <ias:criteria timeout="val" > - specifies the cached element timeout, in seconds. The cache criteria are specified here before the closing </ias:criteria>.

  • <ias:check class="classname" /> - is one mechanism of specifying cache criteria. The classname refers to a class that has a method called check, which has the following signature:

    public Boolean check(ServletRequest, Servlet)

    This returns a boolean value indicating if the element is to be cached or not.

  • <ias:param name="paramName" value="paramValue" scope="request" /> - is the other mechanism to specify cache criteria.

paramName is the attribute name, passed in either request object (using setAttribute) or in the URI. This parameter is used as the cache criterion.

Table 3-13 shows the paramValue parameter values, which determine if caching is performed or not.


Table 3-13    paramValue Parameter Values

Constraint

Description

x = ""  

x must be present either as a parameter or as an attribute.  

x = "v1|...|vk", where vi might be "*"  

x is mapped to one of the strings (parameter/attribute). If x=*, then the constraint is true of the current request if the request parameter for x has the same value as was used to store the cached buffer.  

x = "1-u", where 1 and u are integers.  

x is mapped to a value in the range [1,u]  

The scope identifies the attribute sources to be checked and can be page, request (default), session, or application.


Example
The following example represents a cached JSP page:

<%@ taglib prefix="ias" uri="CacheLib.tld"%>
<ias:cache>
<ias:criteria timeout="30">
<ias:check class="com.iplanet.server.servlet.test.Checker"/>
<ias:param name="y" value="*" scope="request"/>
</ias:criteria>
</ias:cache>
<%! int i=0; %>
<html>
<body>
<h2>Hello there</h2>

I should be cached.

No? <b><%= i++ %></b>
</body>
</html>

where Checker is defined as:

package com.iplanet.server.servlet.test;

import com.iplanet.server.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Checker {
   String chk = "42";
   public Checker()
   {

   }
   public Boolean check(ServletRequest _req, Servlet _serv)
   {

      HttpServletRequest req = (HttpServletRequest)_req;
      String par = req.getParameter("x");
      return new Boolean(par == null ? false : par.equals(chk));
   }
}

Given the above, a cached element is valid for a request with parameter x=42 and y equal to the value used to store the element. Note that it is possible to have multiple sets of <ias:param> and <ias:check> inside an <ias:criteria> block. Also, it is possible to have multiple <ias:criteria> blocks inside a JSP.


Previous     Contents     Index     Next     
Copyright © 2002 Sun Microsystems, Inc. All rights reserved.

Last Updated March 06, 2002