Using WebLogic JSP
- I. Introduction
- What is JSP?
- The WebLogic Implementation of JSP
- How JSP Requests are Handled
- II. Setting up WebLogic for JSP
- Deploying JSPs in Web Applications
- Deploying JSPs Using the weblogic.properties File
- III. WebLogic JSP Reference
- JSP Tags
- Custom WebLogic JSP Tags (Cache, Process, Repeat)
- Reserved Words
- Directives
- Declarations
- Scriptlets
- Expressions
- A Simple Example with HTML and Embedded Java
- Actions
- Using Sessions with JSP
- Deploying Applets from JSP
- Using the WebLogic JSP compiler
- IV. Troubleshooting guide
- Symptoms in the browser
- Symptoms in the log file
- Other related documents
- The JSP Homepage
- Writing JSP Extensions
- Using WebLogic HTTP servlets
- Writing a Web Application
- JSP examples
- Sun's JSP Homepage
I. Introduction
This developers guide provides a reference to the basic syntax of
JavaServer Pages (JSP), the functionality available, and how to use
JSP with WebLogic Server. It is not intended as a comprehensive
introduction to using JSP. For more information, see:
What is JSP?
JavaServer Pages (JSP) is a JavaSoft specification for combining
Java with HTML to provide dynamic content in web pages. JSPs are more
convenient to write than HTTP
Servlets because they allow you to embed Java code directly into
your HTML pages, in contrast with HTTP servlets where you embed HTML
inside of Java code. JSP is part of the Java Two Enterprise Edition
(J2EE).
JSP allows you to separate the dynamic content of a Web page from
its presentation. It caters to two different types of developers: HTML
developers, who are responsible for the graphical design of the page,
and Java developers, who handle the development of software to create
the dynamic content. Although similar to WebLogic JHTML, a proprietary WebLogic API,
JSP facilitates development of dynamic Web pages through the use of
higher level control tags and JavaBeans.
Because JSP is part of the J2EE standard, JSPs may be deployed on a
variety of platforms, including WebLogic Server. In addition, third
party vendors and application developers can provide JavaBean
components and define custom JSP tags that can be referenced from a
JSP page.
The WebLogic Implementation of JSP
BEA WebLogic JSP supports the JSP 1.1
specification from JavaSoft. JSP 1.1 includes support for defining
custom JSP tag extensions.
WebLogic JSP supports mulitbyte character sets according to the Unicode standard.
How JSP Requests are Handled
- A browser requests a page ending in .jsp from WebLogic Server.
- An internal WebLogic HTTP servlet, called the JSPServlet, which is
configured to handle requests for pages ending in .jsp, reads the request.
- The JSPServlet finds the requested JSP file, and converts it
into a servlet class that implements javax.servlet.jsp.JspPage using the JSP
compiler. The JSP file is only compiled when the page is first
requested, or when the JSP file has changed. Otherwise, the previously
compiled JSP servlet class is re-used, making subsequent responses
much quicker.
- The generated JspPage servlet class is invoked to handle the
browser request.
It is also possible to invoke the JSP compiler
directly with out making a request from a browser. Since the JSP
compiler creates a Java servlet as its first step, you can look at the
Java files it produces, or register the generated JspPage servlet
class as an HTTP servlet.
II. Setting Up WebLogic Server for JSP
There are two ways to set up WebLogic Server for JSP. The first,
familiar to many WebLogic Server users, is to register the JSP Servlet
in the weblogic.properties
file. The second way, which conforms to the Java 2 Enterprise Edition
(J2EE) standard, is to deploy JSPs in a Web Application. A Web
Application is a J2EE standard for bundling together the resources
that comprise an application. These resources include JSP files,
servlets, static HTML pages, Enterprise JavaBeans, (EJB) and
security. Web Applications are deployed using a standardized directory
structure that can be archived into a single file called a .war file, in conjunction with a
deployment descriptor.
Deploying JSPs in Web Applications
Detailed information on deploying JSPs as J2EE Web Applications can
be found in the document Writing a Web
Application.
Deploying JSPs Using the weblogic.properties File
To set up WebLogic Server to serve JSP files:
- Set the following properties in your weblogic.properties file to register the
JSPServlet. There is a commented-out set of properties included in the
default weblogic.properties
that is shipped with the WebLogic Server distribution. You can
uncomment these properties and edit the properties to suit your
environment.
The JSPServlet is a standard HTTP servlet that is included with the
WebLogic Server. Register the JSPServlet it to handle all HTTP
requests for files ending with the extension ".jsp" using the
property:
weblogic.httpd.register.*.jsp=\
weblogic.servlet.JSPServlet
- Set the following initialization arguments for the JSPServlet
using the standard servlet initArgs property as shown here. The bold
parameters are required.
weblogic.httpd.initArgs.*.jsp=\
compileCommand=path to a Java compiler,\
workingDir=directory to store compiled JSP classes,\
verbose=[true | false],\
keepgenerated=[true | false],\
pageCheckSeconds=interval
packagePrefix=package prefix for compiled files,\
Where the argument names are defined as:
- compileCommand
- (Required)
Full pathname of the standard Java compiler used to compile the
generated JSP servlets. For example, to use the standard Java
compiler, you would specify its location on your system with:
compileCommand=/jdk117/bin/javac.exe
- workingDir
- (Required)
Absolute path of a local directory where the compiled class and Java
files from the JSP compiler are placed. For example,
workingDir=/weblogic/myserver/compiled
This directory will contain the .java
and .class files generated from all
JSP files.
Note: Do not point the workingDir to any directory in the
system classpath or the WebLogic classpath.
- verbose
- (Optional) default value is false.
When set to true, debugging information is printed out to the browser, the
command prompt, and the WebLogic Server log file.
- keepgenerated
- (Optional) default is false.
When set to true, the generated .java
source files are stored with the class
files in the directory specified by the workingDir parameter.
- pageCheckSeconds
- (Optional) default value is 0.
Interval at which WebLogic checks to see if JSP files have been
changed and need recompiling. Dependencies are also checked and
recursively reloaded if changed. If set to 0, pages are checked on
every request. If set to -1, pages are not checked until the server is restarted.
- packagePrefix
- (Optional) Default is jsp_servlet.
Specifies the package into which all compiled JSP pages will be
placed.
- encoding
- (Optional) Specifies the character set used in the JSP
page.
Defaults to the default character encoding of your JVM.
- Set the Document Root
The JSPServlet looks for JSP files beneath the WebLogic document
root. The document root is shared by other services of WebLogic
Server, as described under Setting
up a document root in the Setting WebLogic Properties
guide. Set the document root using the following property in the
weblogic.properties file:
weblogic.httpd.documentRoot=path
where path is an absolute directory path, or a relative directory path
from the myserver/ directory under
your WebLogic installation. For example, if you set the property:
weblogic.httpd.documentRoot=jsp_files
uou would publish your JSP files in the directory:
/weblogic/myserver/jsp_files
The document root defaults to the
/weblogic/myserver/public_html directory. Be aware that changing the
document root may affect other aspects of WebLogic Server.
- Set up session tracking (optional).
To enable session tracking, set this property to "true":
weblogic.httpd.session.enable=true
For more information on session tracking, see Setting up Session Management.
III. WebLogic JSP Reference
JSP Tags
The following table describes the basic tags in a JSP page. Each short-hand
tag has an XML equivalent. For more details, see the related section later in
this document.
JSP tag |
Syntax
 |
