JavaServer

JavaServer Pages Specification - Draft

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:

Introduction

JavaServer Pages technology lets you embed a scripting language in web pages (HTML documents). The scripted HTML file has a .jsp extension to identify it as a JavaServer Pages file to the server. Before the page is served, the JavaServer Pages syntax is parsed and processed into an object on the server side. The resulting object generates dynamic HTML content and sends it back to the client.

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:

scripting language
Java
compiled JavaServer Pages object
servlet
Java components
JavaBeans components

JavaServer Pages Access Model

The server can use JavaServer Pages in either of the following ways:

  1. A request comes into a JavaServer Pages file. The page accesses reusable components, such as JavaBeans components, that perform particular well-defined computations (such as accessing a database) and store result-sets as bean properties. The page uses such components to generate dynamic content and presents it back to the client. The contract that the JavaServer Pages developer cares about is the bean interface.
  2. A request comes in to a servlet which generates some dynamic content and invokes a JavaServer Pages file to present this content.

    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 file

In 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.

Syntax

The syntax of JavaServer Pages can be divided into five main areas.

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:

JavaServer Pages Declarations

All declarations that define class-wide variables for the servlet class and all methods that are classwide definitions can be defined in a JavaServer Pages file within a SCRIPT tag. The SCRIPT open tag is:
<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>

JavaServer Pages Scriptlets

The body of the JavaServer Pages scriptlet is the heart of the body of the service method of the generated servlet unless a specific method directive is specified. Any valid Java code can be used. The script specified here can rely upon a set of predefined variables. These variables are:

The code itself is embedded between <% and %> tags. For example:

<% out.println("Hello"); %>
Another example:
<%
foo = request.getParameter("Name");
out.println(foo);
%>

JavaServer Pages Expressions

These are tags that contain Java language expressions and that will be replaced with the values of those expressions. These are specified between <%= and %> tags. Expressions specified within these tags will first be evaluated, then the result converted into a string and displayed. Conversions to string representation for all primitive types such as int , float , and so on are provided automatically. For example:
<%= foobar %>
will substitute the value of "foobar" in place of the tag.

JavaServer Pages Beans

One of the most powerful features of JavaServer Pages technology is that JavaBeans components can be accessed from within a JavaServer Pages file. Any of the following actions can be performed on the bean. The bean can be:

  1. created from a serialized file or a class file
  2. referred to from an HTTP session
  3. passed to the page from a servlet

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() %> .

Errors in JavaServer Pages

There can be errors in a JavaServer Pages file. These errors are reported back to the client (i.e browser) trying to access the page. All errors are of type 500, internal error. The specific errors reported back to the client are:

JavaServer Pages APIs

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. 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:

Special Considerations

Bean Introspection and Security

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 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. 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:

Multiple Clients on Same Machine

In session tracking, when scope=session and introspection=yes, there are concurrency issues of which you should be aware. If more than one client (browser) on a single machine accesses a JavaServer Pages file on the server, session tracking will treat them as if they were the same client.

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.

Samples

The following samples help illustrate the use of JavaServer Pages technology:

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

Simple Sample

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=Trent
would lead to a response:
Hello Trent

Login Sample

In this sample, the JavaServer Pages file accesses a bean component. The bean component allows a user to log in to a specified realm. If the login succeeds, the bean component exposes properties that contain the preferences of the user who just logged in. If the login fails, the bean component exposes a property to describe the nature of the failure.

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.

In this case, following the JavaBeans design patterns, the corresponding property names become:

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.

The JavaServer Pages designer simply accesses the bean properties like getForeground() , to access the results. In this example, the JavaServer Pages file is login.jsp. This page uses the LoginBean class to accept user login and set browser color preferences.

Colors Sample

In this sample, you are asked to guess a particular pair of background and foreground colors. If only one entry of the color pair is guessed correctly, that one is displayed. (For instance, if the correct foreground color was guessed, the foreground would indeed be set to that color.) If both colors are correctly guessed, the page is set accordingly.

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.


Appendix A: HttpServiceRequest

Back to JavaServer Pages Specification - Draft

Class com.sun.server.http.HttpServiceRequest

java.lang.Object
   |
   +----com.sun.server.http.HttpServiceRequest

public class HttpServiceRequest
implements javax.servlet.http.HttpServletRequest
extends Object
This class represents an HTTP request. It implements javax.servlet.http.HttpServletRequest. The methods in the HttpServletRequest interface are not shown here. Only methods that have been added to this class that are not in the servlet interface are shown here.


Method Index

 o setAttribute(String, Object)
This method stores an attribute in the request context

Methods

 o setAttribute
 public void setAttribute(String key,
                          Object o)
This method stores an attribute in the request context

Parameters:
key - a String specifying the name of the attribute
o - a context object stored with the key.

Appendix B: HttpServiceResponse

Back to JavaServer Pages Specification - Draft

Class com.sun.server.http.HttpServiceResponse

java.lang.Object
   |
   +----com.sun.server.http.HttpServiceResponse

public class HttpServiceResponse
implements javax.servlet.http.HttpServletResponse
extends Object
This class represents an HTTP response. It implements the javax.servlet.http.HttpServletResponse interface. The methods in the HttpServletResponse interface are not shown here. Only methods that have been added to this class that are not in the servlet interface is shown here.


Method Index

 o callPage(String, HttpServletRequest)
This method is used to serve a page from within a servlet.

Methods

 o callPage
 public void callPage(String fileName,
                      HttpServletRequest hreq) throws ServletException, IOException
This method is used to serve a page from within a servlet. A regular HTML page can be served or a JavaServer Pages page can be served. If its a JavaServer Pages page being served, then some context can be passed to it via the request object. The file passed back will be passed with a header directive that will indicate to the browser that this page is not to be cached.

Parameters:
fileName: - The name of the URL that identifies a file that will be used to generate the output and present the content. When the name begins with a "/" it is assumed relative to the document root. When it does not begin with a "/" it is assumed to be relative to the URL that this current request was invoked with.
req: - The HttpServletRequest object of the servlet invoking this method. Typically the content is passed as a bean in the context of the request object.

Appendix C: Sample code for login.jsp

Back to JavaServer Pages Specification - Draft

<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>



Appendix D: Sample code for LoginBean.java

Back to JavaServer Pages Specification - Draft

/*
 * @(#)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;
    }
}



Appendix E: Sample code for colors.jsp

Back to JavaServer Pages Specification - Draft

<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>


Top
jsp-feedback@eng.sun.com
Copyright © 1998 Sun Microsystems, Inc.
All Rights Reserved.