13 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 13-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 2.1 specification. See Actions.

Comments
<%/* comment */%>

Ensure that your comments are removed from the viewable source of your HTML files by using only JSP comment tags. HTML comments remain visible when the user selects view source in the browser.


Defining JSP Versions

Because JSP 2.1 imports some new features, the same syntax could hold different meanings between JSP 2.1 and JSP 2.0, so the JSP version must be defined to attain the expected behavior. For example:

  • <%@ page deferredSyntaxAllowedAsLiteral="true" %> is not allowed in JSP 2.0.

  • # {expr} is valid in JSP 2.0 template text, but is invalid in JSP 2.1 by default.

Rules for Defining a JSP File Version

Since there is no explicit method of specifying a JSP page's version, its version is eventually determined by the Web application version, as follows:

  • If <jsp:root> appears in a JSP document, its attribute version value will determine that JSP document's version; otherwise, the Web application version will determine it.

  • If the Web application version is determining the JSP version, then 2.5 indicates the version is JSP 2.1 and 2.4 means the version is JSP 2.0.

  • If a JSP document contains <jsp:root>, and if Web application version is 2.4, the <jsp:root> version must not be higher than 2.0. However, if the Web application version is 2.5, then the <jsp:root> version could be less than 2.1.

  • All Referred JSP tag versions must not be higher than current JSP file's version.

Rules for Defining a Tag File Version

All JSP tag file versions are defined by the version of the tag library they belong to.

  • Since an implicit tag library will be created for each directory, including tag files, the implicit tag library's version is 2.0 by default. However, the version can be configured by the implicit.tld file in same directory in JSP 2.1.

  • A .tagx file's <jsp:root> attribute version value must be same as the tag file's version.

  • All Referred JSP tag versions must not be higher than current tag file's version.

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 2.1 specification. The JSP API is described in the Javadocs available from the Sun Microsystems JSP Home Page at http://www.java.sun.com/products/jsp/download/index.html.

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.

Table 13-2 Reserved Words for Implicit Objects

Reserved Word Description
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

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.

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

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

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

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 2.1 specification states that if the session directive is set to false, then using the session keyword results in a fatal translation time error.

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

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

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.


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:

  • Shorthand: <%@ dir_type dir_attr %>

  • XML: <jsp:directive.dir_type dir_attr />

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

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.

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

  • You can have multiple blocks of scriptlet Java code mixed with plain HTML.

  • You can switch between HTML and Java code anywhere, even within Java constructs and blocks. In Example of a JSP with HTML and Embedded Java the example declares a Java loop, switches to HTML, and then switches back to Java to close the loop. The HTML within the loop is generated as 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. Call the print() method to add a string to the HTTP page response.

  • Any time you print data that a user has previously supplied, Oracle recommends that you remove any HTML special characters that a user might have entered. If you do not remove these characters, your Web site could be exploited by cross-site scripting. For more information, refer to JSP Expression Language.

  • The Java tag is an inline tag; it does not force a new paragraph.

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.

Expressions are often used to return data that a user has previously supplied. Any time you print user-supplied data, Oracle recommends that you remove any HTML special characters that a user might have entered. If you do not remove these characters, your Web site could be exploited by cross-site scripting. For more information, refer to JSP Expression Language.

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:

Surrounding text describes jsp_output.jpg.

Actions

You use JSP actions to modify, use, or create objects that are represented 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:

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

Table 13-3 Defining the Scope attribute of a JavaBean Object

Scope Description
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 JSP 2.1 specification at http://www.java.sun.com/products/jsp/index.html.

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>

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.

JSP Expression Language

The new JSP expression language (JSP EL 2.1) is inspired by both ECMAScript and the XPath expression languages. The JSP EL is available in attribute values for standard and custom actions and within template text. In both cases, the JSP EL is invoked consistently by way of the construct #{expr} or ${expr}.

The #{expr} syntax refers to deferred expressions introduced in JSP EL 2.1. Expressions delimited by "#{}" use "deferred evaluation" because the expression is not evaluated until its value is needed by the system, and so can be processed by the underlying mechanism at the appropriate moment within its life cycle. Whereas, expressions delimited by "${}" use "immediate evaluation" because the expression is compiled when the JSP page is compiled and it is executed when the JSP page is executed. The deferred expression includes deferred ValueExpression and deferred MethodExpression. The ${expr} syntax is supported in JSP EL 2.1.

