![]() |
![]() |
ABOUT THIS DOCUMENT
This document is an updated draft of the JavaServerTM PagesTM specification. It will be available for review and comment on this site until November 12, 1998, when it will be removed for update.
Comments received will be carefully considered and revisions made to the specification as necessary. We hope to have the revised specification available shortly thereafter.
Please send your comments and questions to: jsp-feedback@eng.sun.com.
Copyright © 1998 Sun Microsystems, Inc.
901 San Antonio Road, Palo Alto, CA 94303 USA
All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.
Sun Microsystems, Inc. (SUN) hereby grants to you at no charge a nonexclusive, nontransferable, worldwide, limited license (without the right to sublicense) under SUN's intellectual property rights that are essential to use the JavaServer Pages 0.92 Specification ("Specification") for internal evaluation purposes only. Other than this limited license, you acquire no right, title, or interest in or to the Specification and you shall have no right to use the Specification for productive or commercial use.
Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-1(a).
This software and documentation is the confidential and proprietary information of Sun Microsystems, Inc. ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Sun.
SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
Sun, the Sun logo, Sun Microsystems, JavaSoft, JavaBeans, JDK, Java, HotJava, HotJava Views, Visual Java, Solaris, NEO, Joe, Netra, NFS, ONC, ONC+, OpenWindows, PC-NFS, EmbeddedJava, PersonalJava, SNM, SunNet Manager, Solaris sunburst design, Solstice, SunCore, SolarNet, SunWeb, Sun Workstation, The Network Is The Computer, ToolTalk, Ultra, Ultracomputing, Ultraserver, Where The Network Is Going, Sun WorkShop, XView, Java WorkShop, the Java Coffee Cup logo, JavaServer, and JavaServer Pages are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.
com.sun.server.http.HttpServiceResponse.callPage(String uri, HttpServletRequest
request)
is now:
javax.servlet.ServletContext.getRequestDispatcher(String uripath)
com.sun.server.http.HttpServiceRequest.setAttribute(String key, Object o)
is now:
javax.servlet.ServletRequest.setAttribute(String key, Object o)
The DISPLAY, LOOP, INCLUDEIF, and EXCLUDEIF tags now use hierarchical naming, rather than Java object naming, to describe a Bean property. A hierarchical name would be constructed as:
beanname+:propertyname
The use of colons (:) rather than periods (.) helps distinguish this naming convention from Java syntax.
The features listed below are being considered for Release 1.0 of the JavaServer Pages specification and reference implementation:
<PLUGIN name=JDK version=1.2>
The PLUGIN tag will convert all APPLET tags in the .jsp page to download the appropriate plugin. For example, applets that depend on Java Development Kit 1.2 can automatically download Java Runtime Environment 1.2 . For more information on plugins, refer to http://java.sun.com/products/plugin/
<HEADER name=" " value =" ">
The HEADER tag will set response header values so that you can specify items such as cache control.
[ item ] | Brackets surrounding an item indicate that the item is optional. |
item + | A plus sign following an item indicates that the item may occur one or more times. |
item ... | Ellipsis points following an item indicates that some elements following the item have not been shown. |
item | item | item | Vertical bars separating several items indicate that exactly one of those items must occur. |
{ item1 item2 } | Braces surrounding a set of items indicates the items appear as a group. |
KEYWORD | Uppercase characters are used to indicate reserved keywords. |
variable | This font is used to indicate variables -- placeholders for real values or characters. |
bold | Bold font is used to indicate characters that a user would type. |
filename |
This typeface is used when referring to commands, files, or directories within a sentence. |
code |
Constant width font is used for source code examples that are displayed separately from regular text. |
The JavaServer Pages technology is a simple but powerful way to dynamically generate HTML on the server side.
With JavaServer Pages technology, you can quickly and easily create Web pages with dynamically generated content. When you write JavaServer Pages, you call reusable server components (such as JavaBeans) and automatically created data objects from an HTML file. This allows you to cleanly separate the generation of dynamic content from its presentation.
Not only will you find it faster and simpler to create dynamic Web pages using JavaServer Pages, but in most cases, the responses to client requests will be faster too. Because JavaServer Pages are processed on the server, the Web page can be compiled and stored in memory on the client for faster access. And, because the client receives only plain HTML, client-machine limitations are less of a concern.
Finally, you'll find you have access to a powerful scripting solution -- JavaTM. Because JavaServer Pages technology uses the Java programming language as its default scripting language, scripting on the server side can take full advantage of the powerful set of capabilities offered by the Java programming language.
We built the JavaServer Pages technology to help you write dynamic Web pages as easily and simply as possible, with maximum power and flexibility. As we developed the JavaServer Pages technology, we held your needs firmly in mind as our primary design goals. These needs, as we envisioned them, are:
The JavaServer Pages technology is entirely platform-independent, both in its dynamic Web pages and its underlying server components. You can write the dynamic Web pages on any platform, run them on any Web server, and access them from any Web browser. You can also build and run the server components, which are JavaBeans or Java Servlets, on any server platform.
JavaServer Pages emphasizes the use of reusable, cross-platform server components written in Java. This saves you considerable development time while giving you the power and flexibility of JavaBeans and Java Servlets. And because components do much of the processing work, component development is more cleanly separated from Web design, improving the productivity of cross-functional teams.
JavaServer Pages is an integral part of the Java Platform for the Enterprise, which brings Java technology to enterprise computing. You can now develop powerful enterprise-wide or middle-tier server applications, using a JavaServer Pages Web site as a front end. When you want to update your application, you can update the components and dynamic Web pages that reside on the server, and all of your users are updated at once.
JavaServer Pages are HTML files written in a combination of industry-standard HTML, JavaServer Pages HTML tags, and -- if you like -- Java as a scripting language. A JavaServer Pages file has the extension .jsp and calls reusable components that reside on the server. It's as simple as that.
In this release, the components are JavaBeans or Java Servlets, with support for Enterprise JavaBeans anticipated in a future release.
As we designed the JavaServer Pages technology, we tried to describe who the typical users might be. The actual users of JavaServer Pages technology, or their set of skills, may turn out to be slightly different than we anticipated. That's fine. We expect to learn even more about our users -- their skills and their needs -- as the technology continues to evolve.
Here's an initial description of who we expect will be typical users:
There are many possible implementation choices for the three key elements -- reusable components, scripting language, and compiled-page object -- of the JavaServer Pages technology.
JavaServer Pages presently supports JavaBeans as reusable components and Java as its scripting language. We anticipate third-party support soon for other popular scripting languages. JavaServer Pages are compiled into objects, frequently Java Servlets, although we anticipate third-party implementations using other object technologies.
To anchor this discussion of the JavaServer Pages technology in the concrete, however, it was necessary to select an implementation. For simplicity, we decided upon the following default implementations:
In this specification, we use JavaBeans, Java, and Java Servlets as an example of JavaServer Pages elements, not as a recommendation for your specific implementation.
You can apply the JavaServer Pages technology in two ways:
The user working in a client Web browser can make a request directly of a JavaServer Pages file.
After receiving the client request, the JavaServer Pages file requests information from a JavaBean. The JavaBean can in turn request information from an Enterprise JavaBean or a database. Once the JavaBean generates content (perhaps working with an Enterprise JavaBean, a database, or both), the JavaServer Pages file can query and display the Bean's content.
Another way to to use JavaServer Pages is to send a request to a Java Servlet.
In this example, the client makes a request that is handled by a Java Servlet. The servlet generates the dynamic content -- in this example, the servlet uses JDBC to communicate with a database to obtain the content. The servlet then wraps the dynamic content into a bean. The JavaServer Pages file accesses the dynamic content from the bean and displays the content in the client web browser.
In either Model 1 or Model 2, the JavaServer Pages file is identified to the server by a .jsp extension -- this tells the server that special handling is required. The first time a request is made for such a file -- either directly from a client browser or from a servlet -- the .jsp file is compiled into an object. (For that reason, there can be a slight delay on the first request for a .jsp page.) The output from the object is standard HTML which the browser interprets and displays as usual.
After compilation, the compiled-page object is stored in memory on the server. On subsequent requests for that page, the server checks to see if the .jsp file has changed. If it has not changed, the server uses the compiled-page object stored in memory to generate the response to the client. (Because the object is stored in memory, the response is very fast.) If the .jsp file has changed, the server automatically recompiles the page file and replaces the object in memory.
Some examples of components that can be called from a JavaServer Pages file are JDBCTM or JavaTM BlendTM components. The results are obtained from the components by the JavaServer Pages, using standard Bean property readers, and are displayed using HTML.
This separation of generation from presentation is reflected in the design of the JavaServer Pages syntax. The syntax is component-centric, with the ability to add small sections of code if required. (This is in contrast to some other dynamic-content technologies which focus on scripting languages as the main mechanism, with some ability to include components.)
The syntax of JavaServer Pages can be roughly divided as follows:
For a description of the conventions used in describing syntax and code in this document, see the Conventions section of the Introduction.
Their similarity to HTML tags in both look and feel makes these component-centric tags easy to distinguish from the infrequently used scripting-centric tags. Also making them easy to distinguish, one from the other, is their use of a hierarchial naming convention when accessing dynamic content from components. (Scripting-centric tags use the standard variable naming conventions of the chosen scripting language.)
A hierarchical name is constructed as follows:
beanname:propertyname+
An example would be:
dateBean:monthwhere the dateBean is a Bean containing a property called month.
The use of colons (:) rather than periods (.) also helps distinguish this naming convention from Java syntax. (Note that a property may, itself, be a Bean containing further properties. Such a situation is discussed in further detail in the Nested Properties section.)
Note: The one place hierarchical naming is not used in the component-centric tags is in the USEBEAN tag -- NAME and TYPE both use the Java variable naming convention.
Syntax that allows access to a Bean and its properties within the .jsp file. These are defined by:
Syntax Notes:
Dependancies, order, and the treatment of multiple instances of a tag are indicated in the tag descriptions which follow.
The syntax to refer to a Bean inside a .jsp file is defined by the USEBEAN tag. Any non-implicit Bean must first be declared this way before it and its properties can be accessed later in the .jsp file. The occurrence of a USEBEAN tag in the .jsp file triggers the start of the lifecycle for that Bean.
The general form of a JavaServer Pages USEBEAN tag is:
<USEBEAN NAME="nameofbeaninstance"
TYPE="nameofbeanclass"
LIFESPAN="page|session|application" >
and
</USEBEAN>
All the attributes of the USEBEAN tag are required but they need not appear in any particular order. The attributes are defined this way:
An opening <USEBEAN...> and closing </USEBEAN> tag pair may enclose nothing. Optionally, the pair may enclose one of the following:
No other HTML or JSP tags are permitted between the opening and closing USEBEAN tags.
The USEBEAN tags for any given Bean, with the exception an Implicit Bean, must appear before any property of the Bean can be accessed by any other JavaServer Pages tags.
An example of the USEBEAN tag is:
<USEBEAN NAME="clock" TYPE="calendar.JspCalendar" LIFESPAN="page">
</USEBEAN>
The possible errors are:
Lifecycle of a JavaServer Pages Bean
The lifecycle of a (non-implicit) JavaServer Pages Bean is as follows:
Note that "does exist" implies the Bean is present at compile time and locateable
through standard means, such as the classpath environment variable.
processRequest
method exists. If such a method does exist,
it is called. The processRequest
method typically performs the dynamic
content generation which may then be accessed from the JavaServer Pages
file. The signature of this method is:
public void processRequest(HttpServletRequest req);
Using the Bean
Typically, the purpose of a Bean is to compute some set of results. The results are then stored as properties of the Bean.For a JavaServer Pages file to be able to access a Bean's properties, the Bean must first be registered by name for the appropriate lifespan (previous step). Then the JavaServer Pages file can display the Bean's properties using the property-display tags. The property-display tags are
- <DISPLAY...> for single-valued properties
- <LOOP ...><DISPLAY... ></LOOP > combination for multi-valued or nested properties (indexed properties)
Deleting the Bean
Once the lifespan (scope) becomes invalid, all JavaServer Pages objects with that lifespan become invalid as well. The invalid objects, termed garbage, are then subject to Java's normal garbage-collection mechanism which automatically detects when an object is no longer needed and deletes it.Currently, three lifespans are possible in the JavaServer Pages Technology:
- Page lifespan:
- This is the lifespan that is valid for the duration of one client-request. When the request ends (typically with a response), the JavaBeans objects in the page lifespan are destroyed.
- Session lifespan:
- This is the lifespan that is valid for the duration of the HTTP session. When the server ends a session, the JavaBeans objects in the session lifespan are destroyed.
- Application lifespan:
- This is the lifespan that is valid for the duration of the application. When the server unloads the application, the JavaBeans objects in the application lifespan are destroyed.
Resolving Bean Names
You should always provide uniques names for your Beans.
In some cases, Bean names must be unique (otherwise a
JavaServer Pages error is generated). In other cases, Bean names
are recommended to be unique (because
the results of the JavaServer Pages Bean name resolution mechanism
might be different than
you intended). Avoid errors and unintentional behavior
by choosing a unique name for each Bean.
The following chart indicates how Bean names are handled in JavaServer Pages:
Within a page | Across pages | |
---|---|---|
Across lifespans | Bean name must be unique. Otherwise, an error is generated. |
Bean name should be unique. Otherwise, the Bean accessed from a given page will be the Bean explicitly registered on the current page. References to Beans with differing lifespans from previous pages are lost. |
Within the same lifespan | Bean name must be unique. Otherwise, an error is generated. |
Bean name must be unique. Otherwise, an error is generated. |
The SETONCREATE tag defines a value for a property which will automatically be set once for each Bean (through JavaBeans introspection) when the Bean is created. The property value can be a string, integer, or float.
When the SETFROMREQUEST tag is present, all request parameters (query or form based) are examined. The appropriate property setter methods from the Bean's BeanInfo are called for each property depending on the attribute specified.
The syntax for the SETONCREATE tag is as follows:
<SETONCREATE BEANPROPERTY="propertyname" VALUE="propertyvalue" >
The attributes for the SETONCREATE tags are:
A SETONCREATE tag can appear only between the opening <USEBEAN ...> and closing </USEBEAN> tags. More than one SETONCREATE tag may appear in that position. SETONCREATE tags are not valid anywhere else in the file.
An example of a USEBEAN tag with enclosed SETONCREATE tag is:
<USEBEAN NAME="foobar" TYPE="FooClass" LIFESPAN="page">
<SETONCREATE BEANPROPERTY="foobarProperty" VALUE="1">
</USEBEAN>
Similarly, the syntax for the SETFROMREQUEST tag is as follows:
<SETFROMREQUEST BEANPROPERTY="*|propertyname" PARAMNAME="value">
Note that this general syntax results in the following 3 cases:
- <SETFROMREQUEST BEANPROPERTY="
*
" >When the wildcard character
*
is used, BEANPROPERTY matches any property name. In this case, all request parameters are copied into the Bean, matching parameter names in the request to property names in the Bean -- the PARAMNAME attribute, if present, is ignored.- <SETFROMREQUEST BEANPROPERTY="propertyname" >
When a specific BEANPROPERTY value is provided but a PARAMNAME value is not, the PARAMNAME value is assumed to be equivalent to the BEANPROPERTY value.
For example
<SETFROMREQUEST BEANPROPERTY="foo" >would be read as if it said:<SETFROMREQUEST BEANPROPERTY="foo" PARAMNAME="foo">- <SETFROMREQUEST BEANPROPERTY="propertyname" PARAMNAME="name">
This is the fully qualified case. In this form, the tag says to copy into the Bean property named propertyname, the value of the request parameter named name.
The attributes for the SETFROMREQUEST tags are:
Like SETONCREATE, a SETFROMREQUEST tag can appear only between the opening <USEBEAN ...> and closing </USEBEAN> tags. More than one SETFROMREQUEST tag may appear in that position. SETFROMREQUEST tags are not valid anywhere else in the file.
So, what happens in the following situation:
<USEBEAN NAME="foobar" TYPE="FooClass" LIFESPAN="page">
<SETFROMREQUEST BEANPROPERTY="foobarProperty" PARAMNAME="employmentStatus">
<SETONCREATE BEANPROPERTY="foobarProperty" VALUE="Salaried">
</USEBEAN>
The tagging indicates two possible values for the foobar Bean's foobarProperty -- "Salaried" and the value of the employmentStatus parameter. It obviously cannot hold both values simultaenously so how is the conflict resolved?
As noted earlier, SETFROMREQUEST and SETONCREATE tags can only appear between the opening <USEBEAN ...> and closing </USEBEAN> tags. Within a given USEBEAN pair of tags, all SETONCREATE tags are processed first (in their order of appearance) and then all SETFROMREQUEST tags are processed (in their order of appearance). Therefore, in the case above, the value of the BEANPROPERTY foobarProperty would first be assigned "Salaried" and then be assigned the value associated with the request parameter employmentStatus.
Once a Bean is declared, it can be accessed later in the file. For example, using the expression syntax discussed earlier, you can access the Bean declared in the example above inside that same JavaServer Pages file as follows:
<p>The name of the row is <%= foobar.getRowName() %>. </p>
The possible errors are:
Reviewer Note: For discussion
The JavaServer Pages syntax that allows for the display of Bean properties is new and tentative. For single-valued properties, the DISPLAY tag provides webpage designers a quick and easy way to access a property value for display within HTML presentation code. For multi-valued (indexed) properties, the addition of the LOOP tag enables the webpage designer, for each element in the array, to access the property value for display. We are interested in your thoughts on the proposed syntax -- how well you think it works or how you believe it might be be improved. Your comments are welcome. |
As mentioned earlier, the JavaServer Pages model enables the separation of content presentation from content generation. That separation is made possible through the use of reusable components (for content generation) and a small set of HTML-like tags designed to access the content of those components (for presentation purposes). This section of the JavaServer Pages specification discusses those tags.
There are two kinds of Bean properties you might wish to display:
And there exists a variation on each of the above:
The simplest Bean property to display is one in which there is a one-to-one mapping of property to property value -- this is called a single-valued Bean property. An example would be a Bean property called favouriteColor that can hold only a single choice. Such a single-valued property value can be accessed for presentation in a .jsp file through the use of the DISPLAY tag.
To use the Bean-property display tags for any Bean other than an implicit Bean, you must provide a USEBEAN tag for that Bean earlier in the JavaServer Pages file. Requiring the earlier USEBEAN tag helps ensure that the Bean exists (is instantiated) and is accessible (registered for the lifespan of the specified file).
The general syntax for the DISPLAY tag is:
<DISPLAY PROPERTY="[beanname:+]property" PLACEHOLDER="substitutevalue">
The attributes for the DISPLAY tag are:
The value of the PROPERTY attribute is case-sensitive, while the value of the PLACEHOLDER attribute is not. As always, the tag and attribute names themselves are case-insensitive.
For properties that return Java native types, DISPLAY will show the property value
automatically converted to String. For all other Objects, the toString
method
will be called.
An example of the DISPLAY tag would be:
<DISPLAY PROPERTY="preference:someProperty"
PLACEHOLDER="<H1>Not Available</H1>">
Another example would be:
<img src="<DISPLAY PROPERTY=productA:imageURL>">
The following sample file shows the required early USEBEAN tag and then the tags for displaying single-valued properties of the Bean:
<html>
<body>
<USEBEAN NAME=bar TYPE=jsp.beans.LunchSpecial LIFESPAN=page >
<SETONCREATE BEANPROPERTY="soup" VALUE="clam chowder">
<SETONCREATE BEANPROPERTY="dessert" VALUE="lemon meringue pie">
</USEBEAN>
<h1>Welcome to Jake's Emporium!</h1>
<h2>Today's Lunch Special is:</h2>
<p>
<ul>
<li>Hot and tasty <DISPLAY PROPERTY="bar:soup" PLACEHOLDER="tomato"> soup</li>
<li>Hearty <DISPLAY PROPERTY="bar:sandwich" PLACEHOLDER="cheese" > sandwich</li>
<li>Homemade <DISPLAY PROPERTY="bar:dessert" PLACEHOLDER="apple" ></li>
</ul>
</p>
</body>
</html>
The output from that page would look like:
Welcome to Jake's Emporium!
Today's Lunch Special is:
- Hot and tasty clam chowder soup
- Hearty cheese sandwich
- Homemade lemon meringue pie
Note that Bean-property display tags essentially have the effect of printing the value to the page -- they have no intrinsic value. You can manipulate their presentation, but not the values themselves. For instance, if the property values had been "99", "20", and "16" respectively, you would not have been able to add or otherwise arithmetically alter them using the display tags.
The possible errors are:
To Display a Multi-valued Property
A Bean property that contains more than one value, a one-to-many relationship, is called a multi-valued or indexed property. An example would be a Bean property called favouriteFoods that contains an array of chosen items.
As mentioned in the previous section, to use the Bean-property display tags for any Bean other than an implicit Bean, you must provide a USEBEAN tag for that Bean earlier in the JavaServer Pages file.
The syntax for the simplest combination of LOOP and DISPLAY tags is shown below. Note that a LOOP tag can only contain either a DISPLAY tag or another LOOP tag (which encloses a DISPLAY tag).
<LOOP PROPERTY="beanname:indexedproperty" PROPERTYELEMENT="x" >
<DISPLAY PROPERTY= "x" PLACEHOLDER="substitutevalue">
</LOOP>
The attributes for the LOOP tag are:
Notes for Component Programmers
From a programmer's point of view, multiple-valued (indexed) properties can take one of the following forms:
In this case, the size of the array is known.
The LOOP tag simply causes the repeat of the DISPLAY tag and associated HTML
for each element in the array.
This method is called n times, starting with index 0 and incrementing the index by 1 each time, until the index n-1 is reached. The value of n can be determined in any of the following ways:
Multi-valued Bean Property
Enclose the syntax for displaying a multi-valued Bean property inside a pair of LOOP tags:
<LOOP PROPERTY="beanname:indexedproperty" PROPERTYELEMENT="x" >
<DISPLAY PROPERTY= "x" PLACEHOLDER="nullvalue">
</LOOP>
Here's an example of displaying a multi-valued Bean using the LOOP and DISPLAY tags:
<html>
<body>
<USEBEAN NAME=test TYPE=jsp.beans.GroceryList LIFESPAN=page >
</USEBEAN>
<p>Remember to pick up on the way home:
<ul>
<li><b>Dairy</b>
<ul>
<LOOP PROPERTY=test:dairy PROPERTYELEMENT=x>
<li><DISPLAY PROPERTY=x:item > </li>
</LOOP>
</ul></li>
</ul>
<ul>
<li><b>Vegetables</b>
<ul>
<LOOP PROPERTY=test:vegetables PROPERTYELEMENT=y>
<li><DISPLAY PROPERTY=y:item > </li>
</LOOP>
</ul></li>
</ul>
<ul>
<li><b>Baking</b>
<ul>
<LOOP PROPERTY=test:baking PROPERTYELEMENT=z>
<li><DISPLAY PROPERTY= z:item > </li>
</LOOP>
</ul></li>
</ul>
</table>
</p>
</body>
</html>
For which the output would look something like:
Remember to pick up on the way home:
- Dairy
- milk
- eggs
- cheese
- cream
- Vegetables
- artichokes
- carrots
- Baking
- sugar
- vanilla
- yeast
The possible errors are:
Nested Bean Properties
Sometimes the multi-valued property you're interested in is itself a property of a
another property -- that is, it is a nested property. An example of this situation
might be:
A Market Bean with a property called Company that held multiple values; and for each value of Company there was a property called Products that held multiple values, for each value of Product there were two single-valued properties Name Price
Then to get a listing of names and prices for Product j from Company i, you would write something like:
<LOOP PROPERTY="market:company" PROPERTYELEMENT="i" >
<LOOP PROPERTY="i:products" PROPERTYELEMENT="j" >
<DISPLAY PROPERTY= "j:name" > <DISPLAY PROPERTY= "j:price" >
</LOOP>
</LOOP>
While the following would result in an error because the Company property is multi-valued, but no particular value has been selected:
<LOOP PROPERTY="market:company:products" PROPERTYELEMENT="i">
<DISPLAY PROPERTY=" i:name" ><DISPLAY PROPERTY="i:price" >
</LOOP>
The possible errors are:
Two Beans are provided for use in JavaServer Pages without explicit user intervention -- that is, without the user having to first identify them with the USEBEAN tag prior to use. These implicit Beans are: exception and request.
Additional details on the nature and use of these implicit Beans are provided below.
exception Bean
Errors may occur either at compile time, when the .jsp file is first compiled to an object
(see the Access Model section for information on this) or at runtime when the compiled
object is actually used. An example of a compile time error is a .jsp file with a
syntax error, which may be as simple as a misspelled or missing required
attribute. An example of a runtime time error is a .jsp file that references an
invalid class file for the creation of a new Bean.
The exception Bean is of type java.lang.Throwable. Although all of the methods of that class are available, JavaServer Pages authors will typically use the getMessage method, and component or application developers the printStack Trace method. The API for java.lang.Throwable is provided in the appendix of this document.
request Bean
Information from the incoming client request is automatically made available through the
request Bean. The request Bean provides access to CGI-like environment variables, request
parameters, and request headers.
The request Bean properties can be accessed in the DISPLAY, LOOP-DISPLAY, INCLUDEIF, or EXCLUDEIF constructs.
Briefly, the listing of available request Bean properties is:
contentLength
contentType
protocol
scheme
serverName
serverPort
remoteAddr
remoteHost
realPath
characterEncoding
method
requestURI
servletPath
pathInfo
pathTranslated
queryString
remoteUser
In addition to the above properties, the request Bean has two nested Beans. The properties of these nested Beans, and the value assigned to their properties, are determined dynamically. The request Bean's nested Beans are:
The nested headers Bean contains information from the HTTP request header. For each header defined by the HTTP protocol, there is a property of the same name. For example, here's how you might display the HTTP header "user-agent":
<DISPLAY PROPERTY="request:headers:user-agent" >
The nested params Bean contains user-provided request parameters (such as form or query based parameters). As an example, consider a form with name and address fields. On submission by the user, the action may be posted as:
http://www.mycompany.com/subscribe.jsp?name="x"&address="y"
If you then wanted to show those request parameters in your response to the user (client), you could do so with the following syntax:
<DISPLAY PROPERTY="request:params:name" >
JavaServer Pages syntax provides the ability to conditionally include or exclude a block of code, which may be composed of any valid JSP syntax, based on the evaluation of a bean-property value. The two conditional tags are:
INCLUDEIF and EXCLUDEIF tags can only be used with Bean properties that return either a String type or a Java native type. If a Bean property used in this tag returns a Java native type, that returned value is automatically converted to a String type.
The syntax for the INCLUDEIF tags is as follows:
<INCLUDEIF PROPERTY="bean[:property]+" VALUE="valuetomatch" CASE="sensitive|insensitive MATCH="null|exact|contains|startswith|endswith">
and
</INCLUDEIF>
Similarly, the syntax for the EXCLUDEIF tags is as follows:
<EXCLUDEIF PROPERTY="bean:[property]+" VALUE="valuetomatch" CASE="sensitive|insensitive MATCH="contains|startswith|endswith|null|exact">
and
</EXCLUDEIF>
The attributes for both tags are defined as follows:
An example of using the INCLUDEIF tag is:
<p> CONGRATULATIONS!! You are a winner in the "Guess My Favourite Colors" Game.
<INCLUDEIF PROPERTY="cb:hintTaken" VALUE="true" CASE="insensitive" MATCH="exact">
<p> (Although I know you cheated and peeked into the hints!)
</INCLUDEIF>
The possible errors are:
When directives are present in a JavaServer Pages file, they should appear at the top. The general syntax of the JavaServer Pages directive is:
<%@ variable="value" %>
Note that a space is required between the <%@ and the variable parts of the tag.
The possible variables are:
The lifespan (scope) of this tag is for the entire file and all included files. If used more than once in a single file, only the first tag in the file is significant. If omitted entirely in the top-level (enclosing) file, the default scripting language used is java (for the Java programming language).
If an included file contains this directive and it does not match the value (default or explicit) of the top-level enclosing file, an error will be given.
An example of the language directive is shown below:
<%@ language="java" %>
The lifespan (scope) of this tag is for the entire file and all included files. If used more than once, only the first tag is significant. If omitted, errors will be returned directly to the requesting client. If the file is not fully qualified (location and filename), the error page is assumed to be located in the same directory as the originating .jsp file.
For information on the use of the exception Bean with files specified by the errorpage directive, see the Errors section of this document.
An example of the errorpage directive is:
<%@ errorpage="contactwebmaster.html" %>
The lifespan (scope) of this tag is for the entire file. This tag can be used multiple times within a file, and in included files, to import different Java packages. If omitted, no packages are imported.
An example of the import directive is:
<%@ import="java.io.*,java.util.Hashtable" %>
The possible errors are:
All declarations that define page-wide variables for the compiled page file, and all methods that are class-wide definitions, can be defined in a JavaServer Pages file within the SCRIPT tag pair.
The general form of a JavaServer Pages declaration is:
<SCRIPT RUNAT="location">
and
</SCRIPT>
The attributes are defined as follows:
Note: If RUNAT is not specified, it defaults to "client" and the statements enclosed by the SCRIPT tags will be passed unprocessed in the page sent to the client.
An example of the SCRIPT tags appears below:
(Because the SCRIPT tag in this example encloses Java code, the RUNAT=server tag is required to indicate that the enclosed code is for server-side processing. )
<SCRIPT RUNAT=server>
int i = 0;
String foo = "Hello";
private void foo() {
// some code
}
</SCRIPT>
The possible errors are:
Scriptlets can enclose any code that is valid for the language specified in the language directive.
The general form of a JavaServer Pages scriptlet is:
<% ... %>
Note that a space is required between the <% and the remainder of the tag.
The script specified can rely upon a set of predefined variables: servletrequest, servletresponse, in, and out. For more information on predefined variables, see the Implicit Variables in the Syntax section of this specification.
An example of the scriptlet tags appears below:
<% out.println("Hello"); %>
Another example:
<%
foo = request.getParameter("Name");
out.println(foo);
%>
The possible errors are:
You can think of an expression as a description of, or placeholder for, an item you
want evaluated. The expression is evaluated and then it is replaced by its value. The
value is always converted to a string. Conversions to string representation
are provided automatically for all primitive types (such as int
and
float
).
The general form of a JavaServer Pages expression is:
<%= variable %>
Note that a space is required between the <% and the variable parts of the tag.
Valid contents within the tag are any expression that is valid in the scripting language designated by the language directive given in the file.
For example, if myexpression
was a valid expression
for the designated scripting language and its value was 1020 Somestreet, USA, you could write:
<p>I live at: <%= myaddress %> </p>
This would result in the substitution of the value of "myaddress" in place of the <%= myaddress %> tag, just as if you had written in your HTML file:
<p>I live at: 1020 Somestreet, USA </p>
As another example, if Java was the scripting language, and Bean b was a Java variable, you could write:
<%= b.getFoo %>
The possible errors are:
Note: These predefined variables cannot be used within <SCRIPT> </SCRIPT> declaration tags.
Server-side includes (SSI) give you the ability to embed instructions to the server inside an HTML document. A common use of SSI is embedding files that contain boilerplate text (such as copyright notices) or accessing predefined environment variables (such as time of day).
Using server-side includes, you can embed an .html file or even another .jsp file inside the current JavaServer pages file. (If you decide to embed another .jsp file, read the Directives section of the JavaServer Pages Syntax for information on how embedded directives are handled when in conflict with those of the parent page.)
JavaServer Pages supports SSI directives written in the National Center for Supercomputing Applications (NCSA) format:
<--# command tag1="value1" -->
Notes:
Most commands take only one tag at a time.
No spaces are allowed between the <-- and the #.
Here is a description of the NCSA SSI include
command:
virtual
file
virtual
, the file
tag simply specifies the name
of the file. When used alone, it specifies the path and name of the file relative to the
current directory (the string "../" cannot be used).For example:
<!--#include virtual="/pathfromdocdir/" file="copyright.html" -->
<!--#include file="data/table.html" -->
And here is an example of its use in a file:
<html>
<head>
</head>
<body>
<h1>A Page for the Company Website</h1>
<p>Please buy my product. </p>
<!--# include file="productspecification.jsp" -->
<!--# include file="disclaimer.html" -->
<!--# include file="copyright.html" -->
</body>
</html>
JavaServer Pages supports the full set of NCSA Server Side Include commands which can be found on the NCSA's HTTPd website or in most introductory books on Web programming.
Not surprisingly, there can be errors in a JavaServer Pages file. Depending on the nature of the error, it may be found at the time the page file is compiled or not until the compiled page is invoked. Errors in a page file's format, or in the scripting code it contains, are examples of compile-time errors.
Using the errorpage directive
With the ERRORPAGE directive, you can identify a .jsp or an .html page to be returned to
the client's browser when an error occurs. You also have access to an implicit Bean named
exception (of type java.lang.throwable), which contains information about the most recent
error. The exception Bean information can be helpful if you are debugging your own pages
or if you wish to include some of the error information into the returned page as an aide
to users.
The exception Bean can only be accessed from a file specified by the errorpage directive. Within the specified error page, the exception Bean's information can be accessed just like any other Bean's properties. That is, to access the exception Bean's information, use the syntax for expressions (as in <%= exception.getMessage %>) or the syntax for displaying Bean properties (as in <DISPLAY PROPERTY="exception:message" >).
The only difference between using the implicit exception Bean and other Beans you might access, is that you don't need to use a USEBEAN tag before accessing its properties -- that's all handled automatically.
Here's some of the ways you can call that information from your JavaServer Pages error page:
Not using the errorpage directive
If the errorpage
directive is not used, an error of type 500 (internal error)
is reported back to the client trying to access the page. The specific errors reported
back to the client are:
Bean developers need a way to accurately describe the properties of a Bean to the Web designer who is designing the .jsp page. Web designers also need an easy way to understand the properties they can use in a .jsp file and what those properties do, even if the Bean is not used in a visual builder tool.
In a future release of JavaServer Pages, we anticipate providing a tool that generates a property sheet for a Bean in an .html file, similar to JavaDoc. However, for this preliminary specification and reference implementation, Bean developers and Web designers need an interim method.
For now, we propose that the Bean developer might provide written information about properties in a format something like this one:
Type BeanName:property1 descriptive comment Single Type[] BeanName:property2[] descriptive comment Multi Type BeanName:property3:property4 descriptive comment Single
This property sheet describes all the Bean's properties, including single-valued properties, indexed properties (also called multivalued properties), and nested properties. The notation Single means that the property has a single value that you access through the <DISPLAY> tag. The notation Multi means that the property is an indexed (multivalued) property, whose values you access through the <LOOP> tag.
Let's expand this format into a concrete example. Suppose you had a Bean named Ticker that provided a stock market ticker. The Bean tracks companies on different stock markets and displays a list of data about each stock. For example, the Ticker bean might track three companies on the New York Stock Exchange and three companies on the NASDAQ and display the stock's latest price during trading (updated at intervals), its high and low prices for the day, and its previous closing price.
The Bean developer has already given Ticker a few properties:
In JavaServer Pages notation, we would list the properties this way:
As Ticker runs, the properties are dynamically replaced with concrete data, for example:
After finishing Ticker, the Bean developer might give the Web designer property information written in the following format, which we call a property sheet:
String Ticker:market The name of the market Single String[] Ticker:market:companyName[] An array of company names on that market Multi Double Ticker:market:companyName1:latest The latest price for Company 1 Single Double Ticker:market:companyName1:high The high price for Company 1 Single Double Ticker:market:companyName1:low The low price for Company 1 Single Double Ticker:market:companyName1:previous The previous closing price for Company 1 Single Double Ticker:market:companyName2:latest The latest price for Company 2 Single Double Ticker:market:companyName2:high The high price for Company 2 Single . . .
By using the property sheet, the Web designer can easily incorporate Ticker's output into the page design described in the .jsp file.
Applications can be thought of as a set of cooperating resources (servlets, applets, image file, or webpages) that share information between them to achieve some end functionality. The information is stored in a shared data-object, which is accessible by any of the resources that belong to the application. An application resource can put information into the shared data-object or retrieve information from that data object.
The builder of the application-support mechanism (sometimes called the engine) decides the implementation details of exactly how resources will become associated together as an application. The administrator of the server manages the application-support mechanism according to the engine builder's directions.
All a dynamic-content programmer or webpage designer needs to know are the resources that make up a given application -- not how the underlying association is performed. For example, an .html page with instructions, a .jsp page containing a form, a database-access Bean, and a rate-calculation Bean may all be part of the same real-estate transaction application. Knowing that, the designer and developer both know that information can be shared between these resources without the need for one resource to directly access and pass on information to each of the others.
For example, a Web designer might want to add a counter to a .jsp page to show how many times the page has been accessed. The .jsp page might call a Bean named cbean, display the value of the Bean's counter property, and set the values of the Bean's imageDirectory and imageName properties:
<html> <USEBEAN NAME="cbean" TYPE = "counter.Counter" LIFESPAN = "application"> <SETONCREATE BEANPROPERTY="imageDirectory" VALUE="/images/counter/"> <SETONCREATE BEANPROPERTY="imageName" VALUE="ocr.gif"> </USEBEAN> This page has been accessed <DISPLAY PROPERTY="cbean:counter"> times. </html>
In this example, the .jsp page and the Bean share information, but neither the designer nor the developer need to know the underlying mechanics of how the resources access each other.
The Hypertext Transport Protocol (HTTP), on which the Web is built, is stateless. That means that each HTTP transaction opens with the client's request to the server for a resource (typically a webpage) and closes with the server's response. The next request initiated by that client carries no information, or state, from the last request. In many situations, that lack of ability to store information from one request to another quickly becomes a burden for both the client and the service provider.
The following scenarios are typical situations where the ability to store information from one request to another is desirable:
Without session tracking, you would have no way to store the information about your selected items (no "shopping cart"). You'd have to select and buy each item in a series of individual transactions.
Without session tracking, you would have to provide your identification and password at not just the first entry page to a restricted area of a website (perhaps restricted by membership level), but for every page you accessed in that area of the website.
Session tracking is a high-level replacement for the traditional cookie setting and management with which you may already be familiar. The JSP session tracking feature tracks client-serverinteractions via objects rather than strings.
With JavaServer Pages, webpage authors don't need to worry about managing cookies -- the server takes care of the saving state between the client and server. Because JavaServer Pages takes care of thread contention, you can be assured there is only one thread working on your session object -- similarly for applications. Request objects are strictly thread-safe.
(The characteristics of session tracking -- how many objects can be in a given session, how long a session lasts, and a number of other session characteristics -- are configurable by the server administrator.)
In the sample code below, the .jsp file contains a Bean. When the .jsp file is requested by a client, the Bean component and an associated session object are created (if not currently in existence) or located (if they already exist). Once identified, information can be stored into or retrieved from the session object. In this example, if information about selected items had been stored into the session object on previous pages (requests), that information would be retrieved and displayed on this page.
<html>
<body>
<USEBEAN NAME="cart" TYPE=sessions.DummyCart LIFESPAN=session>
<SETFROMREQUEST BEANPROPERTY="*">
</USEBEAN>
You have the following items in your cart: <ol>
<LOOP PROPERTY=cart:items PROPERTYELEMENT=x>
<li> <DISPLAY PROPERTY=x> </li>
</LOOP>
</ol>
</body>
</html>
One of the most powerful features of JavaServer Pages technology is the ability to access reusable components, such as JavaBeans, from within a JavaServer Pages file. The underlying mechanisms are transparent to .jsp page authors, familiar to Bean programmers, and easily understood by JSP-support providers.
By default, all of a Bean's properties are accessible by a client -- not just those the client is meant to access. This is a well-known situation with Beans which is not specific to JavaServer Pages technology.
Take the following example. A client inquiry form has name, address, and email fields.
When it is submitted, this particular form calls a JavaServer Pages file. The JavaServer
Pages has a USEBEAN tag declaring foobean
. Foobean has not only set and get
methods for name, address, and email, but also set and get methods for account
and balance
. The client can simply add code to the form which calls the getAccount
method on that Bean.
With JavaServer Pages syntax, however, you can easily limit which Bean properties can be set from an incoming client request by explicitly naming those properties in the SETFROMREQUEST tag.
As in the more general case of Bean development, a JavaServer Pages developer can take can steps in addition to, or instead of, the JSP-specific SETFROMREQUEST approach. These include, but are not limited to:
Note: The JavaServer Pages code that does the introspection would be required to respect the "hidden" attribute on such properties by refusing to set them from the SETONCREATE values or request parameters.
Two interfaces support the JavaServer Pages technology. These APIs provide a way to separate content generation from the presentation of that content. It is intended that these methods become part of the Servlet API. For now, they are candidate APIs, which will be supported by our implementation of the Servlet API.
The idea is for a servlet to be able to generate content and then store this content (typically in the form of a Bean) in the request context. The servlet that generated the context then generates a response by passing the request context to a JavaServer Pages file that contains mostly presentation logic. To access the dynamic content, you use the USEBEAN tag described above.
An example is a website developer who sets up a timed program on a webserver to automatically call a link checker servlet. The results-set from the servlet could be stored as a Bean. Then the servlet would call a JavaServer Pages file, which would present a report format of the information stored in the Bean.
The two JavaServer Pages APIs are defined below:
By now you may be excited about JavaServer Pages and want to start using .jsp files, property sheets, and Bean components right away. We have anticipated your needs and provided a set of code samples with the JavaServer Pages 0.92 Reference Implementation.
The samples are listed below. In some cases, the samples are named informally, according to the JavaServer Pages tags or features they demonstrate:
The samples are located with the Reference Implementation files.
http://server_host:port/javaserverpages_file
For example:
http://schnauzer:8080/simple.jsp
http://schnauzer:8080/simple.jsp?name=John
A Reference Implementation of the current JavaServer Pages specification, 0.92, is now available for download.
We invite you to experiment with the JavaServer Pages technology using this reference implementation. Please share your questions and suggestions with us about how the specification does or does not address your needs. Where possible please describe your role -- for instance, website designer or dynamic content programmer or server-support builder. If you have experience with other dynamic content technologies and would like to comment on the comparison, we'd appreciate your perspective.
If the use of NCSA Server-Side Includes is new to you, you may want to check out the NCSA online tutorial at:
http://hoohoo.ncsa.uiuc.edu/docs/tutorials/includes.html
Servlets are shipped as part of the Java Servlet Development Kit (JSDK). You can download the JSDK for free from:
http://java.sun.com/products/java-server/servlets/index.html#sdk
Note that the downloadable version may not include proposed additions or changes to the API that are currently undergoing public review prior to inclusion.
The Servlet API is a standard extension to the Java Development Kit (JDK). A new section on servlets has recently been added to the Java tutorial on the Sun Microsystems website. You can find it at:
http://java.sun.com/docs/books/tutorial/servlets/index.html
If you simply want an overview and maybe a quick guide to writing your own JavaBeans component, you might want to take a look at two tutorials on the Sun Microsystems' site:
The JavaBeans Development Kit (BDK) contains a Bean tester called BeanBox, sample Beans, and a tutorial. You can download the BDK from:
http://java.sun.com/beans/software/bdk_download.html
.
For the latest news and Frequently Asked Questions about JavaBeans component, visit Sun Microsystems' JavaBeans website at http://java.sun.com/beans/
There are numerous websites, books, and courses about the Java programming language. To start, you may want to check out the free Java tutorial on Sun Microsystems' website:
http://java.sun.com/docs/books/tutorial/index.html
Sun Microsystems also published two series of Java language books:
Information about the Java Plug-in (formerly called Java Activator) for client browsers can be found on the Sun Microsystems' website at http://java.sun.com/products/plugin/
A | B | C | D | E | F | G | H | I | |
Back
to JavaServer Pages Specification - DraftThis interface is for getting data from the client to the servlet for a service request. Network service developers implement the ServletRequest interface. The methods are then used by servlets when the service method is executed; the ServletRequest object is passed as an argument to the service method.
Some of the data provided by the ServletRequest object includes parameter names and values, attributes, and an input streamto read data from the client. Subclasses of ServletRequest can provide additional protocol-specific data. For example, HTTP data is provided by the interface HttpServletRequest, which extends ServletRequest. This framework provides the servlet's only access to this data.
Bodies of Multipurpose Internet Mail Extensions (MIME) files are either text or binary data. Use getReader to handle text, including the character encodings. The getInputStream call should be used to handle binary data. Multipart MIME bodies are treated as binary data, since the headers are US-ASCII data.
Note: Not all of the methods in ServletRequest interface are shown here. Only methods that have been added to the ServletRequest interface are shown.
public abstract void setAttribute(String key, Object o)
Back
to JavaServer Pages Specification - DraftThe ServletContext interface gives servlets access to information about their environment and allows them to log significant events.
A servlet's ServletContext object is at least as unique as the virtual host in which it resides. Services may also provide ServletContext objects that are "children" of the host ServletContext for servlets that are grouped together by administration settings or by a Servlet Deployment JAR file. This allows groups of servlets to share private data.
It is useful to think of the ServletContext as a servlet's "view" into the environment in which it is running. The object representing this "view" is not the actual environment, but gives the Servlet access to the information that it is allowed to see. In the case of a grouped servlet (a servlet that was deployed in a JAR with private resources and other data), this view would allow the servlet to access the resources that it was deployed with, but servlets that were not part of this grouping would not be able to see these resources.
Note: Not all of the methods in ServletContext interface are shown here. Only methods that have been added to ServletContext interface are shown.
public RequestDispatcher getRequestDispatcher(String uripath);
If the server that is implementing this interface supports the notion of servlet aliasing (mapping a URI name space to a servlet), then the URI parameter should be processed through that aliasing mechanism.
If the URI resolves to a servlet, including a JavaServer Pages file that has been compiled into a servlet, then:
When the URI begins with a "/" it is assumed to be relative to the document root. Otherwise it is assumed to be relative to the URI that invoked this request, which can be retrieved with getRequestURI().
Back to JavaServer Pages Specification - Draft
java.lang.Object | +----java.lang.Throwable
The Throwable
class is the superclass of all errors and exceptions in the
Java language. Only objects that are instances of this class (or of one of its subclasses)
are thrown by the Java Virtual Machine or can be thrown by the Java throw
statement. Similarly, only this class or one of its subclasses can be the argument type in
a catch
clause.
A Throwable
class contains a snapshot of the execution stack of its thread
at the time it was created. It can also contain a message string that gives more
information about the error.
Here is one example of catching an exception:
try { int a[] = new int[2]; a[4]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); }
Throwable
with no detail message. Throwable
with the specified detail message. Throwable
. Throwable
and its backtrace to the standard error stream. Throwable
and its backtrace to the specified print stream. Throwable
and its backtrace to the specified print writer. public Throwable()
Throwable
with no detail message. The stack trace is
automatically filled in. public Throwable(String message)
Throwable
with the specified detail message. The stack
trace is automatically filled in. public String getMessage()
Throwable
, or null
if this Throwable
does not have a detail message. public String getLocalizedMessage()
Throwable
. Subclasses may override
this method in order to produce a locale-specific message. For subclasses that do not
override this method, the default implementation returns the same result as getMessage()
.
public String toString()
Throwable
. public void printStackTrace()
Throwable
and its backtrace to the standard error stream. public void printStackTrace(PrintStream s)
Throwable
and its backtrace to the specified print stream. public void printStackTrace(PrintWriter s)
Throwable
and its backtrace to the specified print writer. public native Throwable fillInStackTrace()
try { a = b / c; } catch(ArithmeticThrowable e) { a = Number.MAX_VALUE; throw e.fillInStackTrace(); }
Throwable
object. Copyright © 1998 Sun Microsystems, Inc. All Rights Reserved. |