Friday, January 2, 2009

JavaServer Pages (JSP ) v2.0 Syntax Reference

CONTENTS

Core Syntax

Description

Comment

Documents the JSP page but is not inserted into the response.

Declaration

Declares a variable or method valid in the scripting language used in the page.

Expression

Contains an expression valid in the scripting language used in the page.

Scriptlet

Contains a code fragment valid in the scripting language used in the page.

EL Expression

Contains an expression in the JSP Expression Language (EL). See Expression Language section below for the syntax.

Directives

Description

Attribute Directive

Declares an attribute of the custom tag defined in the tag file.

Include Directive

Includes a resource of text or code when the JSP page is translated.

Page Directive

Defines attributes that apply to an entire JSP page.

Tag Directive

Similar to the page directive in a JSP page, but applies to tag files instead of JSP pages.

Taglib Directive

Defines a tag library and prefix for the custom tags used in the JSP page.

Variable Directive

Defines an expression language variable exposed by the tag to the calling page.

Standard Actions

Description

Used as a substitute for attributes of standard or custom actions.

Explicitly defines an element body. This tag is required if the enclosing element contains any jsp:attribute tags.

Dynamically generates an XML element

Evaluates the body of the tag used by the calling page to invoke this tag file.

Forwards a request to an HTML file, JSP page, or servlet.

Inserts the value of a bean property into the response.

Includes a static resource or the result from another web component

Evaluates a fragment attribute.

Specifies the XML declaration or the document type declaration in the request output of a JSP document or a tag file that is in XML syntax.

Causes the execution of an applet or bean. The applet or bean executes in the specified plugin. If the plugin is not available, the client displays a dialog to initiate the download of the plugin software.

Defines standard elements and namespace attributes of tag libraries.

Sets a bean property value or values.

Encloses template data.

Instantiates or references a bean with a specific name and scope.

Preface

All tags are case sensitive. A pair of single quotes is equivalent to a pair of double quotes. Spaces are not allowed between an equals sign and an attribute value.

The elements in a JSP page can be expressed in JSP syntax or XML syntax. The following rules apply:

  • JSP and XML syntax cannot be mixed within a page.
  • A page in one syntax can include or forward to a page in the other syntax.

Quoting Conventions

The following outlines quoting conventions for JSP pages expressed in JSP syntax.

Scripting Elements

  • %> by %\>

EL Expressions

  • a literal ${ by '${'

Template Text

  • <% by <\%
  • Only when the EL is enabled for a page, a literal $ by \$. This is used for quoting EL expressions.

Attributes

  • ' as \'. This is required within a single quote-delimited attribute value.
  • " as \". This is required within a double quote-delimited attribute value.
  • \ as \\
  • %> as %\>
  • <% as <\%
  • ' and " can be used to indicate single and double quotes.

Typographic Conventions

code = fixed

bold = default

italics = user-defined

| = or

[ ] = optional

{ } = required choice

... = list of items

+ = can repeat

' ' = literal

() = grouped together

^ = anything other than

- = a range

Notes

Some action elements have attributes whose value can be computed at request time. In JSP syntax, the format of such a value is the same as a JSP expression: <%= expression %>. In XML syntax, the format of the value is %= expression %. When using the JSP expression language (EL), the format of the value in either syntax is ${ expression }.

EL expressions can be quoted by adding a backslash to the front of the expression when the expression language is enabled. This prevents the expression from being evaluated. Example: \${x+y} will display as ${x+y}.

All elements in XML syntax can contain an xmlns attribute that complies with the XML namespaces spec. This attribute is used to declare tag libraries and other namespaces. Within the start tag of an element, its syntax is [xmlns:taglibprefix="URI"]+.

All JSP standard actions and custom actions can contain a jsp:attribute standard element as a substitute for any of its attributes. The jsp:attribute syntax is attributeName" [ trim="true | false" ] />

If an action contains any jsp:attribute elements and the action also has a body, it must use the jsp:body tag to represent the body. The jsp:body syntax is any elements or text


Comment

Documents the JSP page but is not inserted into the response.

JSP Syntax

<%-- comment --%>

XML Syntax

Example

<%@ page language="java" %>             
     
A Comment Test       
    

A Test of Comments

<%-- This comment will not be included in the response --%>  
   

Description

A comment marks text or lines that the JSP container should ignore. A comment is useful when you want to comment out part of your JSP page. The JSP container does not process anything within the <%-- and --%> characters or within the characters. A comment is not inserted into the response.


Declaration

Declares a variable or method valid in the scripting language used in the JSP page.

JSP Syntax

<%! declaration; [ declaration; ]+ ... %>

OR

     
   code fragment [ declaration; ]+ ...         

XML Syntax

     
   code fragment [ declaration; ]+ ...         

Examples

<%! int i = 0; %>    
<%! int a, b, c; %>  
<%! Circle a = new Circle(2.0); %>

Description

A declaration declares one or more variables or methods that you can use in Java code later in the JSP page. You must declare the variable or method before you use it in the JSP page.

You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language.

When you write a declaration in a JSP page, remember these rules:

  • You must end the declaration with a semicolon (the same rule as for a Scriptlet, but the opposite of an Expression).
  • You can already use variables or methods that are declared in packages imported by the page directive, without declaring them in a declaration element.

A declaration has translation unit scope, so it is valid in the JSP page and any of its static include files. A static include file becomes part of the source of the JSP page and is any file included with an include directive or a static resource included with a element. The scope of a declaration does not include dynamic resources included with .

See Also


Expression

Contains an expression valid in the scripting language used in the JSP page.

JSP Syntax

<%= expression %>

OR

     
   expression

XML Syntax

     
   expression            

Examples

The map file has <%= map.size() %> entries.
 
Good guess, but nope. Try        
numguess.getHint().

Description

An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted into the response where the expression appears in the JSP page. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP page.

The expression element can contain any expression that is a valid page scripting language. When the Java programming language is the scripting language you do not use a semicolon to end the expression. However, the same expression within a scriptlet requires the semicolon; see Scriptlet).

You can sometimes use expressions as attribute values in JSP elements (see the JavaServer Pages Syntax Card). An expression can be complex and composed of more than one part or expression. The parts of an expression are evaluated in left-to-right order.

See Also


Scriptlet

Contains a code fragment valid in the page scripting language.

JSP Syntax

<% code fragment %>

OR

         
   code fragment       

XML Syntax

         
   code fragment       

Examples

<%          
   String name = null;               
   if (request.getParameter("name") == null) {          
%>          
               
<%@ include file="error.html" %>           
               
<%          
   } else {  
   foo.setName(request.getParameter("name"));       
   if (foo.getName().equalsIgnoreCase("integra"))     
      name = "acura"; 
   if (name.equalsIgnoreCase( "acura" )) { 
%>

Description

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.

Within a scriptlet, you can do any of the following:

  • Declare variables or methods to use later in the JSP page (see also Declaration).
  • Write expressions valid in the page scripting language (see also Expression).
  • Use any of the implicit objects or any object declared with a element.
  • Write any other statement valid in the scripting language used in the JSP page.

Any text, HTML tags, or JSP elements you write must be outside the scriptlet.

Scriptlets are executed at request time, when the JSP container processes the request. If the scriptlet produces output, the output is stored in the out object.

See Also


EL Expression

Contains an expression in the JSP Expression Language (EL). It allows easy access to application data stored in JavaBeans components.

Syntax (JSP and XML)

${Expression}
Expression = {(ChoiceExpression | (Expression BinaryOp Expression)        
            (UnaryOp Expression) | Value }
ChoiceExpression = Expression ? Expression : Expression
BinaryOp (JSP syntax) = and | && | or | || | '+' | '-' | * | / | did                
                        | % | mod | > | gt | < | lt | >= | ge | <= |      
                        le | == | eq | != | ne
BinaryOp (XML syntax) = and | && | or | || | '+' | '-' | * | / | div              
                        | % | mod | gt |  lt | ge |  le | == | eq | ne
UnaryOp = {'-' | ! | not | empty }
Value = {ValuePrefix | (Value ValueSuffix) }
ValuePrefix = {Literal | '('Expression')' | ImplicitObject |            
            Java language identifier | FuncInvocation }
ValueSuffix = { . Identifier | '['Expression']'}
FuncInvocation = [Identifier :]Identifier '('[Expression [','          
                  Expression]+ ]')'
Literal = {true|false} | (0-9)+ | FloatingPtLiteral | StringLiteral  
            | null
FloatingPtLiteral = [0-9]+ . (0-9)+ [Exponent] | (0-9)+ [Exponent]
Exponent = {e | E} ['+' | -] (0-9)+
StringLiteral = {'[^(' | \) | \' | \\]+' | "[^(" | \) | \" | \\]+"}

Examples

The following three examples show tag attributes using EL expressions to access values stored in JavaBeans components. TABLE 1 shows how some example EL expressions evaluate.

        
            
${x+y}
 

Expression language examples

TABLE 1

EL Expression

Result

${1 > (4/2)}

false

${4.0 >= 3}

true

${100.0 == 100}

true

${(10*10) ne 100}

false

${'a' < 'b'}

true

${'hip' gt 'hit'}

false

${4 > 3}

true

${1.2E4 + 1.4}

12001.4

${3 div 4}

0.75

${10 mod 4}

2

${!empty param.Add}

True if the request parameter named Add is null or an empty string

${pageContext.request.contextPath}

The context path

${sessionScope.cart.numberOfItems}

The value of the numberOfItems property of the session-scoped attribute named cart

${param['mycom.productId']}

The value of the request parameter named mycom.productId

${header["host"]}

The host

${departments[deptName]}

The value of the entry named deptName in the departments map

${requestScope['javax.servlet.forward.servlet_path']}

The value of the request-scoped attribute named javax.servlet.forwardservlet_path

 
 

 
 
 

Description

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.

The test attribute of the following conditional tag is supplied with an EL expression that compares the number of items in the session-scoped bean named cart with 0:

 0}"> 
  ...
 

