bea.com | products | dev2dev | support | askBEA
 Download Docs   Site Map   Glossary 
Search

Programming WebLogic JSP

 Previous Next Contents Index View as PDF  

WebLogic JSP Reference

The following sections provide reference information for writing JavaServer Pages (JSPs):

 


JSP Tags

The following table describes the basic tags that you can use in a JSP page. Each shorthand tag has an XML equivalent.

Table 3-1 Basic Tags for JSP Pages

JSP Tag

Syntax

Description

Scriptlet

<% java_code %>

. . . or use the XML equivalent:

<jsp:scriptlet>
java_code
</jsp:scriptlet>

Embeds Java source code scriptlet in your HTML page. The Java code is executed and its output is inserted in sequence with the rest of the HTML in the page. For details, see Scriptlets.

Directive

<%@ dir-type dir-attr %>

. . . or use the XML equivalent:

<jsp:directive.dir_type dir_attr />

Directives contain messages to the application server.

A directive can also contain name/value pair attributes in the form attr="value", which provides additional instructions to the application server. See Directives for WebLogic JSP.

Declarations

<%! declaration %>

. . . or use XML equivalent...

<jsp:declaration>
declaration;
</jsp:declaration>

Declares a variable or method that can 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 the bean is instantiated here

</jsp:useBean>
<jsp:setProperty ... >
<jsp:getProperty ... >
<jsp:include ... >
<jsp:forward ... >
<jsp:plugin ... >

Provide access to advanced features of JSP, and only use XML syntax. These actions are supported as defined in the JSP 1.1 specification. See Actions.

 


Reserved Words for Implicit Objects

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 from the Sun Microsystems JSP Home Page.

Note: Use these implicit objects only within Scriptlets or Expressions. Using these keywords from a method defined in a declaration causes a translation-time compilation error because such usage causes your page to reference 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. Examples of these responses include cookies and other header information.

Warning: You cannot use the response.getWriter() method from within a JSP page; if you do, a run-time exception is thrown. Use the out keyword to send the JSP response back to the browser from within your scriptlet code whenever possible. The WebLogic Server implementation of javax.servlet.jsp.JspWriter uses javax.servlet.ServletOutputStream, which implies that you can use response.getServletOutputStream(). Keep in mind, however, that this implementation is specific to WebLogic Server. To keep your code maintainable and portable, use the out keyword.

out

out is an instance of javax.jsp.JspWriter that has several methods you can use to send output back to the browser.

If you are using a method that requires an output stream, then JspWriter does not work. You can work around this limitation by supplying a buffered stream and then writing this stream to out. For example, the following code shows 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 using the session keyword results in a fatal translation time error. For more information about using sessions with servlets, see Programming WebLogic HTTP Servlets.

application

application represents a javax.servlet.ServletContext object. Use it to find information about the servlet engine and the servlet environment.

When forwarding or including requests, you can access the servlet requestDispatcher using the ServletContext, or you can use the JSP forward directive for forwarding requests to other servlets, and the JSP include directive for including output from other servlets.

config

config represents a javax.servlet.ServletConfig object and provides access to the servlet instance initialization parameters.

page

page represents the servlet instance generated from this JSP page. It is synonymous with the Java keyword this when used in 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. For convenience, we recommend that you use the Java keyword this to reference the servlet instance and get access to initialization parameters, instead of using page.

For more information on the underlying HTTP servlet framework, see the related developers guide, Programming WebLogic HTTP Servlets.

 


Directives for WebLogic JSP

Use directives to instruct WebLogic JSP to perform certain functions or interpret the JSP page in a particular way. You can insert a directive anywhere in a JSP page. The position is generally irrelevant (except for the include directive), and you can use multiple directive tags. A directive consists of a directive type and one or more attributes of that type.

You can use either of two types of syntax: shorthand or XML:

Replace dir_type with the directive type, and dir_attr with a list of one or more directive attributes for that directive type.

There are three types of directives page, taglib, or include.

Using the page Directive to Set 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" %>

Replace the custom-encoding with a standard HTTP-style character set name .

The character set you specify with a contentType directive specifies the character set used in the JSP as well as any JSP included in that JSP.

You can specify a default character encoding by specifying it in the WebLogic-specific deployment descriptor for your Web Application. For more information, see the jsp-descriptor section.

Using the taglib Directive

Use a taglib directive to declare that your JSP page uses custom JSP tag extensions that are defined in a tag library. For details about writing and using custom JSP tags, see "Programming WebLogic JSP Extensions".

 


Declarations

Use declarations to define variables and methods at the class-scope level of the generated JSP servlet. Declarations made between JSP 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 being executed in the same instance of a servlet. To guard against sharing violations, 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" %>

By default, this attribute is set to true. When set to false, the generated servlet implements the javax.servlet.SingleThreadModel interface, which prevents multiple threads from running in the same servlet instance. Setting isThreadSafe to false consumes additional memory and can cause performance to degrade.

 


Scriptlets

JSP scriptlets make up the Java body of your JSP servlet's HTTP response. To include a scriptlet in your JSP page, use 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 the following features of scriptlets:

 