The addition of the JSP EL to the JSP technology better facilitates the writing of scriptlets JSP pages. These pages can use JSP EL expressions but cannot use Java scriptlets, Java expressions, or Java declaration elements. You can enforce this usage pattern through the scripting-invalid JSP configuration element of the web.xml deployment descriptor.

For more information on the JSP expression language, see the http://java.sun.com/products/jsp/download/index.html.

Expressions and Attribute Values

You can use JSP EL expressions in any attribute that can accept a run-time expression, whether it is a standard action or a custom action. The following are use-cases for expressions in attribute values:

  • The attribute value contains a single expression construct of either <some:tag value="${expr}"/> or <some:tag value="#{expr}"/>. In this case, the expression is evaluated and the result is coerced to the attribute's expected type according to the type conversion rules described in section 1.18, "Type Conversion," of http://java.sun.com/products/jsp/download/index.html.

  • The attribute value contains one or more expressions separated or surrounded by text of either: <some:tag value="some${expr}${expr}text${expr}"/> or <some:tag value="some#{expr}#{expr}text#{expr}"/>. In this case, the expressions are evaluated from left to right, coerced to Strings (according to the type conversion rules described later), and concatenated with any intervening text. The resulting String is then coerced to the attribute's expected type according to the type conversion rules described in section 1.18, "Type Conversion," of http://java.sun.com/products/jsp/download/index.html.

  • The attribute value contains only text: <some:tag value="sometext"/>. In this case, the attribute's String value is coerced to the attribute's expected type according to the type conversion rules described in section 1.18, "Type Conversion," of http://java.sun.com/products/jsp/download/index.html.

    Note:

    These rules are equivalent to the JSP 2.1 conversions, except that empty strings are treated differently.

The following two conditions must be satisfied when using JSPX:

  • web.xml – The web-app must define the Servlet version attribute as 2.4 or higher; otherwise, all EL functions are ignored.

  • TLD file – Namespace declaration is required for the jsp prefix, as follows:

    <html xmlns:jsp="http://java.sun.com/JSP/Page";
    

The following shows a conditional action that uses the JSP EL to test whether a property of a bean is less than 3.

<c:if test="${bean1.a < 3}">
...
</c:if>

Note that the normal JSP coercion mechanism already allows for: <mytags:if test="true" />. There may be literal values that include the character sequence ${. If this is the case, a literal with that value can be used as shown here:

<mytags:example code="an expression is ${'${'}expr}" />

The resulting attribute value would then be the string an expression is ${expr}.

Expressions and Template Text

You can use the JSP EL directly in template text; this can be inside the body of custom or standard actions or in template text outside of any action. An exception to this use is if the body of the tag is tag dependent or if the JSP EL is turned off (usually for compatibility issues) explicitly through a directive or implicitly.

The semantics of a JSP EL expression are the same as with Java expressions: the value is computed and inserted into the current output. In cases where escaping is desired (for example, to help prevent cross-site scripting attacks), you can use the JSTL core tag <c:out>. For example:

<c:out value="${anELexpression}" />

The following shows a custom action where two JSP EL expressions are used to access bean properties:

<c:wombat>
One value is ${bean1.a} and another is ${bean2.a.c}. 
</c:wombat>

JSP Expression Language Implicit Objects

There are several implicit objects that are available to JSP EL expressions used in JSP pages. These objects are always available under these names:

  • pageContext—Represents the pageContext object.

  • pageScope—Represents a Map that maps page-scoped attribute names to their values.

  • requestScope—Represents a Map that maps request-scoped attribute names to their values.

  • sessionScope—Represents a Map that maps session-scoped attribute names to their values.

  • applicationScope—Represents a Map that maps application-scoped attribute names to their values.

  • param—Represents a Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name)).

  • paramValues—Represents a Map that maps parameter names to a single String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name)).

  • header—Represents a Map that maps header names to a single String header value (obtained by calling ServletRequest.getHeader(string name)).

  • headerValues—Represents a Map that maps header names to a String[] of all values for that header (obtained by calling ServletRequest.getHeaders(String name)).

  • cookie—Represents a Map that maps cookie names to a single Cookie object. Cookies are retrieved according to the semantics of HttpServletRequest.getCookies(). If the same name is shared by multiple cookies, an implementation must use the first one encountered in the array of Cookie objects returned by the getCookies() method. However, users of the cookie implicit objects must be aware that the ordering of cookies is currently unspecified in the servlet specification.

  • initParam—Represents a Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletRequest.getInitParameter(String name)).

Table 13-4 shows some examples of using these implicit objects:

Table 13-4 Example Uses of Implicit Objects

Expression Description
${pageContext.request.requestURI}