The JSP expression evaluator is responsible for handling EL expressions, which are enclosed by the ${ } characters and can include literals. Here's an example:

  ...
 

Any value that does not begin with ${ is treated as a literal and is parsed to the expected type using the PropertyEditor for the type:

...
 

Literal values that contain the ${ characters must be escaped as follows:

 

EL expressions can be used:

  • In static text
  • In any standard or custom tag attribute that can accept an expression

The value of an expression in static text is computed and inserted into the current output. If the static text appears in a tag body, note that an expression will not be evaluated if the body is declared to be tagdependent.

There are three ways to set a tag attribute value:

  • With a single expression construct: The expression is evaluated and the result is coerced to the attribute's expected type.
  • With one or more expressions separated or surrounded by text: The expressions are evaluated from left to right. Each expression is coerced to a String and then concatenated with any intervening text. The resulting String is then coerced to the attribute's expected type.
  • With text only: In this case, the attribute's String value is coerced to the attribute's expected type.

Expressions used to set attribute values are evaluated in the context of an expected type. If the result of the expression evaluation does not match the expected type exactly, a type conversion will be performed. For example, the expression ${1.2E4} provided as the value of an attribute of type float will result in the following conversion:

Float.valueOf("1.2E4").floatValue() 

See section JSP2.8 of the JSP 2.0 specification for the complete type conversion rules.

Variables

The Web container evaluates a variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String). For example, when evaluating the expression ${product}, the container will look for product in the page, request, session, and application scopes and will return its value. If product is not found, null is returned. A variable that matches one of the implicit objects described in Implicit Objects will return that implicit object instead of the variable's value.

Properties of variables are accessed using the . operator and can be nested arbitrarily.

The JSP expression language unifies the treatment of the . and [] operators. expr-a.identifier-b is equivalent to expr-a["identifier-b"]; that is, the identifier identifier-b is used to construct a literal whose value is the identifier, and then the []operator is used with that value.

To evaluate expr-a[expr-b], evaluate expr-a into value-a and evaluate expr-b into value-b. If either value-a or value-b is null, return null.

  • If value-a is a Map, return value-a.get(value-b). If !value-a.containsKey(value-b), then return null.
  • If value-a is a List or array, coerce value-b to int and return value-a.get(value-b) or Array.get(value-a, value-b), as appropriate. If the coercion couldn't be performed, an error is returned. If the call returns an IndexOutOfBoundsException, null is returned. If the call returns another exception, an error is returned.
  • If value-a is a JavaBeans object, coerce value-b to String. If value-b is a readable property of value-a, then return the result of a get call. If the get method throws an exception, an error is returned.
Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page's servlet and any Web components contained in the same application.
    • session: The session object for the client.
    • request: The request triggering the execution of the JSP page.
    • response: The response returned by the JSP page.

In addition, several implicit objects are available that allow easy access to the following objects:

  • param: Maps a request parameter name to a single value
  • paramValues: Maps a request parameter name to an array of values
  • header: Maps a request header name to a single value
  • headerValues: Maps a request header name to an array of values
  • cookie: Maps a cookie name to a single cookie
  • initParam: Maps a context initialization parameter name to a single value

Finally, there are objects that allow access to the various scoped variables.

  • pageScope: Maps page-scoped variable names to their values
  • requestScope: Maps request-scoped variable names to their values
  • sessionScope: Maps session-scoped variable names to their values
  • applicationScope: Maps application-scoped variable names to their values

When an expression references one of these objects by name, the appropriate object is returned instead of the corresponding attribute. For example, ${pageContext} returns the PageContext object, even if there is an existing pageContext attribute containing some other value.

Literals

The JSP expression language defines the following literals:

  • Boolean: true and false
  • Integer: as in the Java programming language
  • Floating point: as in the Java programming language
  • String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
  • Null: null
Operators

In addition to the . and [] operators discussed in Variables, the JSP expression language provides the following operators:

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

The precedence of operators highest to lowest, left to right is as follows:

  • [] .
  • () - Used to change the precedence of operators.
  • - (unary) not ! empty
  • * / div % mod
  • + - (binary)
  • < > <= >= lt gt le ge
  • == != eq ne
  • && and
  • || or
  • ? :
Reserved Words

The following words are reserved for the JSP expression 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 that many of these words are not in the language now, but they may be in the future, so you should avoid using them.

Functions

The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags.

Functions can appear in static text and tag attribute values.

To use a function in a JSP page, you use a taglib directive to import the tag library containing the function. Then you preface the function invocation with the prefix declared in the directive.

For example, the following example page imports the /functions library and invokes the function equals in an expression:

<%@ taglib prefix="f" uri="/functions"%>
...
    
      test="${f:equals(selectedLocaleString,
        localeString)}" > 

To define a function you program it as a public static method in a public class. The mypkg.MyLocales class example below defines a function that tests the equality of two Strings as follows:

package mypkg;
public class MyLocales {
  ...
  public static boolean equals( String l1, String l2 ) {
    return l1.equals(l2);
  }
} 

Then you map the function name as used in the EL expression to the defining class and function signature in a TLD. The following functions.tld file maps the equals function to the class containing the implementation of the function equals and the signature of the function:

  equals
  mypkg.MyLocales
  boolean equals( java.lang.String,
    java.lang.String )
 

A tag library can have only one function element that has any given name element.

See Also


Attribute Directive

Declares attributes of custom actions defined in tag files. Used in tag files only.

JSP Syntax

<%@ attribute   name="attribute-name"
   [ required="true | false" ]
   [ fragment="true | false" ]
   [ rtexprvalue="true | false" ]
   [ type="java.lang.String | a non-primitive type"]
   [ description="text" ]
%>

OR

where attributeDirectiveAttrList is the same as the list for JSP syntax

XML Syntax

where attributeDirectiveAttrList is the same as the list for JSP syntax

Examples

The Duke's Bookstore example includes a custom tag, called shipDate, that is defined in a tag file, shipDate.tag. The tag file includes an attribute directive that declares the shipDate tag's attribute, shipping:

<%@ attribute name="shipping" required="true" %>

Here is an example of the shipDate tag used in the bookreceipt.jsp page:

 

Description

The attribute directive allows the declaration of attributes for custom tags in tag files. This is analogous to the attribute element of a TLD file.

Attributes

  • name = "attribute-name"

The unique name of the attribute being declared. A translation error results if more than one attribute directive appears in the same translation unit with the same name. A translation error results if there is an attribute directive with a name attribute equal to the value of the name-given attribute of a variable directive or the dynamic-attributes attribute of a tag directive in this translation unit.

  • required="true | false"

Whether this attribute is required (true) or optional (false). Defaults to false if not specified.

  • fragment="true | false"

Whether this attribute is a fragment to be evaluated by the tag handler (true) or a normal attribute to be evaluated by the container prior to being passed to the tag handler. If this attribute is true:

    • You do not specify the rtexprvalue attribute. The container fixes the rtexprvalue attribute at true.
    • You do not specify the type attribute. The container fixes the type attribute at javax.servlet.jsp.tagext.JspFragment.

Defaults to false.

  • rtexprvalue="true | false"

Whether the attribute's value may be dynamically calculated at runtime by a scriptlet expression. Unlike the corresponding TLD element, this attribute defaults to true.

  • type="java.lang.String | a non-primitive type"

The runtime type of the attribute's value. Defaults to java.lang.String if not specified. It is a translation error to specify a primitive type.

  • description="text"