Expressions

To include an expression in your JSP file, use the following tag:

<%= expr %>

Replace expr with a Java expression. When the expression is evaluated, its string representation is placed inline in the HTML response page. It is shorthand for

   <% out.print( expr ); %>

This technique enables you to make your HTML more readable in the JSP page. Note the use of the expression tag in the example in the next section.

 


Example of a JSP with HTML and Embedded Java

The following example shows a JSP 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>

After the code shown here is compiled, the resulting page is displayed in a browser as follows:

 


Actions

You use JSP actions to modify, use, or create objects that are reperesented by JavaBeans. Actions use XML syntax exclusively.

Using JavaBeans in JSP

The <jsp:useBean> action tag allows you to instantiate Java objects that comply with the JavaBean specification, and to refer to them from your JSP pages.

To comply with the JavaBean specification, objects need:

Instantiating the JavaBean Object

The <jsp:useBean> tag attempts to retrieve an existing named Java object from a specific scope and, if the existing object is 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 following tag attempts to retrieve a Java object of type examples.jsp.ShoppingCart from the HTTP session under the name cart.

<jsp:useBean id="cart"
class="examples.jsp.ShoppingCart" scope="session"/>

If such an object does not currently exist, the JSP attempts to create a new object, and stores it in the HTTP session under the name cart. The class should be available in the CLASSPATH used to start WebLogic Server, or in the WEB-INF/classes directory of the Web Application containing the JSP.

It is good practice to use an errorPage directive with the <jsp:useBean> tag because there are run-time exceptions that must be caught. If you do not use an errorPage directive, the class referenced in the JavaBean cannot be created, an InstantiationException is thrown, and an error message is returned to the browser.

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 exist 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 named JavaBean already exists in the specified scope. This format allows you to set up certain properties when the object is first created. For example:

<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, which stores the object in the javax.servlet.jsp.PageContext of the current page. It is available only from the current invocation of this JSP page. It is not available to included JSP pages, and it is discarded upon completion of this page request.

request

When the request scope is used, the object is stored in the current ServletRequest, and it 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 Web Application. Use of this scope implies that the object is available to any other servlet or JSP page running in the same Web Application in which the object is stored.

For more information about using JavaBeans, see the SP 1.1 specification .

Forwarding Requests

If you are using any type of authentication, a forwarded request made with the <jsp:forward> tag, by default, does not require the user to be re-authenticated. You can change this behavior to require authentication of a forwarded request by adding the <check-auth-on-forward/> element to the <container-descriptor> element of the WebLogic-specific deployment descriptor, weblogic.xml. For example:

<container-descriptor>
    <check-auth-on-forward/>
</container-descriptor>

For information on editing the WebLogic-specific deployment descriptor, see Writing the WebLogic-Specific Deployment Descriptor.

Including Requests

You can use the <jsp:include> tag to include another resource in a JSP. This tag takes two attributes:

page

Use the page attribute to specify the included resource. For example:

<jsp:include page="somePage.jsp"/>

flush

Setting this boolean attribute to true buffers the page output and then flushes the buffer before including the resource.

Setting flush="false" can be useful when the <jsp:include> tag is located within another tag on the JSP page and you want the included resource to be processed by the tag.

 


Using Sessions with JSP

Sessions in WebLogic JSP perform according to the JSP 1.1 specification. The following suggestions pertain to using sessions:

 


Deploying Applets from JSP

Using the JSP provides a convenient way to include the Java Plug-in in a Web page, by generating HTML that contains the appropriate client browser tag. The Java Plug-in allows you to use a Java Runtime Environment (JRE) supplied by Sun Microsystems 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/.

Because the syntax used by Internet Explorer and Netscape is different, 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 allow you to configure the version of the Java Plug-in to be used. If the applet communicates with the server, the JVM running your applet code must be compatible with the JVM running WebLogic Server.

In the following example, the plug-in action is used to deploy an applet:

<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" >
<jsp:params>
  <param name="weblogic_url" value="t3://localhost:7001">
  <param name="poolname" value="demoPool">
</jsp:params>
<jsp:fallback>
  <font color=#FF0000>Sorry, cannot run java applet!!</font>
</jsp:fallback>
</jsp:plugin>

The sample JSP syntax shown here instructs the browser to download the Java Plug-in version 1.3.1 (if it has not been downloaded previously), and run the applet identified 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 the plug-in is not already installed on the browser, the nspluginurl and iepluginurl attributes specify URLs where the Java Plug-in can be downloaded from the Sun Web site. Once the plug-in is installed on the Web browser, it is not downloaded again.

Because WebLogic Server uses the Java 1.3.x VM, you must specify the Java Plug-in version 1.3.x in the <jsp:plugin> tag. To specify the 1.3 JVM in the previous example code, replace the corresponding attribute values with the following:

jreversion="1.3"
nspluginurl=
"http://java.sun.com/products/plugin/1.3/plugin-install.html"
iepluginurl=
"http://java.sun.com/products/plugin/1.3/jinstall-131-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 <jsp: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 </jsp:fallback> tags is sent instead of the plug-in syntax.

 


