Oracle® Containers for J2EE Support for JavaServer Pages Developer's Guide 10g (10.1.3.1.0) Part Number B28961-01 |
|
|
View PDF |
This chapter introduces and reviews standard features and functionality of JavaServer Pages (JSP) technology, then concludes with a discussion of JSP execution models. For further general information, consult the JavaServer Pages Specification, Version 2.0 published by Sun Microsystems.
The chapter contains the following sections:
Note: The Sample Applications chapter available in previous releases has been removed.Sample code and applications are available from the following location on the Oracle Technology Network: |
A quick overview of JSP is provided in the following sections:
In simple terms, JavaServer Pages (JSP) technology makes it possible for dynamically-generated content to be displayed in a Web browser. JSP pages comprise the presentation layer for any Web-based application running in the Oracle Application Server environment, providing the interface into the application's business logic and processing power.
A JSP page is simply a text file containing two types of text markup:
HTML or XML, used to format static content such as page layout and template text; and
JSP syntax elements and possibly embedded Java code, which provide the dynamic content.
Ease of development allows rapid implementation. With the latest release, it is not even necessary for JSP page authors to have a strong understanding of Java.
JavaServer Pages require a Web container that supports JSP page translation and execution. This Web container is provided as part of the Oracle Containers for J2EE (OC4J). See Chapter 2, "The Oracle JSP Implementation" for more on OC4J functionality.
JSP is a key technology of the Java 2 Platform, Enterprise Edition (J2EE) architecture specified by Sun Microsystems. The OC4J Web container is fully compliant with Sun's JSP 2.0 and Servlet 2.4 specifications.
For most situations, there are at least three general advantages to using JSP pages instead of servlets:
Ease of coding
JSP syntax provides a shortcut for coding dynamic Web pages, typically requiring much less code than equivalent servlet code. The JSP translator also automatically handles some servlet coding overhead for you, such as implementing standard JSP or servlet interfaces and creating HTTP sessions.
Separation of static content and dynamic content
JSP technology attempts to allow some separation between the HTML code development for static content, and the Java code development for business logic and dynamic content. This makes JSP programming accessible and attractive to Web designers, as it simplifies the division of maintenance responsibilities between presentation and layout specialists and Java developers.
Reuse of business logic components
JSP technology is designed to facilitate the use of reusable components such as JavaBeans and Enterprise JavaBeans (EJBs). JSP tag libraries, typically supplied with J2EE applications, provide additional coding convenience.
The dynamic nature of a JSP page is enabled through JSP elements embedded within the HTML (or other markup code, such as XML) of your Web pages. These elements provide access to external Java components, such as JavaBeans and Enterprise JavaBeans (EJB), that provide a Web application's business logic and processing power. These components can in turn directly or indirectly access a database or other EIS.
A JSP page is translated into a Java servlet, typically at the time that it is requested from a client. The JSP translator is triggered by the.jsp
file name extension in a URL. The translated page is then executed, processing HTTP requests and generating responses similarly to any other servlet. Note that coding a JSP page is dramatically more convenient than coding the equivalent servlet.
Furthermore, JSP pages are fully interoperable with servlets—JSP pages can include output from a servlet or forward to a servlet, and servlets can include output from a JSP page or forward to a JSP page.
Here is the code for a simple JSP page, welcomeuser.jsp
:
<%@ page import="java.util.*" %> <HTML> <HEAD><TITLE>The Welcome User JSP</TITLE></HEAD> <BODY> <H3>Welcome ${param.user}!</H3> <P><B> Today is ${Date}. Have a fabulous day! :-)</B></P> <B>Enter name:</B> <FORM METHOD=GET> <INPUT TYPE="text" NAME="user" SIZE=5> <INPUT TYPE="submit" VALUE="Submit name"> </FORM> </BODY> </HTML>
This JSP page will produce something like the following output if the user inputs the name "Amy":
Welcome Amy! Today is Wed Jun 2 3:42:23 PDT 2000. Have a fabulous day! :-)
Figure 1-1 illustrates a conceptual overview of the flow of execution when a user calls a JSP page by specifying its URL in the browser. Assume that Hello.jsp
accesses a database.
Because of the.jsp
file name extension, the following steps occur automatically:
The JSP translator is invoked, translating Hello.jsp
and producing the file Hello.java
.
The Java compiler is invoked, creating Hello.class
.
Hello.class
is executed as a servlet, using the JSP runtime library.
The Hello
class accesses the database through JDBC, as appropriate, and sends its output to the browser.
Figure 1-1 JSP Translation and Runtime Flow
The example below illustrates how HTML markup and JSP elements are used together to provide static and dynamic content in a typical JSP. The dynamic content is written in JSP 2.0 syntax, which is fully supported by the OC4J JSP container.
Note: The JSP 2.0 specification supports an XML-compatible JSP syntax as an alternative to the traditional syntax. This allows you to produce JSP pages that are syntactically valid XML documents. The XML-compatible syntax is described in Chapter 8, "Understanding JSP XML Support in OC4J". |
The JSP displays all of the phone numbers stored in the database for the employee specified in the HTTP request. The code creates a JavaBean object containing the employee's phone numbers as a Map of key/value pairs. The JSP iterates over the phone numbers, displaying each key and its value in an HTML table.
<%@ page contentType="text/html; charset=UTF-8"; import="mypkg.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head><title>Phone List</title></head> <body> <jsp:useBean id="employee" scope="application" class="mypkg.Employee"/> <jsp:setProperty name="employee" property="empUserId" param="employeeId"/> <c:set var="empName" value="${employee.fullName}" /> <h2>Current Phone Numbers for ${empName}</h2> <c:if test ="${!empty employee.phoneNumbers}> <table> <tr> <th>Phone Type:</th><th>Number:</th> </tr> <c:forEach var="entry" items="{$employee.phoneNumbers}"> <tr> <td>${entry.key}</td> <td>${entry.value}></td> </tr> </c:forEach> </table> </c:if> <c:if test="${empty employee.phoneNumbers}"> <c:out value="No phone numbers were found for ${empName}"> </c:if> </body> </html>
The JSP elements used in the example are as follows:
Directives provide the OC4J container with instructions specifying how the JSP is to be processed.
The page
directive (<%@ page ... %>
) used in this example specifies the content type returned by the page and imports the mypkg
package for use. The taglib
directive ( <%@ taglib ... %>
) imports a custom tag library for use in the page; in this case, the JavaServer Pages Standard Tag Library (JSTL) core library.
Standard action tags provide easy mechanisms for invoking certain common tasks, such as forwarding execution to another JSP or creating an object and accessing its properties.
In this example, the jsp:useBean
standard action returns an Employee
JavaBean instance.
The jsp:setProperty
tag sets the value of a bean property; in this case, it sets the empUserId
property to the value of the employeeId
request parameter.
Custom tags are similar to standard action tags, except that they are created and packaged by software vendors and page authors - such as yourself. Custom tags allow JSP pages to access logic provided by reusable Java classes, removing the need to embed Java code directly in pages themselves.
Note how c:forEach
tags are used to iterate over the user's phone numbers, while c:if
tags are used to test whether phone numbers are found for the given user, and to print a message if not.
Every custom tag belongs to a tag library, indicated by the tag prefix. Here, the prefix c:
identifies the tags used as belonging to the JSTL core
tag library. See Chapter 7, "Working with Custom Tags" for details on creating and using custom tags.
JSP expression language (EL) expressions, identifiable by the ${ ... }
syntax, provide easy access to objects such as JavaBeans and their properties.
The EL is an alternative to the Java expressions used in traditional JSP syntax. For example, the EL expression${employee.fullName}
is equivalent to the JSP scripting expression <% = employee.getFullName() %>
.
See "Simplified JSP Authoring with the Expression Language" for details.
The following section discusses the basic syntax of JSP, including directives, scripting elements, and standard action tags, and provide a few examples. There is also discussion of bean property conversions. For additional information on JSP 2.0 syntax, see the Sun Microsystems JavaServer Pages Specification, version 2.0.
Note: This section describes standard JSP syntax. For information about JSP XML syntax and JSP XML documents, see Chapter 8, "Understanding JSP XML Support in OC4J". |
Directives provide instruction to the Web container regarding the entire JSP page. This information is used in translating the page. The basic syntax is as follows:
<%@ directive attribute="value" attribute2="value2"... %>
The JSP specification supports the following directives:
page
include
taglib
Use this directive to specify any of a number of page-dependent attributes, such as scripting language, content type, character encoding, class to extend, packages to import, an error page to use, the JSP page output buffer size, and whether to automatically flush the buffer when it is full. For example:
<%@ page language="java" import="packages.mypackage" errorPage="boof.jsp" %>
Alternatively, to enable auto-flush and set the JSP page output buffer size to 20 KB:
<%@ page autoFlush="true" buffer="20kb" %>
This example un-buffers the page:
<%@ page buffer="none" %>
Use this directive to specify a resource that contains text or code to be inserted into the JSP page when it is translated. For example:
<%@ include file="/jsp/userinfopage.jsp" %>
Specify either a page-relative or context-relative path to the resource. See "Requesting a JSP Page" for discussion of page-relative and context-relative paths.
Notes:
|
Use this directive to specify a library of custom JSP tags that will be used in the JSP page. Vendors can extend JSP functionality with their own sets of tags. This directive includes a pointer to a tag library descriptor file and a prefix to distinguish use of tags from that library. For example:
<%@ taglib uri="/oracustomtags" prefix="oracust" %>
Later in the page, use the oracust
prefix whenever you want to use one of the tags in the library. Presume this library includes a tag dbaseAccess
:
<oracust:dbaseAccess ... > ... </oracust:dbaseAccess>
JSP tag libraries and tag library descriptor files are introduced later in this chapter, in "Custom Tag Libraries", and discussed in detail in Chapter 7, "Working with Custom Tags".
JSP scripting elements include the following categories of Java code snippets that can appear in a JSP page:
Declarations
Expressions
Scriptlets
Comments
These are statements declaring methods or member variables that will be used in the JSP page.
A JSP declaration uses standard Java syntax within the <%!...%>
declaration tags to declare a member variable or method. This will result in a corresponding declaration in the generated servlet code. For example:
<%! double f=0.0; %>
This example declares a member variable, f
. In the servlet class code generated by the JSP translator, f
will be declared at the class top level.
Note: Method variables, as opposed to member variables, are declared within JSP scriptlets as described below. See "Using Static Includes Versus Dynamic Includes" for a comparison between the two. |
These are Java expressions that are evaluated, converted into string values as appropriate, and displayed where they are encountered on the page.
A JSP expression does not end in a semicolon, and is contained within <%=...%>
tags. For example:
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
Note: A JSP expression in a request-time attribute, such as in ajsp:setProperty statement, need not be converted to a string value. |
These are portions of Java code intermixed within the markup language of the page.
A scriptlet, or code fragment, can consist of anything from a partial line to multiple lines of Java code. You can use them within the HTML code of a JSP page to set up conditional branches or a loop, for example.
A JSP scriptlet is contained within <%...%>
scriptlet tags, using normal Java syntax.
The following example assumes the use of a JavaBean instance, pageBean
:
<% if (pageBean.getNewName().equals("")) { %> I don't know you. <% } else { %> Hello <%= pageBean.getNewName() %>. <% } %>
Note how the one-line JSP scriptlets are intermixed with two lines of HTML code, one of which includes a JSP expression (which does not require a semicolon). Note that JSP syntax allows HTML code to be conditionally executed within the if
and else
branches (inside the Java brackets set out in the scriptlets).
This next example adds more Java code to the scriptlets.:
<% if (pageBean.getNewName().equals("")) { %> I don't know you. <% empmgr.unknownemployee(); } else { %> Hello <%= pageBean.getNewName() %>. <% empmgr.knownemployee(); }%>
It assumes the use of a JavaBean instance, pageBean
, and assumes that some object, empmgr
, was previously instantiated and has methods to execute appropriate functionality for a known employee or an unknown employee.
Note: Use a JSP scriptlet to declare method variables, as opposed to member variables, as in the following example:<% double f2=0.0; %> This scriptlet declares a method variable, Member variables are declared in JSP declarations as described above. For a comparative discussion, see "Using Method Variable Declarations Versus Member Variable Declarations". |
These are developer comments embedded within the JSP code, similar to comments embedded within any Java code.
Comments are contained within <%--...--%>
syntax. For example:
<%-- Execute the following branch if no user name is entered. --%>
Unlike HTML comments, JSP comments are not visible when users view the page source from their browsers.
In this document, the term JSP object refers to a Java class instance declared within or accessible to a JSP page. JSP objects can be either:
Explicit: Explicit objects are declared and created within the code of your JSP page, accessible to that page and other pages according to the scope
setting you choose.
or:
Implicit: Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets or expressions in JSP pages according to the inherent scope
setting of the particular object type.
These topics are discussed in the following sections:
Explicit objects are typically JavaBean instances that are declared and created in jsp:useBean
action statements. The jsp:useBean
statement and other action statements are described in "Standard JSP Action Tags", but here is an example:
<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />
This statement defines an instance, pageBean
, of the NameBean
class that is in the mybeans
package. The scope
parameter is discussed in "Object Scopes".
You can also create objects within Java scriptlets or declarations, just as you would create Java class instances in any Java program.
JSP technology makes available to any JSP page a set of implicit objects. These are Java objects that are created automatically by the Web container and that allow interaction with the underlying servlet environment.
The implicit objects listed immediately below are available. For information about methods available with these objects, refer to the Sun Microsystems Javadoc for the noted classes and interfaces.
This is an instance of the JSP page implementation class and is created when the page is translated. The page implementation class implements the interface javax.servlet.jsp.HttpJspPage
. Note that page
is synonymous with this
within a JSP page.
This represents an HTTP request and is an instance of a class that implements the javax.servlet.http.HttpServletRequest
interface, which extends the javax.servlet.ServletRequest
interface.
This represents an HTTP response and is an instance of a class that implements the javax.servlet.http.HttpServletResponse
interface, which extends the javax.servlet.ServletResponse
interface.
The response
and request
objects for a particular request are associated with each other.
This represents the page context of a JSP page, which is provided for storage and access of all page
scope objects of a JSP page instance. A pageContext
object is an instance of the javax.servlet.jsp.PageContext
class, which extends javax.servlet.jsp.JspContext
as of JSP 2.0.
The pageContext
object has page
scope, making it accessible only to the JSP page instance with which it is associated.
This represents an HTTP session and is an instance of a class that implements the javax.servlet.http.HttpSession
interface.
This represents the servlet context for the Web application and is an instance of a class that implements the javax.servlet.ServletContext
interface.
The application
object is accessible from any JSP page instance running as part of any instance of the application within a single JVM.
This is an object that is used to write content to the output stream of a JSP page instance. It is an instance of the javax.servlet.jsp.JspWriter
class, which extends the java.io.Writer
class.
The out
object is associated with the response
object for a particular request.
This represents the servlet configuration for a JSP page and is an instance of a class that implements the javax.servlet.ServletConfig
interface. Generally speaking, servlet containers use ServletConfig
instances to provide information to servlets during initialization. Part of this information is the appropriate ServletContext
instance.
exception
(JSP error pages only)
This implicit object applies only to JSP error pages, to which processing is forwarded when an exception is thrown from another JSP page. These error pages must have the page
directive isErrorPage
attribute set to true
.
The implicit exception
object is a java.lang.Throwable
instance that represents the uncaught exception that was thrown from another JSP page and that resulted in the current error page being invoked.
The exception
object is accessible only from the JSP error page instance to which processing was forwarded when the exception was encountered. For an example of JSP error processing and use of the exception
object, see "Processing Runtime Errors".
Any of the implicit objects discussed in the preceding section might be useful. The following example uses the request
object to retrieve and display the value of the username
parameter from the HTTP request:
<H3> Welcome <%= request.getParameter("username") %> ! <H3>
The request
object, like the other implicit objects, is available automatically; it is not explicitly instantiated.
Objects in a JSP page, whether explicit or implicit, are accessible within a particular scope. In the case of explicit objects, such as a JavaBean instance created in a jsp:useBean
action, you can explicitly set the scope with the following syntax, as in the example in "Explicit Objects":
scope="scopeValue"
There are four possible scopes:
scope="page"
(default scope): The object is accessible only from within the JSP page where it was created. A page-scope object is stored in the implicit pageContext
object. The page
scope ends when the page stops executing.
Note that when the user refreshes the page while executing a JSP page, new instances will be created of all page-scope objects.
scope="request"
: The object is accessible from any JSP page servicing the same HTTP request that is serviced by the JSP page that created the object. A request-scope object is stored in the implicit request
object. The request
scope ends at the conclusion of the HTTP request.
scope="session"
: The object is accessible from any JSP page that is sharing the same HTTP session as the JSP page that created the object. A session-scope object is stored in the implicit session
object. The session
scope ends when the HTTP session times out or is invalidated.
scope="application"
: The object is accessible from any JSP page that is used in the same Web application as the JSP page that created the object, within any single Java virtual machine. The concept is similar to that of a Java static variable. An application-scope object is stored in the implicit application
servlet context object. The application
scope ends when the application itself terminates, or when the Web container or servlet container shuts down.
You can think of these four scopes as being in the following progression, from narrowest scope to broadest scope:
page
< request
< session
< application
If you want to share an object between different pages in an application, such as when forwarding execution from one page to another, or including content from one page in another, you cannot use page
scope for the shared object; in this case, there would be a separate object instance associated with each page. The narrowest scope you can use to share an object between pages is request
. (For information about including and forwarding pages, see "Standard JSP Action Tags" below.)
Note: Therequest , session , and application scopes also apply to servlets. |
JSP action elements result in some sort of action occurring while the JSP page is being executed, such as instantiating a Java object and making it available to the page. Such actions can include the following:
Creating a JavaBean instance and accessing its properties
Forwarding execution to another HTML page, JSP page or servlet
Including an external resource in the JSP page
For standard actions, there is a set of tags defined in the JSP specification. Although directives and scripting elements described earlier in this chapter are sufficient to code a JSP page, the standard tags described here provide additional functionality and convenience.
Here is the general tag syntax for JSP standard actions:
<jsp:tagattr="value" attr2="value2" ... attrN="valueN"> ...body... </jsp:tag>
Alternatively, if there is no body:
<jsp:tag attr="value", ..., attrN="valueN" />
The most commonly-used JSP standard action tags are introduced and briefly discussed below:
jsp:usebean
jsp:setProperty
jsp:getProperty
jsp:param
jsp:include
jsp:forward
jsp:plugin
Note: The following tags are covered elsewhere in this book:
|
The jsp:useBean
tag accesses or creates an instance of a Java type, typically a JavaBean class, and associates the instance with a specified name, or ID. The instance is then available by that ID as a scripting variable of specified scope. Scripting variables are introduced in "Custom Tag Libraries". Scopes are discussed in "JSP Objects and Scopes".
The key attributes are class
, type
, id
, and scope
. (There is also a less frequently used beanName
attribute, discussed below.)
Use the id
attribute to specify the instance name. The Web container will first search for an object by the specified ID, of the specified type, in the specified scope. If it does not exist, the container will attempt to create it.
Use the class
attribute to specify a class that can be instantiated, if necessary, by the Web container. The class cannot be abstract and must have a no-argument constructor.
As an alternative to using the class
attribute, you can use the beanName
attribute. In this case, you have the option of specifying a serializable resource instead of a class name. When you use the beanName
attribute, the Web container creates the instance by using the instantiate()
method of the java.beans.Beans
class.
Use the type
attribute to specify a type that cannot be instantiated by the Web container—either an interface, an abstract class, or a class without a no-argument constructor. You would use type
in a situation where the instance will already exist, or where an instance of an instantiable class will be assigned to the type. There are three typical scenarios:
Use type
and id
to specify an instance that already exists in the target scope.
Use class
and id
to specify the name of an instance of the class—either an instance that already exists in the target scope or an instance to be newly created by the Web container.
Use class
, type
, and id
to specify a class to instantiate and a type to assign the instance to. In this case, the class must be legally assignable to the type.
Use the scope
attribute to specify the scope of the instance—either page
for the instance to be associated with the page context object, request
for it to be associated with the HTTP request object, session
for it to be associated with the HTTP session object, or application
for it to be associated with the servlet context.
The following example uses a request-scope instance reqobj
of type MyIntfc
. Because MyIntfc
is an interface and cannot be instantiated directly, reqobj
would have to already exist.
<jsp:useBean id="reqobj" type="mypkg.MyIntfc" scope="request" />
This next example uses a page-scope instance pageobj
of class PageBean
, first creating it if necessary:
<jsp:useBean id="pageobj" class="mybeans.PageBean" scope="page" />
The following example creates an instance of class SessionBean
and assigns the instance to the variable sessobj
of type MyIntfc
:
<jsp:useBean id="sessobj" class="mybeans.SessionBean" type="mypkg.MyIntfc scope="session" />
The jsp:setProperty
tag sets one or more bean properties. The bean must have been previously specified in a jsp:useBean
tag. You can directly specify a value for a specified property, or take the value for a specified property from an associated HTTP request parameter, or iterate through a series of properties and values from the HTTP request parameters.
The following example sets the user
property of the pageBean
instance according to the value set for a parameter called username
in the HTTP request:
<jsp:setProperty name="pageBean" property="user" param="username" />
If the bean property and request parameter have the same name (user
), you can simply set the property as follows:
<jsp:setProperty name="pageBean" property="user" />
The following example results in iteration over the HTTP request parameters, matching bean property names with request parameter names and setting bean property values according to the corresponding request parameter values:
<jsp:setProperty name="pageBean" property="*" />
When you use the jsp:setProperty
tag, string input can be used to specify the value of a non-string property through conversions that happen behind the scenes. See "Bean Property Conversions from String Values" for additional information.
Important: Note the following forproperty="*" :
|
The jsp:getProperty
tag reads a bean property value, converts it to a Java string, and places the string value into the implicit out
object so that it can be displayed as output. The bean must have been previously specified in a jsp:useBean
tag. For the string conversion, primitive types are converted directly and object types are converted using the toString()
method specified in the java.lang.Object
class.
The following example puts the value of the user
property of the pageBean
bean into the out
object:
<jsp:getProperty name="pageBean" property="user" />
You can use jsp:params
tags in conjunction with jsp:include
, jsp:forward
, and jsp:plugin
tags (described below).
Used with jsp:forward
and jsp:include
tags, a jsp:param
tag optionally provides name/value pairs for parameter values in the HTTP request
object. New parameters and values specified with this action are added to the request
object, with new values taking precedence over old.
The following example sets the request
object parameter username
to a value of Smith
:
<jsp:param name="username" value="Smith" />
The jsp:include
tag inserts additional static or dynamic resources into the page at request time as the page is displayed. Specify the resource with a relative URL (either page-relative or application-relative). For example:
<jsp:include page="/templates/userinfopage.jsp" flush="true" />
A "true
" setting of the flush
attribute results in the buffer being flushed to the browser when a jsp:include
action is executed. The JSP specification and the OC4J Web container support either a "true
" or "false
" setting, with "false
" being the default.
You can also have an action body with jsp:param
tags, as shown in the following example:
<jsp:include page="/templates/userinfopage.jsp" flush="true" > <jsp:param name="username" value="Smith" /> <jsp:param name="userempno" value="9876" /> </jsp:include>
Note that the following syntax would work as an alternative to the preceding example:
<jsp:include page="/templates/userinfopage.jsp?username=Smith&userempno=9876" flush="true" />
Notes:
|
The jsp:forward
tag effectively terminates execution of the current page, discards its output, and dispatches a new page—either an HTML page, a JSP page or a servlet.
The JSP page must be buffered to use a jsp:forward
tag; you cannot set buffer="none"
in a page
directive. The action will clear the buffer and not output contents to the browser.
As with jsp:include
, you can also have an action body with jsp:param
tags, as shown in the second of the following examples:
<jsp:forward page="/templates/userinfopage.jsp" />
or:
<jsp:forward page="/templates/userinfopage.jsp" > <jsp:param name="username" value="Smith" /> <jsp:param name="userempno" value="9876" /> </jsp:forward>
Notes:
|
The jsp:plugin
tag results in the execution of a specified applet or JavaBean in the client browser, preceded by a download of Java plugin software if necessary.
Specify configuration information, such as the applet to run and the code base, using jsp:plugin
attributes. You can specify attribute nspluginurl="
url
"
(for a Netscape browser) or iepluginurl="
url
"
(for an Internet Explorer browser).
Use nested jsp:param
tags between the jsp:params
start-tag and end-tag to specify parameters to the applet or JavaBean. (Note that the jsp:params
start-tag and end-tag are not included when using jsp:param
in a jsp:include
or jsp:forward
action.)
Note the use of the jsp:fallback
tag to delimit alternative text to execute if the plugin cannot run.
The following example shows the use of an applet plugin:
<jsp:plugin type=applet code="Sample.class" codebase="/html" > <jsp:params> <jsp:param name="sample" value="samples/sample01" /> </jsp:params> <jsp:fallback> <p>Unable to start the plugin.</p> </jsp:fallback> </jsp:plugin>
Many additional parameters—such as ARCHIVE
, HEIGHT
, NAME
, TITLE
, and WIDTH
—are allowed in the jsp:plugin
tag as well. Use of these parameters is according to the general HTML specification.
As noted earlier, when you use a JavaBean through a jsp:useBean
tag in a JSP page, and then use a jsp:setProperty
tag to set a bean property, string input can be used to specify the value of a non-string property through conversions that happen behind the scenes. There are two conversion scenarios, covered in the following sections:
For a bean property that does not have an associated property editor, Table 1-1 shows how conversion is accomplished when using a string value to set the property.
Table 1-1 Attribute Conversion Methods
Property Type | Conversion |
---|---|
Boolean or boolean |
According to |
Byte or byte |
According to |
Character or char |
According to |
Double or double |
According to |
Integer or int |
According to |
Float or float |
According to |
Long or long |
According to |
Short or short |
According to |
Object |
As if The |
A bean property can have an associated property editor, which is a class that implements the java.beans.PropertyEditor
interface. Such classes can provide support for GUIs used in editing properties. Generally speaking, there are standard property editors for standard Java types, and there can be user-defined property editors for user-defined types. In the OC4J JSP implementation, however, only user-defined property editors are searched for. Default property editors of the sun.beans.editors
package are not taken into account.
For information about property editors and how to associate a property editor with a type, you can refer to the Sun Microsystems JavaBeans API Specification.
You can still use a string value to set a property that has an associated property editor, as specified in the JavaBeans specification. In this situation, the setAsText(String text)
method specified in the PropertyEditor
interface is used in converting from string input to a value of the appropriate type. If the setAsText()
method throws an IllegalArgumentException
, the conversion will fail.
In addition to the standard JSP tags discussed above, the JSP specification lets vendors define their own tag libraries, and lets vendors implement a framework that allows customers to define their own tag libraries as well.
A tag library defines a collection of custom tags and can be thought of as a JSP sub-language. Developers can use tag libraries directly when manually coding a JSP page, but they might also be used automatically by Java development tools. A standard tag library must be portable between different Web container implementations.
Key concepts of standard JavaServer Pages support for JSP tag libraries include the following:
For information about these topics, see Chapter 7, "Working with Custom Tags".
For complete information about the tag libraries provided with OC4J, see the Oracle Containers for J2EE JSP Tag Libraries and Utilities Reference.
The JSP expression language (EL) greatly simplifies JSP authoring by removing the need to use embedded Java scriptlets and expressions to access request parameters or application data stored in JavaBeans.
The EL was originally introduced as part of the JavaServer Pages Standard Tag Library (JSTL) version 1.0. With the JSP 2.0 release, the EL was made an integral part of the JSP specification, dramatically improving its data-access capabilities.
The JSP 2.0-compliant OC4J container understands EL expressions implemented in the following manner:
As values for attributes in any standard action (such asjsp:useBean
) or custom tag that accept runtime expressions; and
In static template text, such as HTML or non-JSP elements. In this usage, the value of the expression within the text is evaluated and inserted into the current output. However, it must be noted that an expression will not be evaluated if the body of the tag is declared to be tagdependent
.
As an example, consider the following use of the JSTL c:if
tag to pick out steel-making companies from a company list:
<c:if test="${company.industry == 'steel'}"> ... </c:if>
This section summarizes the expression language syntax and documents how to enable EL evaluation in your OC4J JSP applications.
Note that although the EL has its own syntax, it is not a general purpose programming language; rather, it is a data access mechanism intended to simplify the lives of JSP authors.
The expression language has its own syntax, partially based on JavaScript syntax. The following list offers a brief summary of key syntax features of the JSP expression language. This is followed by a few simple examples.
Invocation
The expression language is invoked through ${expression}
syntax. The most basic semantic is that invocation of a named variable ${foo}
yields the same result as the method call PageContext.findAttribute(foo)
.
Data structure access
To access named properties within JavaBeans and within collections such as lists, maps, and arrays, the expression language supports the ".
" and "[]
" operators.
The ".
" construct allows access to properties whose names are standard Java identifiers. For example, employee.phones.cell
is equivalent to employee.getPhones().getCell()
in Java syntax.
The "[]
" construct is for more generalized access, such as for accessing arrays or lists. However, for valid Java identifiers it is equivalent to the ".
" construct. For example, the expressions employee.phoneNumbers
and employee["phoneNumbers"]
yield the same result.
Relational operators
The expression language supports the relational operators ==
(or eq
), !=
(or ne
), <
(or lt
), >
(or gt
), <=
(or le
), >=
(or ge
).
Arithmetic operators
The expression language supports the arithmetic operators +
, -
, *
, /
(or div
), %
(or mod
, for remainder or modulo).
Logical operators
The expression language supports the logical operators &&
(or and
), ||
(or or
), !
(or not
), empty
.
Basic Example
The following example shows a basic invocation of the expression language, including the relational "<=
" (less than or equal to) operator.
<c:if test="${auto.price <= customer.priceLimit}"> The <c:out value="${auto.makemodel}"/> is in your price range. </c:if>
Accessing Collections Example
The following example shows use of the ".
" and "[]
" constructs. Here, catalogue
is a Map
object containing the description of products, while preferences
is a Map
object containing a particular user's preferences.
Item: <c:out value="${catalogue[productId]}"/> Delivery preference: <c:out value="${user.preferences['delivery']}"/>
The expression language provides the following implicit objects:
pageScope
: Allows access to page-scope variables.
requestScope
: Allows access to request-scope variables.
sessionScope
: Allows access to session-scope variables.
applicationScope
: Allows access to application-scope variables.
pageContext
: Allows access to all properties of the page context of a JSP page.
param
: A Java Map
object containing request parameters typically accessed using the request.getParameter()
method. The expression ${param["foo"]}
or the equivalent ${param.foo}
both return the first string value associated with the request parameter foo
.
paramValues
: Use paramValues["foo"]
, for example, to return an array of all string values associated with request parameter foo
.
header
: As with param
, you can use this object to access the first string value associated with a request header.
headerValues
: Similarly to using paramValues
, you can use this to access all string values associated with a request header.
initParam
: Allows access to context initialization parameters.
cookie
: Allows access to cookies received in the request.
The expression language also offers the following features:
It can provide default values where failure to evaluate an expression is considered to be recoverable.
Where application data might not exactly match the type expected by a tag attribute or expression language operator, there are rules to convert the type of the resulting value to the expected type.
The expression language allows you to define static methods known as functions that can be invoked within EL expressions.
Creating or using a function is similar to creating or using a custom tag. In fact, the JSTL contains six custom tags that are actually expression language functions. See Chapter 7, "Working with Custom Tags" for details on custom tag implementation.
A function must be implemented as a public static method within a public Java class. The following example paraphrases the static method for the JSTL fn:length
function available in the Jakarta Taglibs Standard library:
public static int length(Object obj) throws JspTagException { ... }
Classes containing function methods are grouped into tag libraries, similar to custom tags. Each function's signature and the mapping to the public class containing its corresponding method are added to the library's tag library descriptor (TLD) file. For example:
<function> <description> Returns the number of items in a collection or the number of characters in a string. </description> <name>length</name> <function-class> org.apache.taglibs.standard.functions.Functions </function-class> <function-signature> int length(java.lang.Object) </function-signature> </function>
To use an EL function, a JSP must import the appropriate tag library using a taglib
directive. Here the page imports the JSTL functions
library which contains the Java class implementing the fn:length
function:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Finally, the function can be invoked within an EL expression in the JSP. Here the scoped variable employees
is a collection of Employee
objects.
There are ${fn:length(employees)} employees listed in the database.
It is possible to disable or deactivate the expression language to allow a pattern written in EL syntax to be passed through a JSP, without being evaluated as an EL expression. The EL can be disabled at either the Web application or individual JSP level. Tag files can also be instructed to ignore EL expressions.
Note that when EL is disabled, the pattern \$
will not be recognized as a quote, whereas it will be recognized as such if EL is enabled.
To disable EL for all JSPs in an application, add the following <jsp-property-group> element to the application's web.xml
Web application descriptor file.
<jsp-property-group> <url-patter>*.jsp</url-pattern> <el-ignored>true</el-ignored> </jsp-property-group>
This section provides a top-level look at how a JSP page is run, including on-demand translation (the first time a JSP page is run) and error processing.
There are two distinct execution models for JSP pages:
In most implementations and situations, the Web container translates pages on demand before triggering their execution; that is, at the time they are requested by the user.
In some scenarios, however, the developer might want to translate the pages in advance and deploy them as working servlets. Command-line tools are available to translate the pages, load them, and publish them to make them available for execution. You can have the translation occur either on the client or in the server. When the user requests the JSP page, it is executed directly, with no translation necessary.
It is typical to run JSP pages in an on-demand translation scenario. When a JSP page is requested from a Web server that incorporates the Web container, a front-end servlet is instantiated and invoked, assuming proper Web server configuration. This servlet can be thought of as the front-end of the Web container. In OC4J, it is oracle.jsp.runtimev2.JspServlet
.
JspServlet
locates the JSP page, translates and compiles it if necessary (if the translated class does not exist or has an earlier timestamp than the JSP page source), and triggers its execution.
Note that the Web server must be properly configured to map the *.jsp
file name extension (in a URL) to JspServlet
.
As an alternative to the typical on-demand scenario, developers might want to pretranslate their JSP pages before deploying them. This can offer the following advantages, for example:
It can save time for the users when they first request a JSP page, because translation at execution time is not necessary.
It is useful if you want to deploy binary files only, perhaps because the software is proprietary or you have security concerns and you do not want to expose the code.
Oracle supplies the ojspc
command-line utility for pretranslating JSP pages. This utility has options that allow you to set an appropriate base directory for the output files, depending on how you want to deploy the application. The ojspc
utility is documented in Chapter 4, "Precompiling JSP Pages with ojspc".
Presuming the typical on-demand translation scenario, a JSP page is usually executed as follows:
The user requests the JSP page through a URL ending with a.jsp
file name.
Upon noting the .jsp
file name extension in the URL, the servlet container of the Web server invokes the Web container.
The Web container locates the JSP page and translates it if this is the first time it has been requested. Translation includes producing servlet code in a .java
file and then compiling the .java
file to produce a servlet .class
file.
The servlet class generated by the JSP translator extends a class (provided by the Web container) that implements the javax.servlet.jsp.HttpJspPage
interface. The servlet class is referred to as the page implementation class. This document will refer to instances of page implementation classes as JSP page instances.
Translating a JSP page into a servlet automatically incorporates standard servlet programming overhead into the generated servlet code, such as implementing the HttpJspPage
interface and generating code for its service method.
The Web container triggers instantiation and execution of the page implementation class.
The JSP page instance will then process the HTTP request, generate an HTTP response, and pass the response back to the client.
Note: The preceding steps are loosely described for purposes of this discussion. As mentioned earlier, each vendor decides how to implement its Web container, but it will consist of a servlet or collection of servlets. For example, there might be a front-end servlet that locates the JSP page, a translation servlet that handles translation and compilation, and a wrapper servlet class that is extended by each page implementation class (because a translated page is not actually a pure servlet and cannot be run directly by the servlet container). A servlet container is required to run each of these components. |
A JSP page can be requested either directly through a URL or indirectly through another Web page or servlet.
As with a servlet or HTML page, the user can request a JSP page directly by URL. For example, suppose you have a HelloWorld
JSP page that is located under a myapp
directory, as follows, where myapp
is mapped to the myapproot
context path in the Web server:
myapp/dir/HelloWorld.jsp
You can request it with a URL such as the following:
http://host:port/myapproot/dir/HelloWorld.jsp
The first time the user requests HelloWorld.jsp
, the Web container triggers both translation and execution of the page. With subsequent requests, the Web container triggers page execution only; the translation step is no longer necessary.
Note: General servlet and JSP invocation are discussed in the Oracle Containers for J2EE Servlet Developer's Guide. |
JSP pages, like servlets, can also be executed indirectly—linked from a regular HTML page or referenced from another JSP page or from a servlet.
When invoking one JSP page from a JSP statement in another JSP page, the path can be either relative to the application root—known as context-relative or application-relative—or relative to the invoking page—known as page-relative. An application-relative path starts with "/
"; a page-relative path does not.
Be aware that, typically, neither of these paths is the same path as used in a URL or HTML link. Continuing the example in the preceding section, the path in an HTML link is the same as in the direct URL request, as follows:
<a href="/myapp/dir/HelloWorld.jsp" /a>
The application-relative path in a JSP statement is:
<jsp:include page="/dir/HelloWorld.jsp" flush="true" />
The page-relative path to invoke HelloWorld.jsp
from a JSP page in the same directory is:
<jsp:forward page="HelloWorld.jsp" />
("Standard JSP Action Tags" discusses the jsp:include
and jsp:forward
statements.)