Description of the attribute. Defaults to no description.


Include Directive

Includes a static file in a JSP page, parsing the file's JSP elements.

JSP Syntax

<%@ include file="relativeURL" %>

OR

relativeURL" />

XML Syntax

relativeURL" />

Examples

include.jsp:
     
An Include Test         
          
  
The current date and time are   
<%@ include file="date.jsp" %>              
    
   
date.jsp:
<%@ page import="java.util.*" %>         
<%= (new java.util.Date() ).toLocaleString() %>
Displays in the page:
The current date and time are   
Aug 30, 1999 2:38:40

Description

An include directive inserts a file of text or code in a JSP page at translation time, when the JSP page is compiled. When you use the include directive, the include process is static. A static include means that the text of the included file is added to the JSP page. The included file can be a JSP page, HTML file, XML document, or text file. If the included file is a JSP page, its JSP elements are translated and included (along with any other text) in the JSP page. Once the included file is translated and included, the translation process resumes with the next line of the including JSP page.

The included file can be an HTML file, a JSP page, a text file, XML document, or a code file written in the Java programming language. Be careful that the included file does not contain , , , or tags. Because the entire content of the included file is added to the including JSP page, these tags would conflict with the same tags in the including JSP page, causing an error.

Some of the behaviors of the include directive depend on the particular JSP container you are using, for example:

  • The included file might be open and available to all requests, or it might have security restrictions.
  • The JSP page might be recompiled if the included file changes.

Attributes

  • file="relativeURL"

The pathname to the included file, which is always a relative URL. A relative URL is just the path segment of an URL, without a protocol, port, or domain name, like this:

"error.jsp"    
"/templates/onlinestore.html"       
"/beans/calendar.jsp"

If the relative URL starts with /, the path is relative to the JSP application's context, which is a javax.servlet.ServletContext object that is in turn stored in the application object. If the relative URL starts with a directory or file name, the path is relative to the JSP page.

Tip

If you are including a text file and do not want the text to be displayed in the JSP page, place the text in a comment element.

See Also


Page Directive

Defines attributes that apply to an entire JSP page.

JSP Syntax

<%@ page              
   [ language="java" ]             
   [ extends="package.class" ]   
   [ import="{package.class | package.*}, ..." ]         
   [ session="true|false" ]        
   [ buffer="none|8kb|sizekb" ] 
   [ autoFlush="true|false" ]     
   [ isThreadSafe="true|false" ]               
   [ info="text" ]        
   [ errorPage="relativeURL" ]   
   [ contentType="mimeType [ ; charset=characterSet ]" |        
      "text/html ; charset=ISO-8859-1" ]            
   [ isErrorPage="true|false" ]  
   [ pageEncoding="characterSet | ISO-8859-1" ]    
   [ isELIgnored="true|false"]   
%>

OR

 

where pageDirectiveAttrList is the same as the list in the JSP syntax.

XML Syntax

 

where pageDirectiveAttrList is the same as the list in the JSP syntax.

Examples

<%@ page import="java.util.*, java.lang.*" %>
<%@ page buffer="5kb" autoFlush="false" %>

Description

The page directive applies to an entire JSP page and any of its static include files, which together are called a translation unit. A static include file is a file whose content becomes part of the calling JSP page. The page directive does not apply to any dynamic resources; see for more information.

You can use the page directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a page directive with import more than once in a JSP page or translation unit.

No matter where you position the page directive in a JSP page or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP page.

Attributes

  • language="java"

The scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files. In v2.0, the only allowed value is java.

  • extends="package.class"

The fully qualified name of the superclass of the Java class this JSP page will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled class.

  • import="{package.class | package.*}, ..."

A comma-separated list of Java packages that the JSP page should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP page. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP page.

The following packages are implicitly imported, so you don't need to specify them with the import attribute:

java.lang.*

javax.servlet.*

javax.servlet.jsp.*

javax.servlet.http.*

You must place the import attribute before the element that calls the imported class.

  • session="true|false"

Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session.

If the value is false, you cannot use the session object or a element with scope=session in the JSP page. Either of these usages would cause a translation-time error.

The default value is true.

  • buffer="none|8kb|sizekb"

The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.

  • autoFlush="true|false"

Whether the buffered output should be flushed automatically when the buffer is full. If set to true (the default value), the buffer will be flushed. If set to false, an exception will be raised when the buffer overflows. You cannot set autoFlush to false when buffer is set to none.

  • isThreadSafe="true|false"

Whether thread safety is implemented in the JSP page. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.

  • info="text"

A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.

  • errorPage="relativeURL"

A pathname to a JSP page that this JSP page sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the web server. If not, the pathname is relative to the current JSP page.

  • isErrorPage="true|false"

Whether the JSP page displays an error page. If set to true, you can use the exception object in the JSP page. If set to false (the default value), you cannot use the exception object in the JSP page.

  • contentType="mimeType [; charset=characterSet ]" |

"text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP page uses for the response. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

  • pageEncoding="characterSet | ISO-8859-1"

The character encoding the JSP page uses for the response. The default character set is ISO-8859-1.

  • isElIgnored="true | false"


Defines whether EL expressions are ignored or evaluated for this page and translation unit. If true, EL expressions (of the form ${...}) are ignored by the container. If false, EL expressions (of the form ${...}) are evaluated when they appear in template text or action attributes. The default value varies depending on the version of the Web application deployment descriptor. The default mode for JSP pages delivered using a Servlet 2.3 or earlier descriptor is to ignore EL expressions. The default mode for JSP pages delivered with a Servlet 2.4 descriptor is to evaluate EL expressions.

Tip

If you need to include a long list of packages or classes in more than one JSP page, you can create a separate JSP page with a page directive that contains the import list and include that file in the main JSP page.


Tag Directive

Used for declaring custom tag properties.

JSP Syntax

<%@ tag                 
[ display-name="name of the tag file | display-name" ]
[ body-content="scriptless|tagdependent|empty" ]
[ dynamic-attributes="page-scoped attribute" ]
[ small-icon="relativeURL" ]
[ large-icon="relativeURL" ]
[ description="text" ]
[ example="text" ]
[ language="java" ]
[ import="{package.class | package.*} , ... " ]
[ pageEncoding="{characterSet | ISO-8859-1}" ]
[ isELIgnored="true|false" ]     
%>

OR

tagDirectiveAttrList />
where tagDirectiveAttrList is the same as the attribute list in the JSP syntax.

XML Syntax

where tagDirectiveAttrList is the same as the attribute list in the JSP syntax.

Examples

This tag accepts an arbitrary number of attributes whose values are colors and outputs a bulleted list of the attributes colored according to the values:

The following code implements the preceding tag. An arbitrary number of attributes whose values are colors are stored in a Map named by the dynamic-attributes attribute of the tag directive. The JSTL forEach tag is used to iterate through the Map and the attribute keys and colored attribute values are printed in a bulleted list.

