Previous Next Contents Index


Presenting Application Pages with JavaServer Pages

This chapter describes how to use JavaServer Pages (JSPs) as page templates in Netscape Application Server applications.

This chapter contains the following sections:


Introducing JavaServer Pages
JavaServer Pages (JSPs) are browser pages in HTML or XML. They can optionally contain Java code, which enables them to perform complex processing, conditionalize output, and communicate with other objects in your application. JSPs are based on the JSP specification. All specifications are accessible from installdir/nas/docs/index.htm, where installdir is the location in which you installed NAS.

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


How JSPs Work
NAS compiles JSPs into servlets the first time they are called. This makes them available to the application environment as standard objects, and it also enables them to be called from a client using a URL. Think of servlets and JSPs as opposite sides of the same coin: each can perform the tasks of the other, but JSPs, as browser files, are best suited for layout tasks, while servlets are best suited for tasks that require Java code.

You can create JSPs that are not a part of any particular application. These JSPs are considered to be part of a generic application. JSPs can also run in the Netscape Enterprise Server (NES) and other web servers, but these JSPs have access to any application data, which makes their use limited.

JSPs that are included using a server-side include are compiled into the JSP when it is first compiled into a servlet.

A JSP and some other application components can be updated at run time without restarting the server, making it easy to change the look and feel of your application without stopping service. For more information, see Dynamic Reloading.

Responding to the Client

The response object contains a reference to the calling client, and this is where a JSP presents the page that it creates. If you call a JSP using the forward() method from the RequestDispatcher interface, forward() provides the response object as a parameter to the JSP. If a JSP is invoked directly from the client, the response object is provided by the server that is managing the relationship with the client.

In either case, the page is automatically returned to the client through the reference provided in the response object. You do not have to write any code to return a page to a client.


Designing JSPs
This section describes some of the decisions you must consider when you write JSPs. Since JSPs are compiled into servlets, the design considerations for servlets are also relevantto JSPs. See Designing JSPs.

The information on a page can loosely be categorized into page layout elements, which consists of tags and information pertaining to the structure of the page, as well as page content elements, which consists of the actual information your page presents to the user.

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

Since page layout is a more or less straightforward task, the design decisions you must make are related more to the way the JSP interacts with the rest of the application and how it is optimized.

The following sections describe specific design issues:

Designing for Ease of Maintenance: How Many JSPs? Each of your JSPs can call or include any number of other JSPs. For example, you could have a generic corporate banner, a standard navigation bar, and left-side column table of contents, each of which resides in a separate JSP that you include for each page you build. This situation is also a good candidate for using HTML frames.

A JSP can be included using a server-side include (SSI) or by including it using the include() method in the RequestDispatcher interface. You can also hand control of an interaction to a separate JSP using RequestDispatcher.forward().

Designing for Portability: Generic JSPs You can write JSPs that are completely portable between different applications and different servers. They have a disadvantage in that they have no knowledge of application data in particular, but this is only a problem if they require that kind of data.

One possible use for generic JSPs is as portable page elements, like navigation bars or corporate headers and footers, that are meant to be included in other JSPs. You can create a library of reusable generic page elements to use throughout your 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 makes a change to the page's structure based on a standard value in the request object.


Creating JSPs
You create JSPs in much the same way that you create static browser pages (HTML or XML files), with the exception that you can add JSP-specific tags in order to provide powerful, conditional routines to dynamically create the content in your pages.

Also, there are a set of JSP tags specifically for embedding Java scripts in your JSPs. These scripts are called scriptlets, and can contain any Java code relevant to the environment in which the JSPs run. This means that JSPs have access to all of an application's components, including EJBs.

There are two types of JSP tags, described in the following sections.

Using Java Beans JSPs support several tags for the purpose of instantiating and accessing Java beans to perform complex calculations and storing data. You use beans to perform computations in order to obtain a set of results, which are stored as bean properties. JSPs provide automatic support for creating beans and for examining their properties.

Beans themselves are separate classes. For more information about Java beans, see Creating Java Beans, and also visit the site http://java.sun.com/beans.

Note. Note that this support is for standard Java beans, not EJBs. To access EJBs from your JSP, see Accessing Business Objects.

There are two implicit beans in all JSPs, the request bean, which encapsulates the same data as the request object in a servlet, and the exception bean, which contains information about the last error encountered by the JSP. For more information, see Implicit Beans.

JSP Tags that Support Beans
JSPs support beans with seven tags, described in the following sections:

Note. In JSPs, a hierarchical naming scheme is used to describe bean properties. The use of colons : rather than periods . as separators helps distinguish this naming convention from Java syntax. (Note that a property may, itself, be a Bean containing further properties, as in superman:costume:cape:color.) Hierarchical naming is not used in the <USEBEAN> tag, where the attributes NAME and TYPE both use the Java variable naming convention.

<USEBEAN>

This set of tags makes a bean available for use later in the JSP. Note that you do not have to write <USEBEAN> to access implicit beans.

The general form of <USEBEAN> is:

<USEBEAN NAME="nameofbeaninstance" 
         TYPE="nameofbeanclass" 
         LIFESPAN="page|session|application" > 
<SETONCREATE>
</USEBEAN> 
The attributes are all required and are defined as follows:

Attribute
Definition
NAME
Identifies the name of that specific instance of the Bean. The name must adhere to Java variable naming conventions and should not appear more than once per file. This value is case-sensitive.
TYPE
The value of the TYPE attribute is the name of the class that defines the bean. The value of this attribute is case-sensitive.
LIFESPAN
This attribute defines the bean's scope. One of the following:

Optionally, the <USEBEAN> tags may enclose one or more <SETFROMREQUEST> or <SETONCREATE> tags, or a combination of these, but no HTML or JSP tags are allowed between <USEBEAN> and </USEBEAN>.

You must declare <USEBEAN> tags for a bean before accessing any property of that bean, except for implicit beans.

For example:

<USEBEAN NAME="clock" 
         TYPE="calendar.JspCalendar" 
         LIFESPAN="page"> 
</USEBEAN> 
Once a bean is declared, it can be accessed later in the file. For example:

<p>The name of the current month is <%= clock.getAttribute("month") %>. 
<SETONCREATE>

This tag enables you to set initial properties in a bean if the JSP file creates the bean. You can only use this tag between <USEBEAN> tags.

The general form of <SETONCREATE> is:

<SETONCREATE BEANPROPERTY="propertyname" VALUE="propertyvalue">
The attributes are all required and are defined as follows:

Attribute
Definition
BEANPROPERTY
The name of the bean property whose value you wish to set. The property name must follow Java variable-naming conventions rather than hierarchal naming conventions.
VALUE
A value to be assigned to the named bean property.

For example:

<USEBEAN NAME="clock" 
         TYPE="calendar.JspCalendar" 
         LIFESPAN="page"> 
<SETONCREATE BEANPROPERTY="year" VALUE="1999">
</USEBEAN>
<SETFROMREQUEST>

This tag enables you to specify request parameters that are examined by the bean's property setter methods. In other words, you can use this tag to copy parameters from the incoming request into a newly-created bean. You can only use this tag between <USEBEAN> tags.

The general form of <SETFROMREQUEST> is:

<SETONCREATE BEANPROPERTY="*|propertyname" PARAMNAME="propertyvalue">
The attributes are defined as follows:

Attribute
Definition
BEANPROPERTY
Required. Either an asterisk * that acts as a wildcard, or a property name for the bean. The property name must follow Java variable-naming conventions rather than hierarchal naming conventions.
PARAMNAME
Optional. A value to be assigned to the named bean property.

There are three behaviors with this tag:

<DISPLAY>

This tag displays a specific bean property.

The general form of <DISPLAY> is:

<DISPLAY PROPERTY="[beanname:+]property" 
         PLACEHOLDER="substitutevalue">
The plus sign + indicates that more than one property can exist.

The attributes are all required and are defined as follows:

Attribute
Definition
PROPERTY
Required. Bean property to display, expressed using a hierarchical naming scheme. This attribute is case-sensitive.
PLACEHOLDER
Optional. A value to be displayed if the requested property value is missing or invalid.

Two examples of <DISPLAY>:

<img src="<DISPLAY PROPERTY=hero.imageURL>">
<DISPLAY PROPERTY="superman:favoriteDrink"
         PLACEHOLDER="<H3>Unknown!</H3>">
<LOOP>

This tag provides a mechanism to display a list of values with <DISPLAY>. A <LOOP> tag can contain a <DISPLAY> tag or another (nested) <LOOP> tag.

The general form of <LOOP> is:

<LOOP PROPERTY="beanname:indexedproperty" 
      PROPERTYELEMENT="x" >
<DISPLAY PROPERTY="x" PLACEHOLDER="substitutevalue"> 
</LOOP>
The attributes are all required and are defined as follows:

Attribute
Definition
PROPERTY
The name of the multiple-valued bean property you wish to display. The bean should return either an array or a value and index. This property takes one of the following forms:
PROPERTYELEMENT
Place-holder for the property name, to be used as the value for PROPERTY in the enclosed <DISPLAY> tag. This attribute enables nested loops to display different properties, as in the examples below.

This example shows a loop through the property superman:allergies:

<h2>Superman's Allergies:</h2>
<LOOP PROPERTY="superman:allergies" 
      PROPERTYELEMENT="x" > 
<DISPLAY PROPERTY= "x" PLACEHOLDER="not found"> 
</LOOP>
This example shows a two-dimensional loop through two related properties:

<h2>Phone numbers for grocery store deli departments: </h2>
<LOOP PROPERTY="store:grocery" 
      PROPERTYELEMENT="i">
  <LOOP PROPERTY="i:phoneNumbers" 
        PROPERTYELEMENT="j"> 
    <DISPLAY PROPERTY= "j:storeName">: <DISPLAY PROPERTY= "j:deliDept"> 
  </LOOP> 
</LOOP>
<INCLUDEIF>

Use this tag to conditionally include a block of HTML code. The condition is based on the value of a bean property; if the condition evaluates to true, the enclosed HTML code is displayed in the final page, otherwise it is not.

The general form of <INCLUDEIF> is:

<INCLUDEIF PROPERTY="bean[:property]+" 
           VALUE="valuetomatch" 
           CASE="sensitive|insensitive
           MATCH="null|exact|contains|startswith|endswith">
The attributes are defined as follows:

Attribute
Definition
PROPERTY
The name of the multiple-valued bean property you wish to compare with VALUE.
VALUE
Value to match against PROPERTY.
CASE
Determines whether to match case, if the property is a String. Specify either sensitive or insensitive. The default is insensitive. If MATCH is specified, the comparison is automatically case-insensitive.
MATCH
Determines matching characteristics if the property is a String. The default is exact. If MATCH is specified, the comparison is automatically case-insensitive. Values are:

For example:

<INCLUDEIF PROPERTY="budget:validItems" VALUE="lunch" 
           CASE="insensitive MATCH="contains"> 
<b>Reminder:</b> Take team to lunch. </INCLUDEIF> 
<EXCLUDEIF>

Use this tag to conditionally exclude a block of HTML code. The condition is based on the value of a bean property; if the condition evaluates to true, the enclosed HTML code is not displayed in the final page, otherwise it is.

The general form of <EXCLUDEIF> is:

<EXCLUDEIF PROPERTY="bean[:property]+" 
           VALUE="valuetomatch" 
           CASE="sensitive|insensitive
           MATCH="null|exact|contains|startswith|endswith">
The attributes are defined as follows:

Attribute
Definition
PROPERTY
The name of the multiple-valued bean property you wish to compare with VALUE.
VALUE
Value to match against PROPERTY.
CASE
Determines whether to match case, if the property is a String. Specify either sensitive or insensitive. The default is insensitive. If MATCH is specified, the comparison is automatically case-insensitive.
MATCH
Determines matching characteristics if the property is a String. The default is exact. If MATCH is specified, the comparison is automatically case-insensitive. Values are:

For example:

<EXCLUDEIF PROPERTY="budget:invalidItems" VALUE="lunch" 
           CASE="insensitive MATCH="contains"> 
<b>Reminder:</b> Take team to lunch. </INCLUDEIF> 
Creating Java Beans
It is beyond the scope of this manual to describe how to create standard Java beans, since beans are described in their specification. There are many tutorials that describe how to create beans, some of which are accessible from the official site, http://java.sun.com/beans.

These are a few general tips regarding beans used in JSPs:

Example Java Bean Access in a JSP

The following example shows a JSP called ColorSize.jsp that accesses a Java bean called ColorSizeBean. This example shows how to use the JSP tags described in this section.

ColorSize.jsp:

<USEBEAN NAME="csBean" 
        TYPE="com.netscape.server.servlet.test.ColorSizeBean"
    LIFESPAN="page">
  <SETONCREATE    beanproperty="fontSize" value="3">
  <SETFROMREQUEST beanproperty="fontSize" paramname="size">