The request's URI (obtained from HttpServletRequest)

${sessionScope.profile}

The session-scoped attribute named profile (null if not found)

${param.productId}

The String value of the productId parameter (null if not found).

${paramValues.productId}

The String[] containing all values of the productId parameter (null if not found).


JSP Expression Language Literals and Operators

These sections discuss JSP EL expression literals and operators. The JSP EL syntax is pretty straightforward. Variables are accessed by name. A generalized [] operator can be used to access maps, lists, arrays of objects and properties of JavaBean objects; the operator can be nested arbitrarily. The . operator can be used as a convenient shorthand for property access when the property name follows the conventions of Java identifies. However the [] operator allows for more generalized access.

Relational comparisons are allowed using the standard Java relational operators. Comparisons may be made against other values, or against boolean (for equality comparisons only), String, integer, or floating point literals. Arithmetic operators can be used to compute integer and floating point values. Logical operators are available.

Literals

Literals exist for boolean, integer, floating point, string, null.

  • Boolean - true and false

  • Integer - As defined by the IntegerLiteral construct in section 1.19, "Collected Syntax," of the JSP 2.1 EL specification.

  • Floating point - As defined by the FloatingPointLiteral construct in section 1.19, "Collected Syntax," of the JSP 2.1 EL specification.

  • String -With single and double quotes - " is escaped as \", ' is escaped as \', and \ is escaped as \\. Quotes only need to be escaped in a string value enclosed in the same type of quote.

  • Null - null

Errors, Warnings, Default Values

JSP pages are mostly used in presentation, and in that usage, experience suggests that it is most important to be able to provide as good a presentation as possible, even when there are simple errors in the page. To meet this requirement, the JSP EL does not provide warnings, just default values and errors. Default values are typecorrect values that are assigned to a subexpression when there is some problem. An error is an exception thrown (to be handled by the standard JSP machinery).

Operators

The following is a list of operators provided by the JSP expression language:

  • . and []

  • Arithmetic: +, - (binary), *, / and div, % and mod, - (unary)

  • Logical: and, &&, or, ||, not, !

  • Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made against other values, or against boolean, string, integer, or floating point literals.

  • Empty: The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

  • Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of A.

For more information about the operators and their functions, see the JSP 2.1 specification.

Operator Precedence

The following is operator precedence, from highest to lowest, left-to-right.

  • [] .

  • ()

  • - (unary) not ! empty

  • * / div % mod

  • + - (binary)

  • < > <= >= lt gt le ge

  • == != eq ne

  • && and

  • || or

  • ? :

JSP Expression Language Reserved Words

The following words are reserved for the language and should not be used as identifiers.

  • and

  • eq

  • gt

  • true

  • instanceof

  • or

  • ne

  • le

  • false

  • empty

  • not

  • lt

  • ge

  • null

  • div

  • mod

    Note:

    Many of these words are not in the language now, but they may be in the future, so developers should avoid using these words now.

JSP Expression Language Named Variables

A core concept in the JSP EL is the evaluation of a variable name into an object. The JSP EL API provides a generalized mechanism, a VariableResolver, that will resolve names into objects. The default resolver is what is used in the evaluation of JSP EL expressions in template and attributes. This default resolver provides the implicit objects discussed in JSP Expression Language Implicit Objects.

The default resolver also provides a map for other identifiers by looking up its value as an attribute, according to the behavior of PageContext.findAttribute(String) on the pageContext object. For example: ${product}.

This expression looks for the attribute named product, searching the page, request, session, and application scopes, and returns its value. If the attribute is not found, null is returned. See chapter 14, "Expression Language API," of the JSP 2.1 specification. for further details on the VariableResolver and how it fits with the evaluation API.

Securing User-Supplied Data in JSPs

Expressions and scriptlets enable a JSP to receive data from a user and return the user supplied data. For example, the sample JSP in Example 13-1 prompts a user to enter a string, assigns the string to a parameter named userInput, and then uses the <%= javax.servlet.ServletRequest.getParameter("userInput")%> expression to return the data to the browser.

Example 13-1 Using Expressions to Return User-Supplied Content

<html>
  <body>
    <h1>My Sample JSP</h1>
      <form method="GET" action="mysample.jsp">
          Enter string here:
          <input type="text" name="userInput" size=50>
          <input type=submit value="Submit">
       </form>
    <br>
    <hr>
    <br>
    Output from last command: 
    <%= javax.servlet.ServletRequest.getParameter("userInput")%>
  </body>
</html>