Using the WebLogic JSP Compiler

Because the JSP Servlet 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 when you are 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, and then compiles the generated .java file into a Java class, using a standard Java compiler.

JSP Compiler Syntax

The JSP compiler works in much the same way that other WebLogic compilers work (including the RMI and EJB compilers). To start the JSP compiler, enter the following command.

$ java weblogic.jspc -options fileName

Replace fileName with the name of the JSP file that you want to compile. You can specify any options before or after the target fileName. The following example uses the -d option to compile myFile.jsp into the destination directory, weblogic/classes:

$ java weblogic.jspc -d /weblogic/classes myFile.jsp

Note: If you are precompiling JSPs that are part of a Web Application and that reference resources in the Web Application (such as a JSP tag library), you must use the -webapp flag to specify the location of the Web Application. The -webapp flag is described in the following listing of JSP compiler options.

JSP Compiler Options

You can use any combination of the following options:

-classpath

Add a list (separated by semi-colons on Windows NT/2000 platforms or colons on UNIX platforms) of directories that make up the desired CLASSPATH. Include directories containing any classes required by the JSP. For example (to be entered on one line):

$ java weblogic.jspc
   -classpath java/classes.zip;/weblogic/classes.zip
   myFile.JSP

-charsetMap

Specifies mapping of IANA or unofficial charset names used in JSP contentType directives to java charset names. For example:

-charsetMap x-sjis=Shift_JIS,x-big5=Big5

The most common mappings are built into the JSP compiler. Use this option only if a desired charset mapping is not recognized.

-commentary

Causes the JSP compiler to include comments from the JSP in the generated HTML page. If this option is omitted, comments do not appear in the generated HTML page.

-compileAll

Recursively compiles all JSPs in the current directory, or in the directory specified with the -webapp flag. (See the listing for -webapp in this list of options.). JSPs in subdirectories are also compiled.

-compileFlags

Passes one or more command-line flags to the compiler. Enclose multiple flags in quotes, separated by a space. For example:

java weblogic.jspc -compileFlags "-g -v" myFile.jsp

-compiler

Specifies the Java compiler to be 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

Runs a Java compiler as a Java class and not as a native executable.

-d <dir>

Specifies the destination of the compiled output (that is, the class file). Use this option as a shortcut for placing the compiled classes in a directory that is already in your CLASSPATH.

-depend

If a previously generated class file for a JSP has a more recent date stamp than the JSP source file, the JSP is not recompiled.

-debug

Compile with debugging on.

-deprecation

Warn about the use of deprecated methods in the generated Java source file when compiling the source file into a class file.

-docroot directory

See -webapp.

-encoding default|named character encoding

Valid arguments include (a) default which specifices using the default character encoding of your JDK, (b) a named character encoding, such as 8859_1. If the -encoding flag is not specified, an array of bytes is used.

-g

Instructs the Java compiler to include debugging information in the class file.

-help

Displays a list of all the available flags for the JSP compiler.

-J

Takes a list of options that are passed to your compiler.

-k

When compiling multiple JSPs with with a single command, the compiler continues compiling even if one or more of the JSPs failed to compile.

-keepgenerated

Keeps the Java source code files that are created as an intermediary step in the compilation process. Normally these files are deleted after compilation.

-noTryBlocks

If a JSP file has numerous or deeply nested custom JSP tags and you receive a java.lang.VerifyError exception when compiling, use this flag to allow the JSPs to compile correctly.

-nowarn

Turns off warning messages from the Java compiler.

-noprintnulls

Shows "null" in jsp expressions as "".

-O

Compiles the generated Java source file with optimization turned on. This option overrides the -g flag.

-package packageName

Sets the package name that is prepended to the package name of the generated Java HTTP servlet. Defaults to jsp_servlet.

-superclass classname

Sets the classname of the superclass extended by the generated servlet. The named superclass must be a derivative of HttpServlet or GenericServlet.

-verbose

Passes the verbose flag to the Java compiler specified with the compiler flag. See the compiler documentation for more information. The default is off.

-verboseJavac

Prints messages generated by the designated JSP compiler.

-version

Prints the version of the JSP compiler.

-webapp directory

Name of a directory containing a Web Application in exploded directory format. If your JSP contains references to resources in a Web Application such as a JSP tag library or other Java classes, the JSP compiler will look for those resources in this directory. If you omit this flag when compiling a JSP that requires resources from a Web Application, the compilation will fail.

Precompiling JSPs

You can configure WebLogic Server to precompile your JSPs when a Web Application is deployed or re-deployed or when WebLogic Server starts up by setting the precompile parameter to true in the <jsp-descriptor> element of the weblogic.xml deployment descriptor:

For more information on the web.xml deployment descriptor, see Assembling and Configuring Web Applications.

Java Server Pages that are contained within a .war file can be precompiled using appc rather than weblogic.jspc. For additional information on using appc, see appc at

 

Back to Top Previous Next