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:
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:
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:
There are three behaviors with this tag:
<SETFROMREQUEST BEANPROPERTY="dogName" PARAMNAME="dogName">
<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:
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:
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:
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:
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 %>):
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.