About this document
This document is an initial draft of the JavaServer(TM) Pages specification. It will be available for review and comment on the Sun Microsystems website until June 18, 1998, at which time it will be removed for update. Comments received will be carefully considered and updates will be 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. |
The JavaServer(TM) Pages technology is a simple yet powerful way to dynamically generate HTML on the server side. This document describes the underlying model and the proposed specification for that technology in the following sections:
JavaServer Pages technology uses the Java(TM) programming language as the default scripting language. This means that scripting on the server side can take full advantage of the powerful set of capabilities that the Java programming language offers. (Support for other scripting languages may be added in the future.) In addition, the JavaServer Pages technology provides a way to easily access reusable components such as JavaBeans(TM).
Traditionally, dynamic HTML content has been generated either by:
Both of these approaches have the same shortcomings: they mix content generation with presentation logic. The web page designer and the servlet (or business logic) developer are different people possessing different skill sets. JavaServer Pages technology offers solutions that helps both web page developers and business logic developers do their own jobs without having to worry about the other.
There are many possible implementations of the JavaServer Pages technology. To make the discussion of the technology as clear as possible, we will assume the following default implementation in the rest of this document:
|
The server can use JavaServer Pages in either of the following ways:
There are two APIs to support this model of request processing using JavaServer Pages technology. One API facilitates passing context between the invoking servlet and the JavaServer Pages file. The other API lets the invoking servlet specify which JavaServer Pages file to use.
(In both of the above cases, the page could also contain any valid Java code. We only encourage separation of content from presentation, we do not mandate it.)
A request comes into a JavaServer Pages fileIn the JavaServer Pages request model shown below, the client makes a request that is handled by a JavaServer Pages file. The JavaServer Pages file refers to a BEAN component which is passed the request parameters automatically via introspection. The JavaServer Pages file can then query the bean to obtain the results of the computation.
(If the bean happens to implement the Servlet interface, the service method of the servlet is called for each request.Each time a property is queried, the bean can do some dynamic computation to return the result.)
Some example bean components that can be used within a JavaServer Pages file might be a JDBC(TM), Java(TM) Blend(TM) or Enterprise JavaBeans(TM) component. The results are obtained by the JavaServer Pages file using standard bean property readers. The results so obtained are displayed using HTML. Typically, the bean developer is a Java programmer and the JavaServer Pages designer is a web page designer or an HTML programmer. JavaServer Pages technology allows them each to do their job by cleanly separating content generation from presentation logic.
A request comes in to a servlet
Another way to achieve the same effect is shown in the
JavaServer Pages request model below.
The client makes a request
that is handled by a Java servlet. The servlet then generates the content
that will be displayed in the HTML page. In this example, the servlet
uses JDBC to communicate with a database in order to obtain the content.
The resulting content is then wrapped into a bean which is passed
to a JavaServer Pages file.
The JavaServer Pages file uses the content generated by the servlet
and presents it in HTML.
In this case, content generation is handled by the servlet and content presentation is handled by the JavaServer Pages file.
The syntax is extensible to allow other tags in the future.
In the following sections, each of these syntax items is described in detail.
JavaServer Pages Directives
The general syntax of the JavaServer Pages directive is
<%@ (variable="value")+ %>
The possible variables are:
<%@ language="java" %>
<%@ method="doPost" %>
<%@ import="java.io.*,java.util.Hashtable" %>
<%@ content_type="text/html;charset=UTF-8" %>
<%@ extends="javax.servlet.http.HttpServlet" %>
<SCRIPT runat=server>
and the close tag is:
</SCRIPT>
In the body of the
SCRIPT tag, Java language variables
that will be used in the servlet class can be declared. Class wide method
definitions can also go into the body of the SCRIPT tag.
The runat=server tag is
required to indicate that this tag is for server-side processing rather than
a hint for the browser. An example usage could be:
<SCRIPT runat=server>
int i = 0;
String foo = "Hello";
private void foo() {
// some code;
}
</SCRIPT>
The code itself is embedded between <% and %> tags. For example:
<% out.println("Hello"); %>
Another example:
<%
foo = request.getParameter("Name");
out.println(foo);
%>
<%= foobar %>
will substitute the value of "foobar" in place of the tag.
So, a JavaServer Pages file can access reusable server-side components by just declaring them in the file. Bean properties can then be accessed inside the JavaServer Pages file. The bean does not necessarily have to come from a class file or a serialized file. For example, a servlet can generate dynamic content and store it in a bean. This bean can then be passed to a JavaServer Pages file for use within the web page defined by the file. The APIs to do this are described in the API section below.
The syntax to refer to a bean inside a JavaServer Pages file is defined by the BEAN tag. Once a bean is declared this way, all request parameters, be it form based or query parameter based, are set in the bean using the write method to set properties as per the JavaBeans design patterns. Also if the bean happens to implement the Servlet interface, the service method of the servlet is called for each request and the init method is called once per creation. Once created, a bean's lifetime is either for the lifetime of the current request or the lifetime of the HTTP session depending on what the scope in the BEAN tag is. The BEAN tag opens with:
< BEAN name="lookup name"
varname="alternate variable name"
type="class or interface name"
introspect="(yes|no)"
beanName="file name"
create="(yes|no)"
scope="(request|session)"
>
and closes with a required < /BEAN > tag. Between the
< BEAN ... > and the < /BEAN > tag, a list of
PARAM tags
can be optionally specified. The attributes inside the BEAN tag need not
appear in any particular order.
The attributes are defined this way:
As described earlier, the BEAN tags can optionally have nested PARAM tags inside them.The syntax of the PARAM tag that is allowed to be optionally nested inside the BEAN tag is shown below:
<PARAM {name="value"}+>
The PARAM tag can define a value for a list properties that will be automatically set in the bean via JavaBeans introspection. These properties are set once for each bean when the bean is created. If the request has parameters that set the value of the same properties that the PARAM tag set, the request properties override the PARAM properties.
An example BEAN tag might be:
<BEAN name="foobar" type="FooClass" scope="request">
<PARAM fooProperty="fooValue" barProperty="1">
</BEAN>
Once a bean is declared it can be accessed anywhere in the file. For example, the bean declared in the example above can be accessed inside a JavaServer Pages file as follows:
The name of the row is <%= foobar.getRowName() %> .
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. Then the servlet that generated the context generates a response by passing the request context to a JavaServer Pages file that contains mostly presentation logic. To access the dynamic content, the JavaServer Pages file uses the BEAN tag described above.
An example might be if a web site developer set up a timed program on a web server 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:
Take the following example. A client inquiry form has name, address,
and email fields.
This particular form calls a JavaServer Pages file when
the form is submitted.
The JavaServer Pages has a BEAN 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.
As in the more general case of bean development, steps can be taken by the JavaServer Pages developer to avoid client access of bean properties. 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 PARAM values or request parameters. However, the JavaServer Pages code can still explicitly call the hidden set method.
This happens because session id is assigned by machine. Therefore, both clients will have the same session id and so the page access of one will be placed in a session object shared with the other.
To invoke a JavaServer Pages file on a webserver which supports JavaServer Pages, you would enter a URL of the following format into the locator field of your browser:
http://<server_host>:<port>/<java_server_page_file>For example:
http://rtc:8080/colors.jsp
This sample is the JavaServer Pages' version of the venerable "Hello World" program. You can personalize the reply by passing a value for the name parameter when calling the page. If you don't provide a value for the name parameter, the response will be the generic "Hello World".
This sample shows how basic Java statements enclosed in JavaServer Pages tags can be combined with HTML tags. The Java code calls the getParameter method of ServletRequest of the Servlet API.
Here's the code:
< html > < head > < /head > < body > HELLO < %out.println(request.getParameter("name")); % > < /body > < /html >
For example, typing:
http://rtc:8080/simple.jsp?name=Trentwould lead to a response:
Hello Trent
One of the things the sample illustrates is how easily components can be accessed from a JavaServer Pages file. The sample also provides some indication as to the ease with which the job of content presentation can be separated from that of content generation when using JavaServer Pages technology. The JavaServer Pages designer does not need to know anything about the logic contained in the bean component itself, and has no direct access to the code in that bean. However, the JavaServer Pages designer understands the "contract" with the bean in terms of what properties can be queried and creates a page that uses this bean.
<html> <BEAN name="login" scope="session" type="LoginBean"> % if (login.isValidLogin()) { %> <!-- Advertisement goes here --> <img src=<%= login.getImage() %>>> % } else {%> Login Failed: <%= login.getError()%> % } %>
The bean requires three properties to be set before it can do its job.
The JavaServer Pages designer (who is a web page designer or HTML programmer) creates the JavaServer Pages file that requires the user to input the data. The JavaServer Pages designer also queries the bean properties and displays content according to user preferences. To create the page, the JavaServer Pages designer needs to know only the name of the class file or serialized file that contains the bean. This file must be in the CLASSPATH of the server.
The bean component needs input from the JavaServer Page. The following methods are provided to set these properties.
setUserName(String)
setPassword(String)
setRealm(String)
In this case, following the JavaBeans design patterns, the corresponding property names become:
userName
password
realm
The JavaServer Pages designer only needs to provide a form with form parameters whose property names match the above property names. When a request comes in for the page, the form parameters are automatically set in the bean used from the JavaServer Pages file.
The bean component has methods to access the results.
cb.getForegroundPreference()
cb.getBackgroundPreference()
cb.isValidLogin()
cb.getErrorMessage()
Color choices are gathered (using an HTML form in the page) and passed to a Bean (using the submit button). A counter is displayed that indicates the number of times you have submitted a guess.
View source page for colors.jsp in Appendix E.
This example shows several of the elements used in JavaServer Pages. :
These elements are discussed in the Syntax section of this document.
Copyright © 1998
Sun Microsystems, Inc. All Rights Reserved. |
java.lang.Object | +----com.sun.server.http.HttpServiceRequest
public void setAttribute(String key, Object o)
java.lang.Object | +----com.sun.server.http.HttpServiceResponse
public void callPage(String fileName, HttpServletRequest hreq) throws ServletException, IOException
<html> <head><title>Hello</title></head> <% if (request.getMethod().equals("GET")) { %> <form method=POST action=/login.jsp> Username: <input type=text name= userName size=16> <br> Password: <input type=password name= password size=16> <br> Realm: <input type=text name= realm size=16> <p> <input type=submit name=action value="Submit"> </form> <% } else { // it is a POST request %> <!-- jsp.beans.LoginBean MUST be CLASSPATH --> <bean name="login_bean" type="jsp.beans.LoginBean" scope="session" varname="cb" create="yes"> </bean>
/* * @(#)LoginBean.java 1.3 98/02/25 * * Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved. * * This software 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. * * CopyrightVersion 1.0 */ package jsp.beans; public class LoginBean { private String fg = null; private String bg = null; private String errorMsg = null; private String user = null; private String realm = null; private String passwd = null; // form parameter userName public void setUserName(String x) { user = x; } // form parameter password public void setPassword(String x) { passwd = x; } // form parameter realm public void setRealm(String x) { realm = x; } public String getForeground() { return fg; } public String getBackground() { return bg; } public String getErrorMessage() { return errorMsg; } public boolean isValidLogin() { // // meat of the logic goes here. // // access userName, passwd and realm // here to do something meaningful // on error set errorMsg to the reason // on success fetch user preferences // and set fg and bg // fg = "red"; bg = "black"; return true; } }
<html> <!-- jsp.beans.ColorGameBean MUST be CLASSPATH --> <%@ import="jsp.beans.ColorGameBean" %> <bean name="cb" type="jsp.beans.ColorGameBean" create="yes"\ scope="session" introspect="yes"> </bean> <body bgcolor= <%= cb.getColor1() %>> <font color=<%= cb.getColor2() %>> <p> This web page is an example using JavaServer Pages tagging and BEANs. <p> Guess my favorite two colors <p> If you fail to guess both of them - you get yellow on red. <p> If you guess one of them right, either your foreground or your background will change to the color that was guessed right. <p> Guess them both right and your browser foreground/background will change to my two favorite colors to display this page. <% if (cb.getHint()) { %> <p> Hint #1: Vampires prey at night! <p> Hint #2: Nancy without the n. <% } %> <% if (cb.getSuccess()) { %> <% cb.reset(); %> <p> CONGRATULATIONS!! <p> You guessed in <%= cb.getAttempts() %> attempts! <% if (cb.gotHints()) { %> <p> ( although I know you cheated and peeked into the hints) <% } %> <% } else { %> <p> Total attempts so far: <%= cb.getAttempts() %> <p> <form method=POST action=/colors.jsp> Color #1: <input type=text name= color1 size=16 value="<%=cb.getColor1()%>"> <br> Color #2: <input type=text name= color2 size=16 value="<%=cb.getColor2()%>"> <p> <input type=submit name=action value="Submit"> <input type=submit name=action value="Hint"> </form> <% } %> <p> </font> </body> </html>
![]() |
Copyright © 1998
Sun Microsystems, Inc. All Rights Reserved. |