Description |
Scriptlet |
<% java_code %>
...or use XML equivalent...
<jsp:scriptlet>
java_code
</jsp:scriptlet>
|
Embeds Java source code scriptlet
within your HTML. The Java code is executed and its output is inserted in sequence
with the rest of the HTML in the page. For more, see Scriptlets.
|
Directive |
<%@ dir_type dir_attr %>
...or use XML equivalent...
<jsp:directive.dir_type
dir_attr /> |
Gives a directive to the application
server. The dir_type determines the type of directive being given,
which can accept a list of directives given as name="quotedValue" pairs
separated by white space.
See Directives.
|
Declaration |
<%! declaration %>
...or use XML equivalent...
<jsp:declaration>
declaration; </jsp:declaration>
|
Declares a variable or method that may be referenced
by other declarations, scriptlets, or expressions in the page.
See Declarations.
|
Expression |
<%=
expression %>
...or use XML equivalent...
<jsp:expression>
expression </expression>
|
Defines a Java expression that is evaluated
at page request time, converted to a String, and sent inline to the output stream of the JSP response.
See Expressions.
|
Actions |
<jsp:useBean ... >
JSP body is included if
bean is instantiated here
</jsp:useBean>
<jsp:setProperty ... >
<jsp:getProperty ... >
<jsp:include ... >
<jsp:forward ... >
<jsp:plugin ... >
|
JSP Actions encompass the more advanced features of JSP, and only use XML
syntax. All these actions are supported as defined in the JSP 1.1
specification. See Action.
|
Custom WebLogic JSP Tags (Cache, process, repeat)
If you are using WebLogic 5.1, there are three new JSP tags that have been created by WebLogic for your use. They are obtainable by
downloading Service Pack 6 or higher for WLS 5.1.0. To use them, you must have the weblogic-tags-510.jar in your weblogic.class.path
for proper operation. The following three tags have been added: CacheTag, RepeatTag, and Process Tag.
The cache tag supports caching the work that is done
within the body of the tag. To this end, it supports both
output (transform) data and input (calculated) data. Output caching refers to the content generated by the code within the tag.
Input caching refers to the values that variables are set to by the code within the tag. Output caching is useful when the final
form of the content is the important thing to cache. Input caching is important
when the view of the data can vary independently of the data calculated within the tag.
The caches are stored using soft references to avoid the caching system from being responsible for running the system
out of memory. Unfortunately, due to incompatibilities with the HotSpot's VM and the Classic VM, we must not use soft references
when we are running within HotSpot. You can override the use of
soft references by setting the subsequent global system properties
in the following order of precedence:
weblogicx.jsp.tags.CacheTag.softreferences = true|false
weblogicx.jsp.tags.CacheTag.nosoftreferences = true|false
Use of soft references defaults to true in a classic VM and false
within a HotSpot VM.
You can force the refresh of a cache by setting _cache_refresh to
true in the scope that you want affected. If you want all caches to
always refresh, put it in the application scope. If you want all the
caches for a user to be refreshed, set it in the session scope. If you
want all the caches in the current request to be refreshed set it
as a parameter or in the request.
The <wl:cache> tag specifies content that does need to be updated each time it is displayed. The statements between the
<wl:cache> and </wl:cache> tags will only be executed if the cache has expired or if any of the values of the key attributes
(see table below) have changed.
Attribute |
Required
 |