</USEBEAN>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML> 
<HEAD> <TITLE>Untitled</TITLE> </HEAD>
<BODY>
<!--- import the bean -->
<%@ import="com.netscape.server.servlet.test.ColorSizeBean" %>
<INCLUDEIF property="csBean:fontSize" value="6">
Hey, your font size is 6!<p>
</INCLUDEIF>
<EXCLUDEIF property="csBean:fontSize" value=4>
Hey, your font size is not 4!<p>
</EXCLUDEIF>
<table border=1>
<tr>
    <td align="center" colspan=2>
        <FONT SIZE=<DISPLAY property="csBean:fontSize">>
        Hello World
        </font>
    </td>
</tr>
<tr>
    <td align="center">
<a href="/servlet/ColorSize.jsp?size=<%= csBean.add(-1) %>">SMALLER</a>
    </td>
    <td align="center">
<a href="/servlet/ColorSize.jsp?size=<%= csBean.add(1) %>">BIGGER</a>
    </td>
</tr>
</table>
<p>Your current font size is:  <DISPLAY property="csBean:fontSize">
<p>Your current counter is:  <DISPLAY property="csBean:counter">
</BODY>
</HTML>
ColorSizeBean.java

package com.netscape.server.servlet.test;
import com.netscape.server.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorSizeBean implements java.io.Serializable {
    int counter = 0;
    private int size = 1;
    public int getFontSize() {
        return size;
    }
    public void setFontSize(int i) {
        size = i;
    }
    public int add(int x) {
        return size+x;
    }
    public int getCounter()
{
        return counter;
    }
    public void processRequest(HttpServletRequest req) {
        counter++;
    }
}
Implicit Beans
There are two "implicit" beans that exist for each JSP:

The request bean contains two nested beans:

For more information about implicit beans, consult the JSP specification. All specifications are accessible from installdir/nas/docs/index.htm, where installdir is the location in which you installed NAS.

Embedded Java You can embed Java code in your JSP in the form of directives, declarations, scriptlets (small Java scripts), and expressions. Attribute values do not require double quotes around them unless they contain spaces, but double quotes are recommended.

The components you can use to embed Java code in your JSP are described in the following table. In all cases, make sure to put a space character between the tag opening the component and any attributes it contains. For example, <%= myBean.someVariable %> is valid, but <%=myBean.someVariable %> is not.

Java Directives
<%@ variable="value" %> 
Use directives to set preferences within the JSP. Possible directives to set are:

For example:

<%@ errorpage="errorpg.htm" 
    import="java.io.*,javax.naming.*"%> 
Java Declarations
<SCRIPT RUNAT="..."> ...
</SCRIPT> 
Use declarations to define variables that are valid throughout the JSP. The attribute RUNAT describes where the script runs; valid values are client and server. Set to server for all JSPs, otherwise the script is simply passed to the client.

For example:

<SCRIPT RUNAT="server">
int i=0;
String scriptname="myScript";
private void myMethod () { ... }
</SCRIPT> 
Java Scriptlets
<% ... %> 
Use scriptlets to define blocks of code to be executed. For example:

<% C balance = request.getAttribute("balance");
printValueAsHTML(balance); %> 
There are four pre-defined implicit variables that you can use within a scriptlet (that is, between <% and %>):

Implicit variable
Description
request
The request object, as defined by javax.servlet.http.HttpServletRequest.
response
The response object, as defined by javax.servlet.http.HttpServletResponse.
in
The servlet input reader class, as defined by java.io.BufferedReader. This variable represents input from the client.
out
The servlet output writer class, as defined by java.io.PrintWriter. This variable represents output to the client.

Java Expressions
<%= ... %> 
Use expressions as variables to be evaluated. The value of the expression is substituted where the expression occurs. For example:

<p>My favorite color is <%= userBean.favColor %>.</p> 
Including Other JSPs Corporate headers and footers can be included on each page appropriately by creating page stubs that contain just the included elements. Note that it is possible to include entire HTML pages on a conditional basis, which provides much more flexibility than simply inserting flat navigation bars or corporate headers.

The following example shows how each portion of a page can be provided by a separate JSP. The example page is followed by the code that constructs it.

There are three ways to include a JSP in your JSP. These methods are discussed in the following sections.

Note. You identify which JSP to call by specifying a path relative to AppPath, with a leading slash / if the JSP is part of the generic application. For instance, if your JSP is part of an application called OnlineOffice, you would refer to a JSP called ShowSupplies.jsp as OnlineOffice/ShowSupplies.jsp. On the other hand, if ShowSupplies.jsp is part of the generic application and is in a subdirectory, specify the subdirectory with a leading slash, as in /GenericJSPs/ShowSupplies.jsp.

