
Preview Pack: JavaServer Pages
Java Web Server Documentation
A word about Preview Packs
This document talks about
JavaServerTM Pages,
a new feature currently under development for the
JavaTM
Web ServerTM.
Enjoy but don't deploy.
The designation "Preview Pack" indicates the feature
is still under development and subject to change.
The Java Web Server Team
|
JavaServer Pages provide a clean separation of
content from presentation. In the past, to create
dynamic pages you had to wear both a web page designer
and a programmer hat. The result was
often pages that were compromised rather than optimized.
JavaServer Pages give you incredible flexibility.
Combine your choice of layout (minimal, moderate, or advanced HTML)
with your choice of content generators (simple Java Code, 3rd-party JavaBeans
components, or beans you write yourself) for the solution that's right
for you. Separating the tasks means not only that you can concentrate on one
task at a time, but also that you can assign those tasks to different team members.
JavaServer Pages let you pick the combination that suits your needs,
your skills, and your time.
The rest of this document gives you the bigger picture:
JavaServer Pages let you embed a scripting language into 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 a
servlet on the server side.
The servlet so generated will output real dynamic content back
to the client.
JavaServer Pages use the JavaTM programming
language as the default scripting language.
This means that scripting on the server side can take
advantage of the full set of capabilities that the
Java programming language offers.
(Support for other scripting languages might be added
in the future.) In addition, JavaServer Pages provide a way to easily
access reusable JavaBean components.
Traditionally, dynamic content for web pages has been generated
in one of the following ways:
- A CGI bin script
- A scripting language in the HTML page
Both these approaches have the same shortcomings: they mix content
generation with presentation.
JavaServer Pages solve this problem easily
and cleanly. JavaServer Pages provide:
- Simple scripting on the server side that takes
advantage of Beans and provides a powerful
dynamic content generation facility on the server side.
- Separation of dynamic content generation and the
presentation of the content.
- The ability to focus on presentation separately from content.
This allow the tasks of webpage design and content generation to be worked
on by different people simultaneously or the same person sequentially.
- The opportunity to employ re-usable components.
Within the content generation task, content can be generated
by re-usable components such as JavaBeans components.
So now the business logic or database access you created
for one set of web pages can easily be reused.
- The ease of making changes.
Compilation of the Java/HTML page is automatic the first time the page
is invoked. If you make changes, it recompiles automatically, otherwise
the server continues to use the cached copy providing remarkably fast access.
- Web Page Design
- Determine the nature of the information to be displayed
- Create a page design in HTML to display that information
(You and the Dynamic Content developer will need to agree
on the names and tags you will use to access the data. For instance,
by using a Bean tag and calling the Bean properties by name.)
- Save the file with an .jsp extension.
- Place the file in your document root directory. (By default,
this is the public_html subdirectory of the webserver root.)
- Dynamic Content Implementation
- Determine how the information to be generated will be
created
- Write any valid Java code (including SQL calls) or
use special tags to declare and access your own (or third-party)
JavaBeans components.
- If using your own components, write them.
- Place any classes or components that need to be accessed
into a directory in your CLASSPATH. (The default CLASSPATH
when you install the Java Web Server includes
the /classes subdirectory of the webserver root.)
- JavaServer Pages are cross-platform.
Thanks to the power of the Java programming language, the
Java Web Server runs on any platform that is JDK 1.1 (or above)
compliant. That means, whether your server platform is Windows NT or
Solaris or something else, the Java Web Server can be used to serve pages
created using JavaServer Pages technology.
- JavaServer Pages can be cross-server.
JavaServer Pages can be run
on any web server which implements support for them.
Like servlet support, cross-server functionality is expected to be
available on other servers currently supporting the Java language.
To invoke the JavaServer Pages samples, with the Java Web Server running,
enter a URL of the following form into the locator field of your browser:
http://<server_host>:<port>/<java_server_page_file>
For example:
http://rtc:8080/colors.jsp
- <Simple Sample
You can personalize the reply by passing a value for the name
parameter when calling this sample page. If you do not provide
value for the name parameter, the response is the generic "Hello World".
For example, typing:
http://rtc:8080/simple.jsp?name=Julie
will lead to a response:
Hello Julie
This example 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.
View source page for simple.jsp
Run the sample
-
You are asked to guess a particular pair of background and foreground
colors. 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.
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.
This example shows several of the elements
used in JavaServer Pages. These elements are discussed in the
Syntax section of this document:
- a directive (<%@ %>)
to import a package
- a bean tag (<BEAN > </BEAN >) to declare
an existing Bean and allow access to it
- an expression (<%= %>)
to be evaluated
- straight Java code statements (<% %>)
to handle flow of execution
- normal HTML tagging, including forms tags
View source page for colors.jsp
Run the sample
The server uses JavaServer Pages in two ways:
- A request comes into a JavaServer Page. The page accesses reusable
JavaBean components that perform particular well-defined computations
(like access a database) and store result sets as bean properties. The
page uses such beans to generate dynamic content and present it back
to the client. The contract that the JavaServer Pages developer cares about
is the bean interface.
- A request comes
in to a servlet that generates the dynamic content that the response would
contain. The servlet invokes a JavaServer Page that will present the content
generated from the servlet.
There are two APIs to support this model of request processing using
JavaServer Pages. One API facilitates
passing context between the invoking servlet
and the JavaServer Page. The other API lets the invoking servlet specify
which JavaServer Page 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
not mandate it.)
A request comes into a JavaServer Page
In the JavaServer Pages access model, dynamic content is generated
by bean components which are accessed from the page. The
presentation of the content is done using a
JavaServer Page. This access model is shown below:
In the JavaServer Pages request model shown above, the client makes a
request that is handled by a JavaServer Page. The JavaServer Page
refers to a BEAN component which is passed the request parameters
automatically via JavaBeans
introspection. The JavaServer Page can then query the bean to obtain the
results of the computation. Also 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.
TM or a
JavaTM
BlendTM component.
The results are obtained by the JavaServer Page using standard
bean property readers.
The results so obtained are displayed using HTML. Typically, the bean
developer is a Java programmer and
the JavaServer Page designer is a web page designer or an HTML
programmer. JavaServer Pages 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 below:
In the JavaServer Pages request model shown here, 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 particular 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 Page. The JavaServer Page 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 Page.
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.
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 >"}+ %>
There is a predefined set of variables which are described below.
- language : The language
variable defines the scripting language used
in the file. The scope of this tag spans the entire file. When used more
than once, only the first tag is significant. If omitted
entirely, the default scripting language used is java (for the
Java programming language). This
is the only value that language can accept
at this time.
- method : The method variable
defines the name of the method which will contain the body of
generated code from the script. By default,
the method defined in the generated servlet is service. When
a specific method name is used, the generated code becomes the
body of the specified method name. The scope of this tag spans
the entire file. When used more
than once, only the first tag is significant.
An example is shown below.
<%@ method = "doPost" %>
- import : The import variable defines the
list of packages
that will be imported by the servlet. This is a comma-separated list of
Java language package names or class names that the servlet
imports. This tag can be used multiple times within a file to import
different packages.
- implements : The implements variable
defines the list of interfaces that the generated servlets implement. The
value for this variable is a comma-separated list of Java language interface
names. This tag can be used multiple times within a file to implement
different interfaces.
- extends : The extends variable defines the
the super class of the generated servlet. The value is the name
of the Java language class from which the servlet extends. The scope of this
tag spans the entire file. When used more
than once, only the first tag is significant.
Following are some examples of JavaServer Pages directives:
<%@ import = "java.io.*,java.util.Hashtable" %>
<%@ extends = "javax.servlet.http.HttpServlet" %>
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 tag begins with a:
< SCRIPT runat=server >
and ends with a:
< /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:
- request: the servlet request class as defined by
javax.servlet.http.HttpServletRequest
- response: the servlet response class as defined by
javax.servlet.http.HttpServletResponse
- out: the servlet output writer class as defined by
java.io.PrintWriter
- in: the servlet input reader class as defined by
java.io.BufferedReader
The code itself is embedded between
<% and %> tags. For example:
<% response.getPrintWriter().print("Hello"); %>
Another example:
<%
foo = request.getParameter("Name");
out.println(foo);
%>
JavaServer Pages Expressions
These are tags that contain Java language expressions in that will be
replaced with
the values of those expressions. These are specified between
<%= and %> tags. Expressions specifed within these tags will first be
evaluated, the result will then be converted into a string and then
displayed. Conversions to string representation for all primitive types like
int , float etc... 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 is that JavaBeans can be
accessed from within a JavaServer Pages file. Any of the following actions can be
performed on the bean. The bean can be:
- created from a serialized file or a class file
- referred to from an HTTP session
- passed to the page from a servlet
So, a JavaServer Page file can access reusable server-side components by just declaring
them in the file. Bean properties can then be accessed inside the JavaServer
Page 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 Page 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 set properties. 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=" < value > " varname=" <
value >" class=" <
name > " introspect="{yes|no}"
serializedfile=" < value >"
create="{yes|no}" scope="{request|session}">
and closes with an optional < /BEAN > tag. The attributes name,
varname, class, create, scope, and
serializedfile are described below.
- name: The value of the name
attribute in the beginning tag identifies the
key used to lookup the bean in the appropriate scope.
For example, this might be the session key value with which
the bean is stored.
- varname: The value of the varname
attribute in the beginning tag identifies the variable
name that will refer to this bean in the rest of the
JavaServer Pages file. This is an optional attribute. If it is not
specified, the name of the variable defaults to the
name of the bean as specified in the name
attribute above.
- class: The value of the class attribute is
the name of the class file that defines the bean. When not
specified the value defaults to the type Object.
- introspect: The value of the introspect attribute is
either a "yes" or a "no" . If it is not specified,
the value defaults to the type "yes". When the value is a
"yes" , all request properties are examined and the appropriate
property setter methods got from the BeanInfo of the bean
is called if they match.
So by just declaring a bean tag, the web page designer gets a handle to a
bean whose properties have been set to the values of the parameters (query
parameters or posted form parameters) that the client called the page with.
- create: The value of the create attribute is either
yes or no. If yes is specified, the
bean is created if not found in the scope specified. The default
value of create is yes .
- scope: The value of the scope parameter can be one of
these values:
- request : This bean is retrieved from the request
context. The bean is set as a context in the request
by a servlet invoking this dynamic page using
the APIs described later in this document. This is the
default value used when scope is not specified. If the bean is not part of
the request context, then the bean is created and stored in the request context
unless the create attribute is no.
- session : This bean is reused from the current
session if present. If not present, it
is created and stored as part of the session if the
create attribute is yes.
The scope attribute is optional. If it is not specified, it
defaults to the request scope.
- serializedfile: The value of the serializedfile attribute
is the name of the serialized file that contains
the bean. This attribute is used only when the bean is not
present in the scope of the BEAN tag and
the value of create is yes.
An example BEAN tag might be:
< BEAN name="foobar" class="FooClass" scope="request" >
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() %> .
JavaServer Pages APIs
Two interfaces are used to support JavaServer Pages. These APIs provide a
way to separate content generation
from the presentation of this content. The idea is for a servlet to be able
to generate content and the 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 mostly contains presentation logic. To access the dynamic content, the
JavaServer Pages file uses the BEAN tag described above.
The two JavaServer Pages APIs are defined below:
- com.sun.server.http.HttpServiceRequest :
This class implements the
javax.servlet.http.HttpServletRequest interface and adds two
methods to set and retrieve attributes defined by name.
- com.sun.server.http.HttpServiceResponse :
This class implements the
javax.servlet.http.HttpServletResponse interface and adds a method
that allows servlets to call pages and optionally pass a context.