Default Value |
Description |
timeout |
no |
-1 |
Cache timeout property. The amount of time, in seconds, after which the statements within the cache tag will be refreshed.
This is not proactive, the value will only be refreshed if it is requested. It is acceptable to postfix the
value with units to override the default units of seconds:
ms = milliseconds
s = seconds (default)
m = minutes
h = hours
d = days |
scope |
no |
application scope |
Specifies the scope where the data should is cached. Valid scopes are: page, request, session, application.
Most caches will be either session or application scope.
|
key |
no |
------------- |
Specifies additional values to be used when evaluating whether
to cache the values contained within the tags. The list of keys is
comma-separated. This is the name of the variable whose value you wish to use as a
key into the cache. You can additionally specify a scope by prepending
the name of the scope to the name:
parameter.key | page.key | request.key | application.key | session.key
It defaults to searching through the scopes in the order above. Each
named key will be available within the cache tag as a scripting variable. A list of keys is
comma-separated.
|
name |
no |
------------- |
A unique name for the cache that allows caches to be shared across multiple JSP pages. This same buffer will be used to store the
data for all pages using the named cache. This is useful for textually
included pages that need cache sharing. If this is not set a unique
name will be chosen for the cache.
It is not recommended that you manually calculate the name of the tag,
the key functionality can be used equivalently in all cases.
The name is calculated as "weblogic.jsp.tags.CacheTag." then the URI and
finally a monotonically increasing number representing which tag in the
page you are caching. If somehow different URIs get to the same JSP page
the caches will not be shared in the default case. Use named caches in this
case.
|
size |
no |
-1 (unlimited) |
For caches that use keys, the number of entries allowed.
The default is an unlimited cache of keys. With a limited number of keys the tag uses
a least used system to order the cache. Changing the value of the size attribute of an already used cache will
not change the size of that cache. |
vars |
no |
------------- |
In addition to caching the transformed output of the cache, calculated values
can also be cached within the block. These variables are specified exactly
the same as the cache keys. This is Input caching. |
The following illustrates ways in which the <wl:cache> tag may be used:
<wl:cache>
// the content between these tags will only be refreshed on server restart
</wl:cache>
<wl:cache key="request.ticker" timeout="1m">
// get stock quote for whatever is in the request parameter ticker and
display it, only update it every minute
</wl:cache>
// incoming parameter value isbn is the number used to lookup the book in
the database
<wl:cache key="parameter.isbn" timeout="1d" size="100">
// retrieve the book from the database and display the information
// the tag will cache the top 100 most accessed book descriptions
</wl:cache>
<wl:cache timeout="15m" >
// get the new headlines from the database every 15 minutes and display
them
</wl:cache>
The <wl:process> tag is used for query parameter-based flow control. By using a combination of the four attributes, you can selectively execute the statements between the <wl:process> and </wl:process> tags.
The process tag may be used to declaratively process the results of form submissions. By specifying conditions based on the values
of request parameters you can include or not include JSP on your page.
Tag Attribute
|
Required
|
Description
|
name
|
no
|
The name of a query parameter.
|
notname
|
no
|
The name of a query parameter.
|
value
|
no
|
The value of a query parameter.
|
notvalue
|
no
|
The value of a query parameter.
|
Illustrated below are some ways in which the process tag may be used:
<wl:process notname="update">
<wl:process notname="delete">
// Only show this if there is no update or delete parameter
<form action="<%= request.getRequestURI() %>">
<input type="text" name="name"/>
<input type="submit" name="update" value="Update"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</wl:process>
</wl:process>
<wl:process name="update">
// do the update
</wl:process>
<wl:process name="delete">
// do the delete
</wl:process>
<wl:process name="lastBookRead" value="A Man in Full">
// this section of code will be executed if lastBookRead exists and the value of lastBookRead is "A Man in Full"
</wl:process>
The repeat tag is used to iterate over many different types of sets including Enumerations, Iterators, Collections,
Arrays of Objects, Vectors, ResultSets, ResultSetMetaData, and the keys of a Hashtable. You can also just loop a certain
number of times by using the count attribute:
The <wl:repeat> tag is used to iterate over a variety of Java objects, as specified in the set attribute.
Tag Attribute
|
Req'd
|
Type
|
Description
|
set
|
No
|
Object
|
The set of objects that includes:
- Enumerations
- Iterators
- Collections
- Arrays
- Vectors
- Result Sets
- Result Set MetaData
- Hashtable keys
|
count
|
No
|
Int
|
Iterate over first "count" entries in the set.
|
id
|
No
|
String
|
Variable to contain current object being iterated over.
|
type
|
No
|
String
|
Type of object that results from iterating over the set you passed in. Defaults to Object. This type must be fully qualified.
|
Illustrated below are some ways in which the repeat tag may be used:
<wl:repeat id="name" set="<%= new String[] { "sam", "fred", "ed" } %>">
<%= name %>
</wl:repeat>
<% Vector v = new Vector();%>
// add to the vector
<wl:repeat id="item" set="<%= v.elements() %>">
// print each element
</wl:repeat>
Reserved Words
JSP reserves words for implicit objects in scriptlets and
expressions. These implicit objects represent Java objects that
provide useful methods and information for your JSP page. WebLogic JSP
implements all implicit objects defined in the JSP 1.1
specification. The JSP API is described in the JavaDocs available at
the Sun Microsystem's JSP Homepage.
Note: You may only use these implicit objects within scriptlets or expressions. Using these keywords from a method
defined in a declaration causes a translation-time compilation
error because your page is referencing an undefined variable.
- request
- request
represents the HttpServletRequest
object. It contains information about the request
from the browser, and has several useful methods for getting cookie, header,
and session data.
- response
- response represents the
HttpServletResponse object, and several useful methods for setting
the response sent back to the browser from your JSP page such as cookies, and
other header information.
Warning: You cannot use the response.getWriter() method from within a JSP page, or
a run-time exception will be thrown. Use the out keyword to send the JSP response back to the
browser from within your scriptlet code wherever possible. WebLogic's
implementation of the javax.servlet.jsp.JspWriter uses the javax.servlet.ServletOutputStream.
This implies that you can use response.getServletOutputStream(), but this is
implementation specific. To keep your code maintainable and portable,
use the out keyword.
- out
-
out is an instance of
javax.jsp.JspWriter
which has several methods you can use to send output back to the browser.
Hint: If you are using a method that requires an outputStream, then JspWriter does not work. You can work around this by supplying a
buffered stream, then writing this to out. For example, here is how to write an exception stack trace to out:
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
exception.printStackTrace(new PrintWriter(ostr));
out.print(ostr);
- pageContext
- pageContext represents
a javax.servlet.jsp.PageContext object. It is a
convenience API for accessing various scoped namespaces and
servlet-related objects, and provides wrapper methods for common
servlet-related functionality.
- session
- session represents a javax.servlet.http.HttpSession object for the
request. The session directive is set to true by default, so the session is valid by default. The JSP
1.1 specification states that if the session directive is set to
false, then the session
keyword results in a fatal translation time error. For more
information on using sessions with servlets, see the Developer Guide,
Using WebLogic HTTP
Servlets.
- application
- application represents a
javax.servlet.ServletContext object. Use it to find
information about the servlet engine and the servlet environment. The
servlet requestDispatcher can
also be accessed through the ServletContext, but JSP also provides the forward directive for forwarding
requests to other servlets, and the include directive for including output from other
servlets.
- config
- config represents a javax.servlet.ServletConfig object. It provides access
to the servlet instance initialization parameters. Currently, you
cannot set initialization arguments for a JSP page, unless you
precompile it with the JSP Compiler and
register it as a regular HTTP servlet. For details, see Registering
user-written servlets in Setting WebLogic Properties.
- page
- page represents the servlet
instance generated from this JSP page. It is synonymous to the Java keyword
this within your scriptlet code.
To use page, you must cast
it to the class type of the servlet that implements the JSP page,
because it is defined as an instance of java.lang.Object. By default, the servlet class is
named after the JSP filename. Instead, we recommend that you simply
use the Java keyword this to
reference the servlet instance and get access to initialization
parameters.
For more information on the underlying HTTP servlet framework, see the
related developers guide, Using WebLogic HTTP Servlets.
Directives
Use directives to instruct WebLogic JSP to perform certain
functions or interpret the JSP page in a particular way. You can insert a
directive into the JSP page anywhere. The position is generally irrelevant
(except for the include directive), and you can
use multiple directive tags. The syntax can be written in two forms, shorthand
and XML, as shown here:
- Shorthand:
<%@ dir_type dir_attr %>
- XML:
<jsp:directive.dir_type dir_attr />
Where dir_type specifies the directive
type, and dir_attr can be a list of
one or more directive attributes for that directive type.
All JSP1.1 directives are supported in WebLogic JSP.
Using a Directive to Set the Character Encoding
To specify a character encoding set, use the following directive at the top of the page:
<%@ page contentType="text/html; charset=custom-encoding" %>
Where custom-encoding is the canonical name of the character set that is returned by the getEncoding methods of the InputStreamReader and OutputStreamWriter classes.
The taglib Directive
You use a taglib directive to declare
that your JSP page uses custom JSP tag extensions that are defined in a tag
library. For details on writing and using custom JSP tags,
see the Developers Guide "Writing JSP
Extensions".
Declarations
Use declarations to define variables and methods at the class scope level
in the generated JSP servlet. Declarations made between these tags are
accessible from other declarations and scriptlets in your JSP page.
For example:
<%!
int i=0;
String foo= "Hello";
private void bar() {
// ...java code here...
}
%>
Remember that class scope objects are shared between multiple threads
executing in the same instance of a servlet.
To guard against sharing violations, you should
synchronize class scope objects. If you are not confident writing thread-safe
code, you can declare your servlet as not-thread-safe, by including the
following directive:
<%@ page isThreadSafe="false" %>
Note: By default this attribute is set to true. When you set it
to false, the generated servlet implements the javx.servlet.SingleThreadModel interface, which
prevents multiple threads from running in the same servlet instance.
JSP scriptlets make up the Java body of your JSP servlet's HTTP
response. You include a scriptlet in your JSP page by using the
shorthand or XML scriptlet tags shown here:
- Shorthand:
<%
// Your Java code goes here
%>
- XML:
<jsp:scriptlet>
// Your Java code goes here
</jsp:scriptlet>
Note these features of scriptlets:
- You can have multiple blocks of scriptlet Java code mixed with
plain HTML. The HTML response page provided by the generated JSP
servlet is given by the HTML and the output from the Java scriptlets
in the sequence they appear in the JSP page.
- You can switch between HTML and Java code anywhere, even within
Java constructs and blocks. In the JSP example
with HTML and embedded Java, shown below, the example declares a
Java loop, switches to HTML, then switches back to Java to close the
loop. The HTML within the loop is output multiple times as the loop
iterates.
- You can use the predefined variable out to print HTML text directly to the servlet output
stream from your Java code. You call the print() method to add a string to the HTTP page
response.
- The Java tag is an "inline" tag; it doesn't force a paragraph.
You can include an expression in your JSP file using the tag:
<%= expr %>
Where expr is a Java expression
that is evaluated and its String
representation is placed inline in the HTML response page. It is shorthand for
<% out.print( expr ); %>
You can use it to make your HTML more readable in the JSP page. (This
is equivalent to the backtick in JHTML.) Note the use of the
expression tag in the following example.
A Simple Example with HTML and Embedded Java
<html>
<head><title>Hello World Test</title></head>
<body bgcolor=#ffffff>
<center>
<h1> <font color=#DB1260> Hello World Test </font></h1>
<font color=navy>
<%
out.print("Java-generated Hello World");
%>
</font>
<p> This is not Java!
<p><i>Middle stuff on page</i>
<p>
<font color=navy>
<%
for (int i = 1; i<=3; i++) {
%>
<h2>This is HTML in a Java loop! <%= i %> </h2>
<%
}
%>
</font>
</center>
</body>
</html>
Here is what the resulting page will look like after it is compiled
and rendered in a browser:
Hello World Test
Java-generated Hello World
This is not Java!
Middle stuff on page
This is HTML in a Java loop! 1
This is HTML in a Java loop! 2
This is HTML in a Java loop! 3
|
Actions
Using JavaBeans in JSP
WebLogic JSP supports all functionality outlined in the JSP 1.1
specification with respect to the <jsp:useBean> tag. This allows you to instantiate
Java objects that comply with the JavaBean specification, and refer to
them from your JSP pages.
To complying with the JavaBean specification, objects need:
- A public constructor that takes no arguments
- A setVariable() method for each variable field.
- A getVariable() method for each
variable field.
Instantiating the JavaBean Object
The <jsp:useBean> tag
attempts to retrieve an existing named Java object from an specific scope, and if not
found, may attempt to instantiate a new object and associate it with the name
given by the id attribute. The object
is stored in a location given by the scope attribute, which determines the availability of the
object. For example, the tag:
<jsp:useBean id="cart"
class="examples.jsp.ShoppingCart" scope="session"/>
attempts to retrieve a Java object of type
examples.jsp.ShoppingCart
from the HTTP session under the
name cart. If it does not currently
exist, the JSP attempts to create the new object, and stores it in the HTTP
session under the name cart.
It is good practice to use an errorPage directive with the <jsp:useBean> tag because there are runtime
exceptions that must be caught. If you do not use an errorPage directive, the class
referenced in the JavaBean cannot be created and an InstantiationException may be
thrown.
You can use the type
attribute to cast the JavaBean type to another object or interface,
provided that it is a legal type cast operation within Java. If you
use the attribute without the class attribute, your JavaBean object must already be
present in the scope specified. If it is not legal, an InstantiationException is thrown.
Doing Setup Work at JavaBean Instantiation
The <jsp:useBean> tag
syntax has another format that allows you to define a body of JSP code
that is executed when the object is instantiated. The body is not
executed if the names JavaBean already exists in the specified scope.
This allows you to set up certain properties when the object is first
created such as:
<jsp:useBean id="cart" class="examples.jsp.ShoppingCart"
scope=session>
Creating the shopping cart now...
<jsp:setProperty name="cart"
property="cartName" value="music">
</jsp:useBean>
Note: If you use the type attribute without the class attribute, a JavaBean object is never
instantiated, and you should not attempt to use the tag format to
include a body. Instead, use the single tag format. In this case, the
JavaBean must exist in the specified scope, or an InstantiationException is thrown. Use an errorPage directive to catch the
potential exception.
Using the JavaBean Object
After you instantiate the JavaBean object, you can refer to it by its
id name in the JSP file as a
Java object. You can use it within scriptlet tags and expression evaluator
tags, and you can invoke its setXxx()
or getXxx() methods using the
<jsp:setProperty> and
<jsp:getProperty> tags
respectively.
Defining the Scope of a JavaBean Object
Use the scope attribute to
specify the availability and life-span of the JavaBean object. The
scope can be one of the following:
- page
- This is the default scope for a JavaBean, where the object is
stored in the javax.servlet.jsp.PageContext of the current page. It
is only available from the current invocation of this JSP page. It is
not available to included JSP pages, and is discarded upon completion
of this page request.
- request
- The object is stored in the current ServletRequest, and is available to other included JSP
pages that are passed the same request object. The object is discarded
when the current request is completed.
- session
- Use the session scope to store the JavaBean object in the HTTP
session so that it can be tracked across several HTTP pages. The
reference to the JavaBean is stored in the page's HttpSession object. Your JSP pages must be able to
participate in a session to use this scope. That is, you must not have
the page directive session set to false.
- application
- At the application scope level, your JavaBean object is stored in
the ServletContext. This
implies that it is available to any other servlet or JSP page running
in the server where the object is stored. It is not available to other
servers running in a WebLogic Cluster.
For more information on using JavaBeans, see the JSP 1.1
specification.
Using Sessions with JSP
In addition to following the JSP specifications, we recommend that you consider the following points when developing your JSP for WebLogic Server.
- Objects stored in sessions should be small in size. For example, a session should not be used to store an EJB, but an EJB primary key instead. Large amounts of data should be stored in the database, with the session holding a simple string reference to the data.
- When using sessions in conjunction with dynamic reloading of
servlets or JSP, the objects stored in the servlet session should be
of simple, non-user defined types (such as String or collections of
String, not data-types contained in the servlet file). This is
because the servlet is reloaded in a new classloader, which results in
an incompatibility between any classes loaded previously (from the old
version of the servlet) and any classes loaded in the new classloader
(for the new version of the servlet classes). This incompatibility
causes the servlet to throw a ClassCastException.
- If session data must be of a user-defined type, the data class should be serializable. Furthermore, the session should store the serialized representation of the data object, and serialization should, of course, be compatible across versions of the data class.
Deploying Applets from JSP
JSP provides a convenient way to generate HTML that contains the
appropriate client browser tag to include the Java Plug-in in a Web
page. The Java Plug-In allows you to use a JRE supplied by JavaSoft
instead of the JVM implemented by the client Web browser. This
feature avoids incompatibility problems between your applets and
specific types of Web browsers. The Java Plug-in is available from Sun
at http://java.sun.com/products/plugin/.
The syntax used Internet Explorer and Netscape use is different,
but the servlet code generated from the <jsp:plugin> action dynamically senses the type
of browser client and sends the appropriate <OBJECT> or <EMBED> tags in the HTML page.
The <jsp:plugin> tag
uses many attributes similar to those of the <APPLET> tag, and some other attributes that
configure which version of the Java Plug-in to use. If the applet
communicates with the server, the JVM running your applet code must be
compatible with the JVM running WebLogic Server.
This example JSP syntax uses the plug-in action to deploy the
phonebook applet, taken from the WebLogic Server examples.
<jsp:plugin type="applet" code="examples.applets.PhoneBook1"
codebase="/classes/" height="800" width="500"
jreversion="1.1"
nspluginurl="http://java.sun.com/products/plugin/1.1.3/plugin-install.html"
iepluginurl="http://java.sun.com/products/plugin/1.1.3/\
jinstall-113-win32.cab#Version=1,1,3,0" >
<params>
<param name="weblogic_url" value="t3://localhost:7001">
<param name="poolname" value="demoPool">
</params>
<fallback>
<font color=#FF0000>Sorry, cannot run java applet!!</font>
</fallback>
</jsp:plugin>
Note: To fit this page, some of the above code is continued on an extra line. This continuation is marked with the "\" character. Do not include
the \ in your actual
code.
This JSP syntax instructs the browser to download the Java Plug-In version
1.1.3 if necessary, and run the applet given by the code attribute from the location specified by codebase.
The jreversion attribute identifies the
spec version of the Java Plug-In that the applet requires to operate. The
web-browser attempts to use this version of the Java Plug-In. If not already
installed on the browser, the nspluginurl and
iepluginurl attributes specify URLs
where the Java Plug-In can be downloaded from Sun's website. Once the plug-in
is installed on the web-browser, it need not be downloaded again.
If you are running WebLogic Server with the Java 1.2.x VM, and your
applet communicates with the server using RMI, JDBC, EJB, or JNDI, then you
must specify the Java Plug-In version 1.2.x in the <jsp:plugin> tag. You would achieve this in the above
example by replacing the corresponding attribute values with:
jreversion="1.2"
nspluginurl="http://java.sun.com/products/plugin/1.2/plugin-install.html"
iepluginurl="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab"
The other attributes of the plug-in action correspond with those of the
<APPLET> tag. You specify applet
parameters within a pair of <params> tags, nested within the
<jsp:plugin> and
</jsp:plugin> tags.
The <fallback> tags allow
you to substitute HTML for browsers that are not supported by the
<jsp:plugin> action. The HTML
nested between the <fallback>
and </fallback> tags is sent
instead of the plug-in syntax.
Using the WebLogic JSP Compiler
Because the JSPServlet automatically calls the WebLogic JSP compiler
to process your JSP pages, you generally do not need to use the
compiler directly. However, in some situations, such as debugging,
accessing the compiler directly is useful. This section is a reference
for the compiler.
The WebLogic JSP compiler parses your JSP file into a
.java file, then compiles the generated
.java file into a Java class using a
regular Java compiler.
Syntax
The JSP compiler works in much the same way that other WebLogic
compilers work (including the RMI and EJB compilers). The command line
follows this pattern:
$ java weblogic.jspc -options fileName
where fileName is the
name of the JSP file that you want to compile. The options may be before or
after the target filename. The following example compiles "myFile.jsp" into the
destination directory (one of the options) "weblogic/classes".
$ java weblogic.jspc -d /weblogic/classes myFile.jsp
Options
You can use any combination of the following options:
- -classpath
- Add a semicolon-delimited list of directories that make
up the desired CLASSPATH. For example (to be entered on one line):
$ java weblogic.jspc \
-classpath java/classes.zip;/weblogic/classes.zip \
myFile.JSP
- -commentary
- Causes the JSP compiler to emit commentary.
- -compiler
- Sets the Java
compiler used to compile the class file from the generated Java source
code. The default compiler used is javac. The Java compiler program should be in
your PATH unless you specify
the absolute path to the compiler explicitly.
- -compilerclass
- Loads compiler as a class instead of an executable.
- -contextPath
- Prepends to the simulated request URI that is munged into the classname for the generated code. The simulated URI must match the actual URI you will use at runtime.
- -d
- Sets the destination of the compiled output (the class file). Use this
as a shortcut to place the compiled classes in a directory that is already in
your CLASSPATH.
- -debug
- Compile with debugging on.
- -deprecation
- Warn about use of deprecated methods in the generated Java source file
when compiling it into a class file. This is compiler dependent. Note that the
Symantec compiler does not provide checking for deprecated methods.
- -docroot
- -docroot <directory> Directory to be considered as the document root for resolving
relative files.
- -encoding
- Valid arguments are "default" to use the default character encoding of your
JDK, or a named character encoding, like "8859_1". If the -encoding flag is not present, an array of bytes is
used.
- -g
- Instructs the Java compiler to include debugging information in the class file.
- -help
- Outputs a list of all the available flags.
- -J
- Use the -J option to add other options that your specific compiler
will parse.
- -keepgenerated
- Keeps the Java files that are created as an intermediary
step in the compilation process.
- -neverStale
- Prevents the generated JSP class from being recomplied by the WebLogic Server even if the source changes. However, if run inside
a different WebLogic release or service pack, the JSP class will be recompiled from the source to check for incompatibilities.
- -nowarn
- Turns off warning messages from the Java compiler.
- -nowrite
- Runs the compilation
process without actually producing a .class file. If you combine this with the -keepgenerated flag, the compiler creates
only the intermediate .java
file, which can be useful for debugging.
- -O
- Compiles the generated Java
source file with optimization turned on. This option overrides the
-g flag.
- -package
- Sets the package for the generated java HTTP servlet. This defaults to
"jsp_servlet".
- -superclass
- Sets the classname of the superclass that the generated servlet
extends. The names superclass must be a derivative of HTTPServlet.
- -verbose
- Prints messages to the command line window when the
flag is present. Default is off.
- -verboseJavac
- Causes the java compiler to be invoked with -verbose.
- -version
- Prints out the version of the JSP compiler.
IV. Troubleshooting
This section describes several techniques for debugging your JSP files.
Symptoms in the Browser
Debugging Information in the Browser
The most useful feature for debugging your JSP pages is output to
the browser by default. This output displays where the error occurred
in the generated HTTP servlet Java file, a description of the error,
and an approximate location of the error code in the original JSP
file. For example, a failed compilation would result in the browser
displaying the following message:
Compilation of 'C:\weblogic\myserver\classfiles\examples\jsp\_HelloWorld.java'
failed:
C:\weblogic\myserver\classfiles\examples\jsp\_HelloWorld.java:73: Undefined variable, class, or package name: foo
probably occurred due to an error in HelloWorld.jsp line 21:
foo.bar.baz();
Tue Sep 07 16:48:54 PDT 1999
|
To disable this feature, set the verbose flag to false in the JSPServlet registration in
the weblogic.properties
file. For details, see Register the
JSPServlet.
Error 404--Not Found
Check that you have typed the URL of the JSP file correctly, and
that it is relative to the document root.
Error 500--Internal Server Error
Check the WebLogic Server log file for Page compilation failed messages, and see
the relevant section in the log file symptoms section below. A
possible source of this error is that a class referenced in the page
could not be located, causing the compilation to fail.
Error 503--Service Unavailable
If you get this response it indicates that you have not set the
compileCommand property in the
weblogic.properties
file. Check the initArgs
property for the JSP compiler. If this is correct, also check that the
virtual name for the initArgs pattern matches the virtual name given
to the JSPServlet (usually
*.jsp).
If you are serving your JSPs using a Web Application, the JSP
compiler is specified in the Web Application's deployment
descriptor. For more information, see Writing
a Web Application.
JSP Page Content Appears in the Browser
If you do not register the JSP Servlet correctly in the weblogic.properties file, the
FileServlet will deliver the JSP page directly to the browser without
compiling it or executing any of its Java code. When viewed in the
Netscape browser, you will see the contents of the JSP page; when
viewed in Internet Explorer, you will see only the HTML parts of the
JSP page.
If you are serving your JSP from a Web Application, the JSPServlet
is implicitly registered for you.
Symptoms in the Log File
This section describes JSP-related error messages in the WebLogic
Server log file. As WebLogic Server runs, verbose messages are saved into a log file
named weblogic/myserver/weblogic.log that you can view using a
text editor. Errors are usually denoted by indented sections or
Exception stack traces. As a general rule, you can search for the word
error or Exception.
Errors when Invoking the JSPServlet
- Couldn't find init param: compileCommand
- You must specify the compileCommand in the
weblogic.properties file. Check that this parameter is
specified in the initArgs
property, and that the virtual name or pattern specified for the initArgs matches that of the
JSPServlet.
Errors when Page Compilation Failed
The following errors may occur if the JSP compiler fails to translate
the JSP page into a Java file, or can not compile the generated Java
file. Look in the log file for the following error messages:
- CreateProcess: ...
- This indicates that the Java compiler specified by
compileCommand
could not be found or was not a valid executable.
- Compiler failed:
- The Java code generated from your JSP page could not be compiled
by the Java compiler you specified in the weblogic.properties file with compileCommand. You can use the JSP Compiler independently to inspect and debug
the generated Java code in more detail.
- Undefined variable or
classname:
- If you are using a custom variable, make sure it
is defined before using it in a scriptlet, or
define it in a declaration. You may see this
error if attempt to use an implicit object
from a declaration. Use of implicit objects in a
declaration is not supported in JSP.
JSP Servlet Run-time Failure
You may encounter the following output if your JSP servlet is
successfully generated, compiled and invoked, but fails at run time
when serving an HTTP request.
- ClassCastException
- A ClassCastException may
be thrown if you modify your JSP page, causing it to reload when you
are storing custom classes in an HTTP session, and those classes are
loaded from the servlet classpath.
For more details on the ClassCastExceptionHTTP, and for some suggested
workarounds for this problem, see the Developers Guide, "Using WebLogic
HTTP servlets", under the section
ClassCastException and HTTP Sessions.

|