This ability to return user-supplied data can present a security vulnerability called cross-site scripting, which can be exploited to steal a user's security authorization. For a detailed description of cross-site scripting, refer to "Understanding Malicious Content Mitigation for Web Developers" (a CERT security advisory) at http://www.cert.org/tech_tips/malicious_code_mitigation.html.

To remove the security vulnerability, before you return data that a user has supplied, scan the data for any of the HTML special characters in Table 13-5. If you find any special characters, replace them with their HTML entity or character reference. Replacing the characters prevents the browser from executing the user-supplied data as HTML.

Table 13-5 HTML Special Characters that Must Be Replaced

Replace this special character: With this entity/character reference:

<

&lt;

>

&gt;

(

&40;

)

&41;

#

&35;

&

&38;


Using a WebLogic Server Utility Method

WebLogic Server provides the weblogic.servlet.security.Utils.encodeXSS() method to replace the special characters in user-supplied data. To use this method, provide the user-supplied data as input. For example:

<%= weblogic.servlet.security.Utils.encodeXSS(
javax.servlet.ServletRequest.getParameter("userInput"))%>

To secure an entire application, you must use the encodeXSS() method each time you return user-supplied data. While the previous example is an obvious location in which to use the encodeXSS() method, Table 13-5 describes other locations to consider using the encodeXSS() method.

Table 13-6 Code that Returns User-Supplied Data

Page Type User-Supplied Data Example

Error page

Erroneous input string, invalid URL, user name

An error page that says "user name is not permitted access."

Status page

User Name, summary of input from previous pages

A summary page that asks a user to confirm input from previous pages.

Database display

Data presented from a database

A page that displays a list of database entries that have been previously entered by a user.


Using Sessions with JSP

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

  • Store small objects in sessions. For example, a session should not be used to store an EJB, but an EJB primary key instead. Store large amounts of data in a database. The session should hold only a simple string reference to the data.

  • When you use sessions with dynamic reloading of servlets or JSPs, the objects stored in the servlet session must be serializable. Serialization is required because the servlet is reloaded in a new class loader, which results in an incompatibility between any classes loaded previously (from the old version of the servlet) and any classes loaded in the new class loader (for the new version of the servlet classes). This incompatibility causes the servlet to return ClassCastException errors.

  • 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. Serialization should be compatible across versions of the data class.

Deploying Applets from JSP

Using the JSP provides a convenient way to include the Java Plug-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="2.0" 
 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

Note:

The WebLogic JSP compiler is deprecated. Oracle recommends that you use the WebLogic appc compiler, weblogic.appc, to compile EAR files, WAR files and EJBs. See "appc Reference" in Programming WebLogic Enterprise JavaBeans for Oracle WebLogic Server.

For better compilation performance, the WebLogic JSP compiler transforms a JSP directly into a class file on the disk instead of first creating a java file on the disk and then compiling it into a class file. The java file only resides in memory.

To see the generated java file, turn on the -keepgenerated flag which dumps the in-memory java file to the disk.

Note:

During JSP compilation, neither the command line flag (compilerclass) nor the descriptor element is invoked.

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

Use any combination of the following options:

Table 13-7 JSP Compiler Options

Option Description
-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.

-compressHtmlTemplate

Compress the HTML in the JSP template blocks to improve run-time performance.

If the JSP's HTML template block contains the <pre> tag, do not enable this option.

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

-optimizeJavaExpression

Optimize Java expressions to improve run-time performance.

-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. To avoid recompiling your JSPs each time the server restarts and when you target additional servers, precompile them using weblogic.jspc and place them in the WEB-INF/classes folder and archive them in a .war file. Keeping your source files in a separate directory from the archived .war file will eliminate the possibility of errors caused by a JSP having a dependency on one of the class files.

Using the JSPClassServlet

Another way to prevent your JSPs from recompiling is to use the JSPClassServlet in place of JSPServlet and to place your precompiled JSPs into the WEB-INF/classes directory. This will remove any possibility of the JSPs being recompiled, as the server will not look at the source code. The server will not note any changes to the JSPs and recompile them if you choose this option. This option allows you to completely remove the JSP source code from your application after precompiling.

This is an example of how to add the JSPClassServlet to your Web application's web.xml file.

<servlet>
    <servlet-name>JSPClassServlet</servlet-name>
    <servlet-class>weblogic.servlet.JSPClassServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>JSPClassServlet</servlet-name>
    <url-pattern>*.jsp</url-pattern>
  </servlet-mapping>

As when using virtual hosting, you must have physical directories that correspond to the mappings you create to allow your files to be found by the server.