Warning. If included JSPs are self-contained with HTML tags, some browsers may not display properly. The included JSP should only contain parts of the head and body.

Including JSPs Using SSI
A JSP can be included from another JSP using a server-side include (SSI). This is similar to a macro call; the called JSP is inserted inline into the calling JSP when it is compiled, resulting in a single callable object.

Also, variable names that are common to both the including JSP and the included JSP, which can cause compile-time errors in the single generated servlet. To avoid this, use separate variable names in all servlets that include or are included in other servlets.

A tutorial that discusses server-side includes (SSI) can be found at:
http://hoohoo.ncsa.uiuc.edu/docs/tutorials/includes.html

Usage

You specify an included file as follows:

<!--#include virtual="directory" file="filename" -->
The file attribute instructs the server to search for the listed filename beginning in the directory listed in the virtual attribute, or in the current directory if virtual is not specified. virtual is a directory path relative to AppPath, a NAS registry variable that indicates the top of the application tree. file can contain slashes to indicate subdirectories of virtual.

The JSP specification introduces another use for these attributes, namely:

<!--#include virtual="filename" --> 
In this case, filename is the full sub-path to the included file, starting at AppPath.

NAS does not support the exec="" SSI command.

Example

This example code shows a JSP that generates the page sample page shown above by including the output from other JSPs using server-side includes:

<html>
<head><title>Sample Corporate Page</title></head>
<body>
<!--#include virtual="" file="corpHead.jsp" --> 
<!--#include file="navBar.jsp" --> <!-- in current directory -->
<hr>
<table border=0><tr>
<td width="30%"><!--#include file="appToc.jsp" --></td>
<td width="70%"><!--#include file="welcome.jsp" --></td>
</tr></table>
<!--#include file="corpFoot.jsp" -->
</body></html> 
Calling JSPs Using include
The include() method in the RequestDispatcher interface calls a JSP and waits for it to return before continuing to process the interaction. Since this is a Java method rather than a server-side include, the included JSP is compiled separately and exists as a separate object that can be reused.

Usage

This example shows a JSP invocation using include():

<% RequestDispatcher dispatcher = 
    getServletContext().getRequestDispatcher("JSP_URI.jsp"); 
dispatcher.include(request, response);
%> 
You identify which JSP to call by specifying a URI, or Universal Resource Identifier. This is normally a path relative to AppPath, with a leading slash / if the JSP is part of the generic application. For instance, if your JSP is part of an application called OnlineOffice, you would refer to a JSP called ShowSupplies.jsp as OnlineOffice/ShowSupplies.jsp. On the other hand, if ShowSupplies.jsp is part of the generic application and is in a subdirectory, specify the subdirectory with a leading slash, as in /GenericJSPs/ShowSupplies.jsp.

Example

This example creates the sample page shown above using include():

<html>
<head><title>Sample Corporate Page</title></head>
<body>
<% 
(RequestDispatcher)getRequestDispatcher("corpHead.jsp").include(request
, response);
(RequestDispatcher)getRequestDispatcher("navBar.jsp").include(request, 
response); %> 
<hr>
<table border=0>
<tr>
  <td width="30%">
   <% 
(RequestDispatcher)getRequestDispatcher("appToc.jsp").include(request, 
response) %>
  </td>
  <td width="70%">
   <% 
(RequestDispatcher)getRequestDispatcher("welcomePage").include(request, 
response) %>
  </td>
</tr>
</table>
<% 
(RequestDispatcher)getRequestDispatcher("corpFooter").include(request, 
response) %>
</body></html>
Forwarding JSPs Using forward
The forward() method in the RequestDispatcher interface hands control of the interaction to another JSP. The original JSP is no longer involved with output for the current interaction after invoking forward(), thus only one forward() call can be made in a particular JSP.

This example shows a JSP invocation using forward():

<% RequestDispatcher dispatcher = 
    getServletContext().getRequestDispatcher("JSP_URI.jsp"); 
dispatcher.forward(request, response); 
%> 
You identify which JSP to call by specifying a URI, or Universal Resource Identifier. This is normally a path relative to AppPath, with a leading slash / if the JSP is part of the generic application. For instance, if your JSP is part of an application called OnlineOffice, you would refer to a JSP called ShowSupplies.jsp as OnlineOffice/ShowSupplies.jsp. On the other hand, if ShowSupplies.jsp is part of the generic application and is in a subdirectory, specify the subdirectory with a leading slash, as in /GenericJSPs/ShowSupplies.jsp.