<%@ tag dynamic-attributes="colorMap"%>           
          
  • ${color.key} = ${color.value}
  • font>
  •            

    Description

    The tag directive is similar to the page directive in a JSP page, but applies to tag files instead of JSP pages. As with the page directive, a translation unit can contain more than one instance of the tag directive. All the attributes apply to the complete translation unit. However, there can be only one occurrence of any attribute or value defined by this directive in a given translation unit. With the exception of the import attribute, multiple attribute or value (re)definitions result in a translation error.

    Attributes

    • display-name="name of the tag file | display-name"

    A short name that is intended to be displayed by tools. Defaults to the name of the tag file, without the .tag extension.

    • body-content="scriptless|tagdependent|empty"

    Provides information on the content of the body of this tag. Can be either empty, tagdependent, or scriptless. A translation error results if JSP or any other value is used. Defaults to scriptless.

    • dynamic-attributes="page-scoped attribute"

    Indicates whether this tag supports additional attributes with dynamic names. If present, the generated tag handler must implement the javax.servlet.jsp.tagext.DynamicAttributes interface, and the container must treat the tag as if its corresponding TLD entry contained true. The implementation must not reject any attribute names. The value identifies a page-scoped attribute in which to place a Map containing the names and values of the dynamic attributes passed during invocation of the tag. The Map must contain each dynamic attribute name as the key and the dynamic attribute value as the corresponding value. Only dynamic attributes with no URI are to be present in the Map; all other dynamic attributes are ignored. A translation error results if the value of the dynamic-attributes of a tag directive is equal to the value of a name-given of a variable directive or the value of a name attribute of an attribute directive.

    • small-icon="relativeURL"

    Either a context-relative path, or a path relative to the tag source file, of an image file containing a small icon that can be used by tools. Defaults to no small icon.

    • large-icon="relativeURL"

    Either a context-relative path, or a path relative to the tag source file, of an image file containing a large icon that can be used by tools. Defaults to no large icon.

    • description="text"

    Defines an arbitrary string that describes this tag. Defaults to no description.

    • example="text"

    Defines an arbitrary string that presents an informal description of an example of a use of this action. Defaults to no example.

    • language="java"

    Carries the same syntax and semantics of the language attribute of the page directive.

    • import="{package.class | package.*} , ... "

    Carries the same syntax and semantics of the import attribute of the page directive.

    • pageEncoding="{characterSet | ISO-8859-1}"

    Carries the same syntax and semantics of the pageEncoding attribute in the page directive. However, there is no corresponding global configuration element in web.xml. The pageEncoding attribute cannot be used in tag files in XML syntax.

    • isELIgnored="true|false"

    Carries the same syntax and semantics of the isELIgnored attribute of the page directive. However, there is no corresponding global configuration element in web.xml.


    Taglib Directive

    Defines a tag library and prefix for the custom tags used in the JSP page.

    JSP Syntax

    <%@ taglib {uri="URI" | tagdir="/WEB-INF/tags[/subdir]+"} 
    prefix="tagPrefix" %>

    XML Syntax

    None. Included in and in any other XML element using the xmlns attribute instead:

    prefix="{uri | urn:jsptld:path |              
          urn:jsptagdir:/WEB-INF/tags[/subdir]+}" >

    Examples

    <%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %>      
                   
               
       ...         

    Description

    The taglib directive declares that the JSP page uses custom tags, names the tag library that defines them, and specifies their tag prefix.

    You must use a taglib directive before you use the custom tag in a JSP page. You can use more than one taglib directive in a JSP page, but the prefix defined in each must be unique.

    Tutorials on creating custom tags are available at http://java.sun.com/products/jsp/taglibraries.html#tutorials.

    Attributes

    • uri="URI"

    The Uniform Resource Identifier (URI) that uniquely locates the TLD that describes the set of custom tags associated with the named tag prefix. A URI can be any of the following:

      • A Uniform Resource Locator (URL), as defined in RFC 2396, available at http://www.hut.fi/u/jkorpela/rfc/2396/full.html
      • A Uniform Resource Name (URN), as defined in RFC 2396
      • An absolute or relative pathname

    If the URI is a URL or URN, then the TLD is located by consulting the mapping indicated in web.xml extended using the implicit maps in the packaged tag libraries. If URI is pathname, it is interpreted relative to the root of the web application and should resolve to a TLD file directly, or to a JAR file that has a TLD file at location META-INF/taglib.tld.

    • tagdir="/WEB-INF/tags[/subdir]+"

    Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. An implicit tag library descriptor is used. A translation error must occur under any of these conditions:

      • The value does not start with /WEB-INF/tags/.
      • The value does not point to a directory that exists.
      • If this attribute is used in conjunction with the uri attribute.
    • prefix="tagPrefix"

    The prefix that precedes the custom tag name, for example, public in . Empty prefixes are illegal. If you are developing or using custom tags, you cannot use the tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by Sun Microsystems.

    See Also

    • Section JSP.8.4 of the JSP 2.0 Specification for information on the implicit tag library descriptor.

    Variable Directive

    Declares an expression language variable exposed by the tag to the calling page.

    JSP Syntax

    <%@ variable { name-given="scripting variable" |   
       (name-from-attribute="scripting variable"              
       alias="locally-scoped attribute")}           
       [ variable-class="java.lang.String" | name of the variable class" ]       
       [ declare="true | false" ]      
       [ scope="AT_BEGIN | AT_END | NESTED" ]         
       [ description="text" ]             
    %>

    OR

    XML Syntax

    Examples

    The following tag file declares a variable, x, with a scope of AT_END and sets its value to 3.

    <%-- a.tag --%>
    <%@ variable name-given="x" scope="AT_END" %>

    The following JSP page references the variable with an EL expression.

    <%-- b.jsp --%>
    <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
    ${x} 
    ${x} 

    The first reference to the variable is undefined because the variable has not been declared yet. After the tag file has been invoked and the variable is set, the page references the variable again, which will result in an output of 3.

    Description

    The variable directive is used to declare variables in tag files. The variable directive is analogous to the variable element in the Tag Library descriptor, and defines the details of a variable exposed by the tag handler to the calling page.

    A custom tag (whether it's implemented using Java or a tag file) is able to declare that it returns variables to the calling page. For example, the following tag can look up user information and place it in a bean:

        
        ${userInfo.name}

    In this case, the lookupUserInfo tag can declare that it returns a variable to the calling page with a name of userInfo.

    Here is another example:

          ${customer.name}
     

    The scope of the variable affects how it is exposed to the calling page (AT_BEGIN means the variable is available from the start tag onwards, AT_END means the variable is available from the end tag onwards, and NESTED means the variable is only available in the body of the tag). In the first preceding example, you would probably use AT_END so that the variable is still available at the end of the tag. In the second example, you would probably use NESTED since the ${customer} variable doesn't need to be accessible anywhere but inside the displayCustomers tag.

    When you want to emulate OUT parameters, use variables with scope AT_BEGIN or AT_END. For each AT_BEGIN or AT_END variable, a page-scoped attribute is made available in the JspContext of the tag file. The scoped attribute is not initialized. Synchronization is performed at the end of the tag for AT_BEGIN and AT_END and also before the invocation of a fragment for AT_BEGIN.

    When you want to emulate nested parameters, use variables with scope AT_BEGIN or NESTED. For each AT_BEGIN or NESTED variable, a page-scoped attribute is made available in the JspContext of the tag file. The scoped attribute is not initialized. Synchronization is performed before each fragment invocation for AT_BEGIN and NESTED, and also after the end of the tag for AT_BEGIN

    The JSP specification recommends that to accomplish IN parameters, use attributes. To accomplish OUT or NESTED parameters, use variables.

    Attributes

    • name-given="scripting variable" | name-from-attribute="scripting variable"

    Defines an EL variable to be used in the page invoking this tag. Either name-given or name-from-attribute must be specified. If name-given is specified, the value is the name of an attribute whose (translation-time) value at the start of the tag invocation will give the name of the variable.

    Translation errors arise in the following circumstances:

      • Specifying neither name-given nor name-from-attribute.
      • If two variable directives have the same name-given.
      • If the value of a name-given attribute of a variable directive is equal to the value of a name attribute of an attribute directive or the value of a dynamic-attributes attribute of a tag directive.
    • alias="locally-scoped attribute"


    Defines a variable, local to the tag file, to hold the value of the EL variable. The container will synchronize this value with the variable whose name is given in name-from-attribute.

    Required when name-from-attribute is specified. A translation error results if used without name-from-attribute.

    A translation error results if the value of alias is the same as the value of a name attribute of an attribute directive or the name-given attribute of a variable directive.

    • variable-class="java.lang.String" | name of the variable class"


    The name of the class of the variable. The default is java.lang.String.

    • declare="true | false"


    Whether or not the variable is declared. Defaults to true.

    • scope="AT_BEGIN | AT_END | NESTED"


    The scope of the variable. Defaults to NESTED.

    • description="text"


    An optional description of this variable. Defaults to no description.

    See Also


    The jsp:attribute element allows you to define the value of a tag attribute in the body of an XML element instead of in the value of an XML attribute.

    JSP Syntax

    attributeName" [ trim= "true | false" ] />

    XML Syntax

    Same as JSP syntax.

    Examples

    The following template page uses jsp:attribute, which uses the output of fmt:message to set the value of the value attribute of tt:parameter:

    ...
       
          
             
          
       
    ...
    ...

    Description

    The jsp:attribute standard action has two uses:

    • It allows the page author to define the value of an action attribute in the body of an XML element instead of in the value of an XML attribute.
    • It allows the page author to specify the attributes of an element dynamically generated by the jsp:element action, which can only appear as a subelement of a standard or custom action.

    All JSP standard actions and custom actions can contain a jsp:attribute standard element as a substitute for any of its attributes. One use case in which jsp:attribute is particularly helpful is where the value of an attribute is the result of a multi-line expression, which would not fit in the value of an attribute in the start tag of the action.

    If an action contains any jsp:attribute elements and the action also has a body, it must use the jsp:body tag to represent the body. The body of jsp:attribute is restricted according to the type of attribute being specified:

    • For simple attributes that accept an EL expression, the body can be any JSP content.
    • For simple attributes that do not accept an EL expression, the body can contain only static text.
    • For fragment attributes, the body must not contain any scripting elements.

    Attributes

    • name="attributeName"

    Identifies which tag attribute is being specified. When used with jsp:element, this attribute specifies the name of the attribute to be included in the generated element.

    If the jsp:attribute tag is not being used with jsp:element and the action does not accept dynamic attributes, the name must match the name of an attribute for the action being invoked, as declared in the Tag Library Descriptor for a custom action, or as specified for a standard action. If it doesn't match, a translation error results.

    If the jsp:attribute element is being used with a jsp:element tag, a translation error results if both an XML element attribute and a jsp:attribute element are used to specify the value for the same attribute.

    The value of name can be a QName. If so, a translation error must occur if the prefix does not match that of the action it applies to, unless the action supports dynamic attributes or the action is jsp:element.

    • trim= "true | false"


    The optional trim attribute determines whether or not whitespace appearing at the beginning and end of the element body should be discarded. By default, the leading and trailing whitespace (including spaces, carriage returns, line feeds, and tabs) is discarded. The whitespace is trimmed when the JSP page is translated. If a body contains a custom tag that produces leading or trailing whitespace, that whitespace is preserved regardless of the value of the trim attribute.

    See Also


    Specifies the body of a tag.

    JSP Syntax

    any elements or text

    XML Syntax

    Same as JSP syntax.

    Examples

    This example generates an HTML header tag with a lang attribute:

             
       xmlns:jsp="http://java.sun.com/JSP/Page">          
       ${content.lang} 
       ${content.body}               

    The name attribute identifies the generated tag's name. The jsp:attribute tag generates the lang attribute. The body of the jsp:attribute tag identifies the value of the lang attribute. The jsp:body tag generates the body of the tag. The output of this example jsp:element could be:

    Heading in French

    Description

    Normally, the body of a standard or custom action invocation is defined implicitly as the body of the XML element used to represent the invocation. The body of a standard or custom action can also be defined explicitly using the jsp:body standard action. This is required if one or more jsp:attribute elements appear in the body of the tag.

    If one or more jsp:attribute elements appear in the body of a tag invocation but no jsp:body element appears or an empty jsp:body element appears, it is the equivalent of the tag having an empty body.

    It is also legal to use the jsp:body standard action to supply bodies to any standard actions that accepts a body (except for jsp:body, jsp:attribute, jsp:scriptlet, jsp:expression, and jsp:declaration). The body standard action accepts no attributes.

    See Also


    Dynamically generates an XML element.

    JSP Syntax

    (elementName"       
     ( /> | >  ( any elements or text  ))
    ) 
    | ( elementName">
           [ attributeName"             
             [ trim="true | false" ]
          ( /> | (any elements or text  ) ) ]+ 
          [  any elements or text  ]
        
      )

    XML Syntax

    Same as JSP syntax.

    Examples

    This example generates an HTML header tag with a lang attribute:

             
       xmlns:jsp="http://java.sun.com/JSP/Page">          
       ${content.lang} 
       ${content.body}               

    The name attribute identifies the generated tag's name. The jsp:attribute tag generates the lang attribute. The body of the jsp:attribute tag identifies the value of the lang attribute. The jsp:body tag generates the body of the tag. The output of this example jsp:element could be:

    Heading in French

    Description

    The jsp:element action is used to dynamically define the value of the tag of an XML element. This action can be used in JSP pages, tag files and JSP documents.

    A jsp:element action has one mandatory attribute, name, of type String. The value of the name attribute is used as that of the tag of the element generated. The jsp:element action can have a body. Two forms are valid, depending on whether the element is to have attributes or not. In the first form, no attributes are present:

       
       optional body        

    In the second form, zero or more attributes are requested, using jsp:attribute and jsp:body, as appropriate.

       
       [jsp:attribute]+     
       [jsp:body]             

    The one valid, mandatory, attribute of jsp:element is its name. Unlike other standard actions, the value of the name attribute must be given as an XML-style attribute and cannot be specified using jsp:attribute This is because jsp:attribute has a special meaning when used in the body of jsp:element.

    Attributes

    • name="elementName"

    The value of name is that of the element generated. The name can be a QName; JSP 2.0 places no constraints on this value: it is accepted as is. A request-time attribute value may be used for this attribute.

    See Also


    Evaluates the body of the tag used by the calling page to invoke this tag file.

    JSP Syntax

    scopedAttributeName"  |           
        varReader="scopedAttributeName" }    
       [scope="page | request | session | application" ] />) | />

    XML Syntax

    Same as JSP syntax.

    Examples

    This example tag file encapsulates the double custom tag

    <%-- double.tag --%>

    It includes two jsp:doBody tags, which will each invoke the body of the custom double tag in any JSP that includes the tag.

    This example JSP page uses the custom double tag to output the text included in the body of the tag two times.

    <%-- a.jsp --%>
    <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
      This text will be printed twice.

    The result will be the output:

    This text will be printed twice.
    This text will be printed twice.

    Description

    The jsp:doBody standard action can only be used in tag files. It invokes the body of the tag, sending the output of the result to the JspWriter, or to a scoped attribute that can be examined and manipulated.

    The jsp:doBody standard action behaves exactly like jsp:invoke, except that it operates on the body of the tag instead of on a specific fragment passed as an attribute. Because it always operates on the body of the tag, there is no name attribute for this standard action.

    Fragments are provided access to variables the same way for jsp:doBody as they are for jsp:invoke. If no body was passed to the tag, jsp:doBody will behave as though a body was passed in that produces no output.

    The body of a tag is passed to the simple tag handler as a JspFragment object. A translation error shall result if the jsp:doBody action contains a nonempty body.

    The result of evaluating the tag body is sent to the response or is stored in an EL variable for later manipulation. To store the result of evaluating a fragment to an EL variable, you specify the var or varReader attribute. If var is specified, the container stores the result in an EL variable of type String with the name specified by var. If varReader is specified, the container stores the result in an EL variable of type java.io.Reader, with the name specified by varReader. The Reader object can then be passed to a custom tag for further processing. A translation error occurs if both var and varReader are specified. An optional scope attribute indicates the scope of the resulting variable. The possible values are page (default), request, session, or application. A translation error occurs if you use this attribute without specifying the var or varReader attribute.

    Attributes

    • var="scopedAttributeName"

    The name of a scoped attribute to store the result of the body invocation in, as a java.lang.String object. A translation error must occur if both var and varReader are specified. If neither var nor varReader are specified, the result of the body goes directly to the JspWriter, as described above.

    • varReader="scopedAttributeName"

    The name of a scoped attribute to store the result of the body invocation in, as a java.io.Reader object. A translation error must occur if both var and varReader are specified. If neither var nor varReader is specified, the result of the body invocation goes directly to the JspWriter, as described above.

    • scope="page | request | session | application"

    The scope in which to store the resulting variable. A translation error results if the value is not one of page, request, session, or application. A translation error results if this attribute appears without specifying either the var or varReader attribute as well. Note that a value of session should be used with caution since not all calling pages may be participating in a session. A container must throw an IllegalStateException at runtime if scope is session and the calling page does not participate in a session. Defaults to page.


    Forwards a request to a web resource.

    JSP Syntax

    relativeURL | '${' Expression'}' |             
       <%= expression %>}" { /> | > [parameterName" 
    value="{parameterValue | '${' Expression '}' | <%= expression %>}" } 
    /> ]+ }

    XML Syntax

    relativeURL | '${' Expression '}' |            
       %= expression % }" { /> | > [  name="parameterName"    
       value="{parameterValue | '${' Expression '}' | %= expression %}" }     
    /> ]+  }

    Examples

            
         

    Description

    The jsp:forward element forwards the request object containing the client request information from one JSP page to another resource. The target resource can be an HTML file, another JSP page, or a servlet, as long as it is in the same application context as the forwarding JSP page. The lines in the source JSP page after the jsp:forward element are not processed.

    You can pass parameter names and values to the target resource by using a jsp:param clause. An example of this would be passing the parameter name username (with name="username") and the value scott (with value="scott") to a servlet as part of the request. If you use jsp:param, the target resource should be a dynamic resource that can handle the parameters.

    Be careful when using jsp:forward with unbuffered output. If you have used the page directive with buffer="none" to specify that the output of your JSP page should not be buffered, and if the JSP page has any data in the out object, using jsp:forward will cause an IllegalStateException.

    Attributes

    • page="{relativeURL | <%= expression %>}"

    A String or an expression representing the relative URL of the component to which you are forwarding the request. The component can be another JSP page, a servlet, or any other object that can respond to a request.

    The relative URL looks like a path--it cannot contain a protocol name, port number, or domain name. The URL can be absolute or relative to the current JSP page. If it is absolute (beginning with a /), the path is resolved by your web or application server.

    • parameterName" value="{parameterValue | <%= expression %>}" />+

    Sends one or more name/value pairs as parameters to a dynamic resource. The target resource should be dynamic, that is, a JSP page, servlet, or other resource that can process the data that is sent to it as parameters.

    You can use more than one jsp:param clause if you need to send more than one parameter to the target resource. The name attribute specifies the parameter name and takes a case-sensitive literal string as a value. The value attribute specifies the parameter value and takes either a case-sensitive literal string or an expression that is evaluated at request time.

    See Also


    Inserts the value of a bean property into the result.

    JSP Syntax and XML Syntax

    beanInstanceName" property="propertyName" />

    Examples

                    

    Calendar of   

    Description

    The jsp:getProperty element gets a bean property value using the property's getter methods and inserts the value into the response. You must create or locate a bean with before you use jsp:getProperty.

    The jsp:getProperty element has a few limitations you should be aware of:

    • You cannot use jsp:getProperty to retrieve the values of an indexed property.
    • You can use jsp:getProperty with JavaBeans components, but not with enterprise beans. As alternatives, you can write a JSP page that retrieves values from a bean that in turn retrieves values from an enterprise bean, or you can write a custom tag that retrieves values from an enterprise bean directly.

    Attributes

    • name="beanInstanceName"

    The name of an object (usually an instance of a bean) as declared in a element.

    • property="propertyName"

    The name of the bean property whose value you want to display. The property is declared as a variable in a bean and must have a corresponding getter method (for more information on declaring variables and writing getter methods in beans, see http://java.sun.com/products/javabeans/docs/).

    Tip

    If you use jsp:getProperty to retrieve a property value that is null, a NullPointerException is thrown. However, if you use a scriptlet or expression to retrieve the value, the string null is displayed in the browser; see Scriptlet or Expression for more information.

    See Also


    Includes a static file or the result from another web component.

    JSP Syntax

    "{relativeURL | '${' Expression '}' |              
       <%= expression %>}"          
       [ flush="true| false" ]           
       { /> | > [ parameterName"    
          value="{parameterValue | '${' Expression '}' |    
          <%= expression %>}" />] +             
     }

    XML Syntax

    "{relativeURL | '${' Expression '}' |              
       %= expression %}"              
       [ flush="true| false" ]           
       { /> | > [ parameterName"    
          value="{parameterValue | '${' Expression '}' |    
          %= expression %}" />] +  
     }

    Examples

          
         

    Description

    The jsp:include element allows you to include either a static or dynamic resource in a JSP page. The results of including static and dynamic resources are quite different. If the resource is static, its content is included in the calling JSP page. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP page.

    You cannot always determine from a pathname if a resource is static or dynamic. For example, http://server:8080/index.html might map to a servlet through a server alias. The jsp:include element handles both types of resources, so it is convenient to use when you don't know whether the resource is static or dynamic.

    If the included resource is dynamic, you can use a jsp:param clause to pass the name and value of a parameter to the resource. As an example, you could pass the string username and a user's name to a login form that is coded in a JSP page.

    Attributes

    • page="{ relativeURL | <%= expression %> }"

    The relative URL that locates the resource to be included, or an expression that evaluates to a String equivalent to the relative URL.

    The relative URL looks like a pathname--it cannot contain a protocol name, port number, or domain name. The URL can be absolute or relative to the current JSP page. If it is absolute (beginning with a /), the pathname is resolved by your web or application server.

    • flush="true | false"

    If the page output is buffered and the flush attribute is given a true value, the buffer is flushed prior to the inclusion, otherwise the buffer is not flushed. The default value for the flush attribute is false.

    • parameterName" value="{parameterValue | <%= expression %>}" />+

    The jsp:param clause allows you to pass one or more name/value pairs as parameters to an included resource. The included resource should be dynamic, that is, a JSP page, servlet, or other resource that can process the parameter.

    You can use more than one jsp:param clause if you want to send more than one parameter to the included resource. The name attribute specifies the parameter name and takes a case-sensitive literal string. The value attribute specifies the parameter value and takes either a case-sensitive literal string or an expression that is evaluated at request time.

    See Also


    Evaluates a fragment attribute.

    JSP Syntax

    fragmentName"    
    ({var="scopedAttributeName" | 
    varReader="scopedAttributeName"}         
    [scope="page | request | session | application" ] />) | />

    XML Syntax

    Same as JSP syntax

    Examples

    The following tag file represents a tag that renders the catalog of a book database as an HTML table. The tag file declares that it sets variables, which are used by two fragment attributes. Before the tag invokes the fragment attributes using the jsp:invoke element, the Web container passes values for the variables back to the calling page.

    <%@ attribute name="bookDB" required="true"
      type="database.BookDB" %>
    <%@ attribute name="color" required="true" %>
    <%@ attribute name="normalPrice" fragment="true" %>
    <%@ attribute name="onSale" fragment="true" %>
     
    <%@ variable name-given="price" %> 
    <%@ variable name-given="salePrice" %>
     
      ...
      
      
        
          
        
        
          
        
      
    ...
     

    The following page invokes the tag. The formatting of the book price is determined by two fragment attributes--normalPrice and onSale--that are conditionally invoked by the tag according to data retrieved from the book database.

      
        
      
      
        
        
        
        
        
        
      
     

    Description

    The jsp:invoke standard action takes the name of an attribute that is a fragment, and invokes the fragment, sending the output of the result to the JspWriter, or to a scoped attribute that can be examined and manipulated. If the fragment identified by the given name is null, jsp:invoke will behave as though a fragment was passed in that produces no output.

    The most basic usage of this standard action will invoke a fragment with the given name with no parameters. It is also possible to invoke the fragment and send the results to a scoped attribute for further examination and manipulation. This can be accomplished by specifying the var or varReader attribute in the action. If var is specified, the container stores the result in an EL variable of type String with the name specified by var. If varReader is specified, the container stores the result in an EL variable of type java.io.Reader, with the name specified by varReader. The Reader object can then be passed to a custom tag for further processing. A translation error occurs if both var and varReader are specified.

    Attributes

    • fragment="fragmentName"

    The name used to identify this fragment during this tag invocation.

    • var="scopedAttributeName"

    The name of a scoped attribute to store the result of the fragment invocation in, as a java.lang.String object. A translation error must occur if both var and varReader are specified. If neither var nor varReader are specified, the result of the fragment goes directly to the JspWriter.

    • varReader="scopedAttributeName"

    The name of a scoped attribute to store the result of the fragment invocation in, as a java.io.Reader object. A translation error must occur if both var and varReader are specified. If neither var nor varReader is specified, the result of the fragment invocation goes directly to the JspWriter.

    • scope="page | request | session | application"

    The scope in which to store the resulting variable. A translation error must result if the value is not one of page, request, session, or application. A translation error will result if this attribute appears without specifying either the var or varReader attribute as well. Note that a value of session should be used with caution since not all calling pages may be participating in a session. A container must throw an IllegalStateException at runtime if scope is session and the calling page does not participate in a session. Defaults to page.var="scopedAttributeName".

    See Also


    Specifies the XML declaration or the document type declaration in the request output of a JSP document or a tag file that is in XML syntax.

    XML Syntax

             
       { doctypeDecl } />
       doctypeDecl ::= ( doctype-root-element="rootElement"
       doctype-public="PubidLiteral"
       doctype-system="SystemLiteral" )
       | ( doctype-root-element="rootElement"                
          doctype-system="SystemLiteral" )

    Examples

    Here is an example of specifying a document type declaration with jsp:output:

                  
       doctype-system="books.dtd" /> 

    The resulting output is:

     

    Description

    The jsp:output element specifies the XML declaration or the document type declaration in the request output of the JSP document.

    The XML declaration and document type declaration that are declared by the jsp:output element are not interpreted by the JSP container. Instead, the container simply directs them to the request output.

    Generating a Document Type Declaration

    A document type declaration (DTD) defines the structural rules for the XML document in which the document type declaration occurs. XML documents are not required to have a DTD associated with them.

    Specifying the document type declaration in the jsp:output element will not cause the JSP container to validate the JSP document against the DTD.

    If you want the JSP document to be validated against the DTD, you must manually include the document type declaration within the JSP document, just as you would with any XML document.

    Generating XML Declarations

    Here is an example of an XML declaration:

     

    This declaration is the default XML declaration. It means that if the JSP container is generating an XML declaration, this is what the JSP container will include in the output of your JSP document.

    Neither a JSP document nor its request output is required to have an XML declaration. In fact, if the JSP document is not producing XML output then it shouldn't have an XML declaration.

    The JSP container will not include the XML declaration in the output when either of the following is true:

    • You set the omit-xml-declaration attribute of the jsp:output element to either true or yes.
    • You have a jsp:root element in your JSP document, and you do not specify omit-xml-declaration="false" in jsp:output.

    The JSP container will include the XML declaration in the output when either of the following is true:

    • You set the omit-xml-declaration attribute of the jsp:output element to either false or no.
    • You do not have a jsp:root action in your JSP document, and you do not specify the omit-xml-declaration attribute in jsp:output.

    The jsp:output element has three attributes that you use to generate the document type declaration:

    • doctype-root-element: Indicates the root element of the XML document
    • doctype-system: Indicates the URI reference to the DTD
    • doctype-public: A more flexible way to reference the DTD. This identifier gives more information about the DTD without giving a specific location. A public identifier resolves to the same actual document on any system even though the location of that document on each system may vary. See the XML 1.0 specification for more information.

    The rules for using the attributes are as follows:

    • The doctype attributes can appear in any order
    • The doctype-root attribute must be specified if the doctype-system attribute is specified
    • The doctype-public attribute must not be specified unless doctype-system is specified

    Attributes

    • omit-xml-declaration="yes | no | true | false"

    Indicates whether to omit the generation of an XML declaration.

    • doctype-root-element="rootElement"


    Must be specified if and only if doctype-system is specified or a translation error must occur. Indicates the name that is to be output in the generated DOCTYPE declaration.

    • doctype-system="SystemLiteral"


    Specifies that a DOCTYPE declaration is to be generated and gives the value for the System Literal.

    • doctype-public="PubidLiteral"


    Must not be specified unless doctype-system is specified. Gives the value for the Public ID for the generated DOCTYPE.

    See Also


    Causes the execution of an applet or bean. The applet or bean executes in the specified plugin. If the plugin is not available, displays a dialog to initiate the download of the plugin software.

    JSP Syntax

                  
       type="bean|applet"               
       code="classFileName"           
       codebase="classFileDirectoryName"      
       [ name="instanceName" ]     
       [ archive="URIToArchive, ..." ]             
       [ align="bottom|top|middle|left|right" ] 
       [ height="{displayPixels |  <%= expression %>}"] 
       [ width="{displayPixels |  <%= expression %>}"]  
       [ hspace="leftRightPixels" ]    
       [ vspace="topBottomPixels" ] 
       [ jreversion="JREVersionNumber | 1.2" ]              
       [ nspluginurl="URLToPlugin" ]               
       [ iepluginurl="URLToPlugin" ] >             
                   
       [      
          [ parameterName"              
             value="{parameterValue | '${' Expression '}' |                
             <%= expression %>}" /> ]+          
        ]   
                   
       [  text message if plugin download fails            
           ]               
                   

    XML Syntax

                  
       type="bean|applet"  code="classFileName"           
       codebase="classFileDirectoryName"      
       [ name="instanceName" ]  [ archive="URIToArchive, ..." ]    
       [ align="bottom|top|middle|left|right" ] 
       [ height="{displayPixels | '${' Expression '}' | %= expression %}" ]       
       [ width="{displayPixels | '${' Expression '}' | %= expression %}"]         
       [ hspace="leftRightPixels" ]  [ vspace="topBottomPixels" ]      
       [ jreversion="JREVersionNumber | 1.2" ]               
       [ nspluginurl="URLToPlugin" ]               
       [ iepluginurl="URLToPlugin" ]  >            
       [      
          [ parameterName"              
             value="{parameterValue | '${' Expression '}' |                
             %= expression %}" /> ]+              
        ]   
       [   text message if plugin download fails           
         ]  

    Examples

              
              
                
             
              
          

    Unable to load applet

            

    Description

    The jsp:plugin element plays or displays an object (typically an applet or bean) in the client web browser, using a Java plug-in that is built in to the browser or downloaded from a specified URL.

    When the JSP page is translated and compiled and Java and sends back an HTML response to the client, the jsp:plugin element is replaced by either an or element, according to the browser version. The element is defined in HTML 4.0 and in HTML 3.2.

    In general, the attributes to the jsp:plugin element specify whether the object is a bean or an applet, locate the code that will be run, position the object in the browser window, specify an URL from which to download the plug-in software, and pass parameter names and values to the object. The attributes are described in detail in the next section.

    Attributes

    • type="bean|applet"

    The type of object the plug-in will execute. You must specify either bean or applet, as this attribute has no default value.

    • code="classFileName"

    The name of the Java class file the plug-in will execute. You must include the .class extension in the name. The class file you specify should be in the directory named in the codebase attribute.

    • codebase="classFileDirectoryName"

    The directory (or path to the directory) that contains the Java class file the plug-in will execute. If you do not supply a value, the path of the JSP page that calls jsp:plugin is used.

    • name="instanceName"

    A name for the instance of the bean or applet, which makes it possible for applets or Beans called by the same JSP page to communicate with each other.

    • archive="URIToArchive, ..."

    A comma-separated list of pathnames that locate archive files that will be preloaded with a class loader located in the directory named in codebase. The archive files are loaded securely, often over a network, and typically improve the applet's performance.

    • align="bottom|top|middle|left|right"

    The position of the image, object, or applet. The position descriptions listed below use the term text line to mean the line in the viewable JSP page that corresponds to the line in the JSP page where the jsp:plugin element appears. The allowed values for align are listed below:

    bottom Aligns the bottom of the image with the baseline of the text line.

    top Aligns the top of the image with the top of the text line.

    middle Aligns the vertical center of the image with the baseline of the text line.

    left Floats the image to the left margin and flows text along the image's right side.

    right Floats the image to the right margin and flows text along the image's left side.

    • height="{displayPixels | <%= expression %>}" width="{displayPixels | <%= expression %>}"

    The initial height and width, in pixels, of the image the applet or bean displays, not counting any windows or dialog boxes the applet or bean brings up.

    • hspace="leftRightPixels" vspace="topBottomPixels"

    The amount of space, in pixels, to the left and right (or top and bottom) of the image the applet or bean displays. The value must be a nonzero number. Note that hspace creates space to both the left and right and vspace creates space to both the top and bottom.

    • jreversion="JREVersionNumber | 1.2"

    The version of the Java Runtime Environment (JRE) the applet or bean requires. The default value is 1.2.

    • nspluginurl="URLToPlugin"

    The URL where the user can download the JRE plug-in for Netscape Navigator. The value is a full URL, with a protocol name, optional port number, and domain name.

    • iepluginurl="URLToPlugin"

    The URL where the user can download the JRE plug-in for Internet Explorer. The value is a full URL, with a protocol name, optional port number, and domain name.

    • [ parameterName"
      value="{parameterValue | <%= expression %>}" /> ]+

    The parameters and values that you want to pass to the applet or bean. To specify more than one parameter value, you can use more than one jsp:param element within the jsp:params element. The name attribute specifies the parameter name and takes a case-sensitive literal string. The value attribute specifies the parameter value and takes either a case-sensitive literal string or an expression that is evaluated at runtime. If the dynamic resource you are passing the parameter to is an applet, it reads the parameter with the java.applet.Applet.getParameter method.

    • text message for user

    A text message to display for the user if the plug-in cannot be started. If the plug-in starts but the applet or bean does not, the plug-in usually displays a popup window explaining the error to the user.

    See Also


    Defines standard JSP elements and namespace attributes of tag libraries.

    JSP Syntax

    None. However, see Taglib Directive.

    XML Syntax

      
       xmlns:jsp="http://java.sun.com/JSP/Page"            
       [ xmlns:taglibPrefix="URI" ]+ ...            
       version="1.2 | 2.0">             
          JSP Page            

    Example

     
       xmlns:jsp="http://java.sun.com/JSP/Page"            
       xmlns:public="http://www.jspcentral.com/tags"     
       version="2.0">      
               
          ...      
             

    Description

    A JSP page in XML syntax can have jsp:root as its root element, but it is not required. You can instead specify your own tag as a root element. Tag libraries used within the JSP page can be represented in the root element through xmlns attributes. (Again, you can use the xmlns attributes in other tags besides the jsp:root element. The xmlns:jsp and version attributes are mandatory.

    Attributes

    • xmlns:jsp="http://java.sun.com/JSP/Page"

    Enables the use of the standard elements defined in the JSP specification.

    • version="1.2 | 2.0"

    Specifies the version of the JSP specification the page is using.

    • xmlns:taglibPrefix="URI"

    Specifies a tag library prefix and URI.

    taglibPrefix precedes the custom tag name, for example, public in . Empty prefixes are illegal. If you are developing or using custom tags, you cannot use the tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by Sun Microsystems.

    URI uniquely locates the TLD that describes the set of custom tags associated with the named prefix. URI may be of one of two forms:

    If the URI is a URI, then the TLD is located by consulting the mapping indicated in web.xml extended using the implicit maps in the packaged tag libraries. If URI is of the form urn:jsptld:path, path is interpreted relative to the root of the web application and should resolve to a TLD file directly, or to a JAR file that has a TLD file at location META-INF/taglib.tld.

    See Also


    Sets a property value or values in a bean.

    JSP Syntax

    beanInstanceName"           
    {              
       property="*" |       
       property="propertyName" [ param="parameterName" ] |      
       property="propertyName" value="{stringLiteral|    
          '${' Expression '}' | <%= expression %>}"         
    }              
    />

    XML Syntax

    beanInstanceName"           
    {              
       property="*" |       
       property="propertyName" [ param="parameterName" ] |      
       property="propertyName" value="{stringLiteral |   
          '${' Expression '}' | %= expression %}"             
    }              
    />

    Examples

       
         

    Description

    The jsp:setProperty element sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with before you set a property value with jsp:setProperty. Because jsp:useBean and jsp:setProperty work together, the bean instance names they use must match (that is, the value of name in jsp:setProperty and the value of id in jsp:useBean must be the same).

    You can use jsp:setProperty to set property values in several ways:

    • By passing all of the values the user enters (stored as parameters in the request object) to matching properties in the bean
    • By passing a specific value the user enters to a specific property in the bean
    • By setting a bean property to a value you specify as either a String or an expression that is evaluated at runtime

    Each method of setting property values has its own syntax, as described in the next section.

    Attributes and Usage

    • name="beanInstanceName"

    The name of an instance of a bean that has already been created or located with a jsp:useBean element. The value of name must match the value of id in jsp:useBean. The jsp:useBean element must appear before jsp:setProperty in the JSP page.

    • property="*"

    Stores all of the values of request parameters in bean properties. The names of the bean properties must match the names of the request parameters. A bean property is usually defined by a variable declaration with matching getter and setter methods (for more information, see http://java.sun.com/products/javabeans/docs/).

    The values of the request parameters sent from the client to the server are always of type String. The String values are converted to other data types when stored in bean properties. If a property has a PropertyEditor class as indicated in the JavaBeans specification, the setAsText(String) method is used. A conversion failure arises if the method throws an IllegalArgumentException. The allowed bean property types and their conversion methods are shown in TABLE 2.

    How jsp:setProperty Converts Strings to Other Values

    TABLE 2

    Property Type

    String Is Converted Using

    Bean Property

    Use setAsText(stringLiteral)

    boolean or Boolean

    java.lang.Boolean.valueOf(String)

    byte or Byte

    java.lang.Byte.valueOf(String)

    char or Character

    java.lang.String.charAt(0)

    double or Double

    java.lang.Double.valueOf(String)

    integer or Integer

    java.lang.Integer.valueOf(String)

    float or Float

    java.lang.Float.valueOf(String)

    long or Long

    java.lang.Long.valueOf(String)

    short or Short

    java.lang.Short.valueOf(String)

    Object

    new String(string-literal)

    You can also use jsp:setProperty to set the value of an indexed property in a bean. The indexed property must be an array of one of the data types shown in TABLE 2. The array elements are converted using the conversion methods shown in the table.

    If a request parameter has an empty or null value, the corresponding bean property is not set. Likewise, if the bean has a property that does not have a matching request parameter, the property value is not set.

    • property="propertyName" [ param="parameterName" ]

    Sets one bean property to the value of one request parameter. In the syntax, property specifies the name of the bean property and param specifies the name of the request parameter by which data is being sent from the client to the server.

    If the bean property and the request parameter have different names, you must specify both property and param. If they have the same name, you can specify property and omit param.

    If a parameter has an empty or null value, the corresponding bean property is not set.

    • property="propertyName" value="{string | <%= expression %>}"

    Sets one bean property to a specific value. The value can be a String or an expression that is evaluated at runtime. If the value is a String, it is converted to the bean property's data type according to the conversion rules shown above in TABLE 2. If it is an expression, its value must have a data type that matches the data type of the value of the expression must match the data type of the bean property.

    If the parameter has an empty or null value, the corresponding bean property is not set. You cannot use both the param and value attributes in a jsp:setProperty element.

    See Also

    Tip

    When you use property="*", the bean properties are not necessarily set in the order in which they appear in the HTML form or the bean. If the order in which the properties are set is important to how your bean works, use the syntax form property="propertyName" [ param="parameterName" ]. Better yet, rewrite your bean so that the order of setting properties is not important.


    Encloses template data.

    JSP Syntax

                   
       template data        

    XML Syntax

                   
       template data        

    Example

    i=3;               
            
     hi you all 
    i       
           

    The output is:

      hi you all             

    Description

    A jsp:text element is used to enclose template data in the XML representation. A jsp:text element has no attributes and can appear anywhere that template data can. The interpretation of a jsp:text element is to pass its content through to the current value of out.

    XML syntax allows an XML element that does not represent a standard or custom action to appear anywhere a jsp:text can appear. Such an element is passed to the current out.


    Locates or instantiates a bean with a specific name and scope.

    JSP Syntax

    beanInstanceName"     
       scope="page|request|session|application"            
    {              
       class="package.class" [ type="package.class" ]|    
       beanName="{package.class | '${' Expression '}' |  
          <%= expression %>}" type="package.class" |   
       type="package.class"            
    }              
    { /> | > other elements  }

    XML Syntax

    beanInstanceName"     
       scope="page|request|session|application"            
    {              
       class="package.class"  [ type="package.class" ]  | 
       beanName="{package.class | '${' Expression '}' |  
          %= expression %}" type="package.class" |       
          type="package.class"         
    }              
    { /> | > other elements   }

    Examples

                
         
         

    Description

    The element locates or instantiates a JavaBeans component. first attempts to locate an instance of the bean. If the bean does not exist, instantiates it from a class or serialized template.

    To locate or instantiate the bean, takes the following steps, in this order:

    1. Attempts to locate a bean with the scope and name you specify.
    2. Defines an object reference variable with the name you specify.
    3. If it finds the bean, stores a reference to it in the variable. If you specified type, gives the bean that type.
    4. If it does not find the bean, instantiates it from the class you specify, storing a reference to it in the new variable. If the class name represents a serialized template, the bean is instantiated by java.beans.Beans.instantiate.
    5. If jsp:useBean has instantiated (rather than located) the bean, and if it has body tags or elements (between <jsp:useBean> and ), executes the body tags.

    The body of a jsp:useBean element often contains a jsp:setProperty element that sets property values in the bean. As described in Step 5, the body tags are only processed if jsp:useBean instantiates the bean. If the bean already exists and jsp:useBean locates it, the body tags have no effect.

    You can use a jsp:useBean element to locate or instantiate a JavaBeans component, but not an enterprise bean. To create enterprise beans, you can write a jsp:useBean element that calls a bean that in turn calls the enterprise bean, or you can write a custom tag that calls an enterprise bean directly.

    Attributes and Usage

    • id="beanInstanceName"

    A variable that identifies the bean in the scope you specify. You can use the variable name in expressions or scriptlets in the JSP page.

    The name is case sensitive and must conform to the naming conventions of the scripting language used in the JSP page. If you use the Java programming language, the conventions in the Java Language Specification. If the bean has already been created by another jsp:useBean element, the value of id must match the value of id used in the original jsp:useBean element.

    • scope="page|request|session|application"

    The scope in which the bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:

    page You can use the bean within the JSP page with the jsp:useBean element or any of the page's static include files, until the page sends a response back to the client or forwards a request to another resource.

    request You can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. You can use the request object to access the bean, for example, request.getAttribute(beanInstanceName).

    session You can use the bean from any JSP page in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session="true".

    application You can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.

    • class="package.class"

    Instantiates a bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor. The package and class name are case sensitive.

    • type="package.class"

    If the bean already exists in the scope, gives the bean a data type other than the class from which it was instantiated. The value of type must be a superclass of class or an interface implemented by class.

    If you use type without class or beanName, no bean is instantiated. The package and class name are case sensitive.

    • class="package.class" type="package.class"

    Instantiates a bean from the class named in class and assigns the bean the data type you specify in type. The value of type can be the same as class, a superclass of class, or an interface implemented by class.

    The class you specify in class must not be abstract and must have a public, no-argument constructor. The package and class names you use with both class and type are case sensitive.

    • beanName="{package.class | <%= expression %>}" type="package.class"

    Instantiates a bean from a class, a serialized template, or an expression that evaluates to a class or serialized template. When you use beanName, the bean is instantiated by the java.beans.Beans.instantiate method. The Beans.instantiate method checks whether the package and class you specify represents a class or a serialized template. If they represent a serialized template, Beans.instantiate reads the serialized form (which has a name like package.class.ser) using a class loader.

    The value of type can be the same as beanName, a superclass of beanName, or an interface implemented by beanName. The package and class names you use with both beanName and type are case sensitive.

    See Also

    0 comments:

    Search

    My Blog List