Page Content Elements At development time, a JSP contains placeholders for page content. The content itself is generated at run time and accessed by the JSP either through attributes in the request object that contain the required information, or directly from the business objects that control the content (EJBs, via a JNDI proxy). JSPs have access to the same public variables controlled by the servlet which called it.

Of course, since JSPs are compiled into servlets when they are first accessed, you can perform presentation logic tasks with JSPs as well. However, the programming model discourages this in favor of using servlets for presentation logic and EJBs for business logic. The exception is in cases where the logic is simple, such as name lookups.

Dynamic content can be accessed by a JSP in three ways:

Accessing the Request Object
You can access parameters and attributes of the request object as a standard system variable using the <% ... %> JSP tag. Parameters are name-value pairs sent from the client, including form field data, HTTP header information, etc. Attributes are name-value pairs that can be set by servlets, and so are not present if the JSP is called directly from via a URL.

For example, in a servlet, you can request an account balance and store the result as an attribute of the request object using setAttribute(), as in this example from a servlet:

request.setAttribute("balance", balance); 
You can then access that variable from the JSP using getAttribute():

<% C balance = request.getAttribute("balance"); %> 
Similarly, you can access a parameter from the request using getParameter() in your JSP:

<% String name = request.getParameter("username"); %> 
This example shows how a short Java loop can be written to display arrays:

<table border=1> 
<% for ( i=0 ; i < request.getAttribute("totalRecords") ; i++ ) { %> 
    <td align=left><%= request.getAttribute(attribute[i]) %></td>
</table>
Accessing Business Objects
Because JSPs are compiled into servlets at run-time, they have full access to the rest of the processes running in the server, including EJBs. You can access beans or servlets in the same way you would access them from a servlet, as long as the Java code you write is embedded inside an escape tag.

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

We recommend you use servlets rather than JSPs to contact EJBs in order to properly partition the presentation components in your application: servlets are best suited for presentation logic, JSPs are best suited for presentation layout.

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

<%@ import cart.ShoppingCart %>;
...
<% // Get the user's session and shopping cart 
   HttpSession session = request.getSession(true); 
   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 the use of JNDI to look up a proxy, or handle, for the cart:

<% String jndiNm = "Bookstore/cart/ShoppingCart"; 
   javax.naming.Context initCtx; 
   Object home; 
       try { 
             initCtx = new javax.naming.InitialContext(env); 
       } 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 usually provide a method in the EJB to convert raw data to a format acceptable on the page, such as getDataAsHTML() in the examples above.

For more information on contacting EJBs, see Accessing Business Logic Components.


Invoking JSPs
You can invoke a JSP programmatically from a servlet, or you can address it directly from a client using a URL. You can also include JSPs as well as invoke them; see Including Other JSPs.

Calling a JSP With a URL You can call JSPs using URLs embedded as links in your application's pages. This section describes how to invoke servlets using standard URLs.

Invoking JSPs in a Specific Application
JSPs that are part of a specific application are addressed as follows:

http://server:port/NASApp/appName/jspName?name=value 
Each section of the URL is described in the table below:

URL element
Description
server:port
Address and optional port number for the web server handling the request.
NASApp
Indicates to the web server that this URL is for a NAS application, so the request is routed to the NAS executive server. This element is configurable by editing the following registry entry:
Software\Netscape\Application Server\4.0\

CCS0\HTTPAPI\SSPL_APP_PREFIX.
appName
The application's name, which must be identical to the name of the application's subdirectory under AppPath.
jspName
The JSP's filename, including the .jsp extension.
?name=value...
Optional name-value parameters to the JSP. These are accessible from the request object.

For example:

http://www.my-company.com/NASApp/OnlineBookings/directedLogin.jsp 
Invoking JSPs in the Generic Application
JSPs that are not part of a specific application are addressed as follows:

http://server:port/servlet/jspName?name=value 
Each section of the URL is described in the table below:

URL element
Description
server:port
Address and optional port number for the web server handling the request.
servlet
Indicates to the web server that this 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.leMort.com/servlet/calcMort.jsp?rate=8.0&per=360&bal=180000 
Invoking a JSP Programmatically A servlet can invoke a JSP in one of two ways:

For more information on these methods, seeDelivering Results to the Client.

A JSP can also invoke another JSP. For more information, see Including Other JSPs.

 

© Copyright 1999 Netscape Communications Corp.