Sei sulla pagina 1di 10

Appendix A.

JSP Elements Syntax Reference JSP defines three types of elements: directives, scripting elements, and action elements. In addition, you can define your own custom actions. This appendix contains descriptions of all JSP elements as well as the general syntax rules for custom actions. A.1 Directive Elements Directive elements are used to specify information about the page itself, especially information that doesn't differ between requests for the page. The general directive syntax is: <%@ directiveName attr1="value1" attr2="value2" %>

The attribute values can be enclosed with single quotes instead of double quotes. The directive name and all attribute names are case-sensitive. A.1.1 include Directive The include directive includes a static file, merging its content with the including page before the combined result is converted to a JSP page implementation class. The include directive supports the attribute described in Table A.1 .

Table A.1, include Directive Attribute Attribute Name Default Description file No default A page-relative or context-relative URI path for the file to include

A page can contain multiple is called a JSP translation unit Example: <%@ include file="header.html" %> A.1.2 page Directive

include .

directives. The including page and all included pages together form what

The page directive defines page-dependent attributes, such as scripting language, error page, and buffering requirements. It supports the attributes described in Table A.2 .

Table A.2, page Directive Attributes Attribute Name Default Description autoFlush true Set to true if the page buffer should be flushed automatically when it's full, or to false if an exception should be thrown when it's full. Specifies the buffer size for the page. The value must be expressed as the size in kilobytes followed by kb , or be the keyword buffering. The MIME type for the response generated by the page, and optionally the charset for the source page as well as the response; e.g., text/html;charset=Shift_JIS . none to disable

buffer

8kb

contentType

text/html

errorPage

No default A page-relative or context-relative URI path for the JSP page to forward to if an exception is thrown by code in the page. The fully qualified name of a Java class that the generated JSP page implementation class extends. The class must implement the HttpJspPage interface in the javax.servlet.jsp package JspPage . or

extends

No default Note that the recommendation is to not use this attribute. Specifying your own superclass restricts the JSP container's ability to provide a specialized, high-performance superclass.

page 260

JavaSercer Pages

import info

No default

A Java import declaration, i.e., a comma-separated list of fully qualified class names or package names followed by .* (for all public classes in the package).

No default Text that a web container may use as a description of the page in its administration user interface. false Set to true for a page that is used as an error page, to make the implicit exception variable available to scripting elements. Use for regular JSP pages. Set to true if the container is allowed to run multiple threads through the page (i.e., lets the page serve parallel requests). If set to container serializes all requests for the page. It may also use a pool of page implementation class instances to serve more than one request at a time. The recommendation is to always use true , and handle multithread issues by avoiding JSP declarations and ensuring that all objects used by the page are thread-safe. Defines the scripting language used in the page. Set to true if the page should participate in a user session. If set to false , the implicit session variable is not available to scripting elements in the page. false

isErrorPage

false

, the

isThreadSafe

true

language session

java true

A translation unit (the JSP source file and any files included via the include directive) can contain more than one page directive, as long as there is only one occurrence of an attribute, with the exception of the import attribute. If multiple import attribute values are used, they are combined into one list of import definitions. Example: <%@ page language="java" contentType="text/html;charset=Shift_JIS"%> <%@ page import="java.util.*, java.text.*" %> <%@ page import="java.sql.Date" %> A.1.3 taglib Directive Declares a tag library, containing custom actions, that is used in the page. The attributes described in Table A.3 . taglib directive supports the

Table A.3, taglib Directive Attributes Attribute Name Default Description prefix No default No default Mandatory. The prefix to use in the action element names for all actions in the library. Mandatory. Either a symbolic name for the tag library defined in the file for the application, or a page-relative or context-relative URI path for the library's TLD file or JAR file. web.xml

uri

Example: <%@ taglib uri="/orataglib" prefix="ora" %>

page 261

JavaSercer Pages

A.2 Scripting Elements Scripting elements let you add small pieces of code to a JSP page, such as an if statement that generates different HTML depending on some condition. The scripting code must be written in the language defined by the page directive. It is executed when the JSP page is requested. A.2.1 Declaration A declaration starts with <%!and ends with %>. The content between the start and the end characters must be a complete, valid declaration in the scripting language defined by the page directive. The JSP implicit variables are not visible in a declaration element. A declaration can be used to declare a scripting language variable or method. When the scripting language is Java, a variable declared by a declaration element ends up as an instance variable in the JSP page implementation class. It is therefore visible to parallel threads (requests) processing the page, and needs to be handled in a thread-safe manner. A thread-safe alternative is to declare variables within a scriptlet element instead. It then becomes a local variable of the method in the page implementation class used to process each request, and is not shared by parallel threads. Example: <%! int globalCounter = 0; %> A.2.2 Expression An expression starts with <%=and ends with %> The content between the start and the end characters must . be a complete, valid expression in the scripting language defined by the page directive that results in or can be converted to a string. All JSP implicit variables are visible in an expression element. Example: <%= globalCounter++ %> A.2.3 Scriptlet A scriptlet starts with <%and ends with %>. The content between the start and the end characters must be a code fragment in the scripting language defined by the page directive. Scriptlet code fragments are combined with code for sending the template data between them to the browser. The combination of all scriptlets in a page must form valid scripting language statements. All JSP implicit variables are visible in a scripting element. Example: <% java.util Date clock = new java.util.Date( ) %> <% if (clock.getHours( ) < 12) { %> Good morning! <% } else if (clock.getHours( ) < 17) { %> Good day! <% } else { %> Good evening! <% } %>

page 262

JavaSercer Pages

A.3 Action Elements Actions are executed when the JSP page is requested by a client. They are inserted in a page using XML element syntax, and encapsulate functionality such as input validation using beans, database access, or passing control to another page. The JSP specification defines a few standard action elements, described in this section, and also includes a framework for developing custom action elements. An action element consists of a start tag (optionally with attributes), a body, and an end tag. Other elements can be nested in the body. Here's an example: <jsp:forward page="nextPage.jsp"> <jsp:param name="aParam" value="aValue" /> </jsp:forward> If the action element doesn't have a body, a shorthand notation can be used in which the start tag ends with /> instead of >, as shown by the <jsp:param> action in this example. The action element name and attribute names are case-sensitive. Some action attributes accept a request-time attribute value, using the JSP expression syntax: <% String headerPage = currentTemplateDir + "/header.jsp"; %> <jsp:include page="<%= headerPage %>" /> The attribute descriptions for each action in this section define whether a request-time attribute value is accepted or not. A.3.1 <jsp:fallback> The <jsp:fallback> action can only be used in the body of a specify the template text to use for browsers that do not support the HTML This action supports no attributes. Example: <jsp:plugin type="applet" code="Clock2.class" codebase="applet" jreversion="1.2" width="160" height="150" > <jsp:fallback> Plugin tag OBJECT or EMBED not supported by browser. </jsp:fallback> </jsp:plugin> A.3.2 <jsp:forward> The <jsp:forward> action passes the request processing control to another JSP page or servlet in the same web application. The execution of the current page is terminated, giving the target resource full control over the request. If any response content has been buffered when the <jsp:forward> action is executed, the buffer is cleared first. If the response has already been committed (i.e., partly sent to the browser), the forwarding fails with an IllegalStateException . The URI path information available through the implicit request object is adjusted to reflect the URI path information for the target resource. All other request information is left untouched, so the target resource has access to all the original parameters and headers passed with the request. Additional parameters can be passed to the target resource through <jsp:param> elements in the <jsp:forward> element's body. <jsp:plugin> action. Its body is used to <embed> or <object> elements.

page 263

JavaSercer Pages
The <jsp:forward> action supports the attributes described in Table A.4 .

Table A.4, <jsp:forward> Attributes Attribute Name Page Java Type String Request-Time Value Accepted Description Yes Mandatory. A page-relative or context-relative URI path for the resource to forward to.

Example: <jsp:forward page="list.jsp" /> A.3.3 <jsp:getProperty> The <jsp:getProperty> action adds the value of a bean property, converted to a string, to the response generated by the page. The attributes described in Table A.5 are supported.

Table A.5, <jsp:getProperty> Attributes Attribute Name name property Java Type String String Request-Time Value Accepted Description No Mandatory. The name assigned to a bean in one of the JSP scopes. No Mandatory. The name of the bean's property to include in the page.

Example: <jsp:getProperty name="clock" property="hours" /> A.3.4 <jsp:include> The <jsp:include> action includes the response from another JSP page, servlet, or static file in the same web application. The execution of the current page continues after including the response generated by the target resource. If any response content has been buffered when the <jsp:include> action is executed, the buffer is flushed first. Even though this behavior can be controlled by the flush attribute, the only valid value in JSP 1.1 is true . This limitation will likely be lifted in a future version of JSP. The URI path information available through the implicit request object reflects the URI path information for the source JSP page even in the target resource. All other request information is also left untouched, so the target resource has access to all the original parameters and headers passed with the request. Additional parameters can be passed to the target resource through <jsp:param> elements in the <jsp:include> element's body. The <jsp:include> action supports the attributes described in Table A.6 .

Table A.6, <jsp:include> Attributes Attribute Name page flush Java Type String boolean Request-Time Value Accepted Description Yes Mandatory. A page-relative or context-relative URI path for the resource to include. No Mandatory in JSP 1.1 with true accepted value. as the only

Example: <jsp:include page="navigation.jsp" />

page 264

JavaSercer Pages
A.3.5 <jsp:param> The <jsp:param> action can be used in the body of a <jsp:forward> or <jsp:include> action to specify additional request parameters for the target resource, as well as in the body of a <jsp:params> action to specify applet parameters. The attributes described in Table A.7 are supported.

Table A.7, <jsp:param> Attributes Attribute Name Java Type Request-Time Value Accepted Description name value String String No Mandatory. The parameter name. Yes Mandatory. The parameter value.

Example: <jsp:include page="navigation.jsp"> <jsp:param name="bgColor" value="<%= currentBGColor %>" /> </jsp:include> A.3.6 <jsp:params> The <jsp:params> action can only be used in the body of a <jsp:plugin> action to enclose a set of <jsp:param> actions that are used to specify applet parameters. This action supports no attributes. Example: <jsp:plugin type="applet" code="Clock2.class" codebase="applet" jreversion="1.2" width="160" height="150" > <jsp:params> <jsp:param name="bgcolor" value="ccddff" /> </jsp:params> </jsp:plugin> A.3.7 <jsp:plugin> The <jsp:plugin> action generates HTML <embed> or <object> elements (depending on the browser type) that result in the download of the Java Plugin software (if required) and subsequent execution of the specified Java Applet or JavaBeans component. The body of the action can contain a <jsp:params> element to specify applet parameters, and a <jsp:fallback> element to specify the text shown in browsers that do not support the <embed> or <object> HTML elements. For more information about the Java Plugin, see http://java.sun.com/products/plugin/ . The attributes described in Table A.8 are supported.

Table A.8, <jsp:plugin> Attributes Attribute Name Java Type RequestTime Value Accepted

Description

align

String

No Optional. Alignment of the applet area. One of or top .

bottom , middle

archive

String

No

Optional. A comma-separated list of URIs for archives containing classes and other resources that will be preloaded. The classes are loaded using an instance of an AppletClassLoader given codebase . Relative URIs for archives are interpreted with respect to the applet's codebase .

with the

code codebase height

String String String

No Mandatory. The fully qualified class name for the object. No Mandatory. The relative URL for the directory that contains the class file. The directory must be a subdirectory to the directory holding the page, according to the HTML 4.0 specification.

No Optional. The height of the applet area, in pixels or percentage.

page 265

JavaSercer Pages

hspace iepluginurl jreversion name nspluginurl title type vspace width

String String String String String String String String String

No Optional. The amount of whitespace to be inserted to the left and right of the applet area, in pixels. No Optional. The URL for the location of the Internet Explorer Java Plugin. The default is implementation-dependent. No Optional. Identifies the spec version number of the JRE the component requires in order to operate. The default is 1.1. No Optional. The applet name, used by other applets on the same page that need to communicate with it. No Optional. The URL for the location of the Netscape Java Plugin. The default is implementation-dependent. No Optional. Text to be rendered by the browser for the applet in a some way, for instance as a "tool tip." No Mandatory. The type of object to embed, one of No Optional. The amount of whitespace to be inserted above and below the applet area, in pixels. No Optional. The width of the applet area, in pixels or percentage. applet or bean .

Example: <jsp:plugin type="applet" code="Clock2.class" codebase="applet" jreversion="1.2" width="160" height="150" > <jsp:params> <jsp:param name="bgcolor" value="ccddff" /> </jsp:params> <jsp:fallback> Plugin tag OBJECT or EMBED not supported by browser. </jsp:fallback> </jsp:plugin>

A.3.8 <jsp:setProperty> The <jsp:setProperty> Table A.9 are supported. action sets the value of one or more bean properties. The attributes described in

Table A.9, <jsp:setProperty> Attributes Attribute Name name Java Type String Request-Time Value Accepted Description

No Mandatory. The name assigned to a bean in one of the JSP scopes. No Mandatory. The name of the bean's property to set, or an asterisk ( *) to set all properties with names matching request parameters. Optional. The name of a request parameter that holds the value to use for the specified property. If omitted, the parameter name and the property name must be the same. param attribute.

property

String

param

String

No

value

See below Yes Optional. An explicit value to assign to the property. This the attribute cannot be combined with

The property type can be any valid Java type, including primitive types and arrays (i.e., an indexed property). If a runtime attribute value is specified by the value attribute, the type of the expression must match the property's type.

page 266

JavaSercer Pages
If the value is a string, either in the form of a request parameter value or explicitly specified by the attribute, it is converted to the property's type as described in Table A.10 . value

Table A.10, Conversion of String Value to Property Type Property Type Conversion Method boolean or Boolean Boolean.valueOf(String) Byte.valueOf(String) String.charAt(int) Double.valueOf(String) Integer.valueOf(String) Float.valueOf(String) Long.valueOf(String)

byte or Byte char or Character double or Double

int or Integer float or Float

long or Long

Example: <jsp:setProperty name="user" property="*" /> <jsp:setProperty name="user" property="modDate" value="<%= new java.util.Date( ) %>" /> A.3.9 <jsp:useBean> The <jsp:useBean> action associates a Java bean with a name in one of the JSP scopes and also makes it available as a scripting variable. An attempt is first made to find a bean with the specified name in the specified scope. If it's not found, a new instance of the specified class is created. The attributes described in Table A.11 are supported.

Table A.11, <jsp:useBean> Attributes Attribute Name beanName class id Java Type String String String Request-Time Value Accepted Description Yes Optional. The name of the bean, as expected by the instantiate( ) method of the Beans class in the java.beans package.

No Optional. The fully qualified class name for the bean. No Mandatory. The name to assign to the bean in the specified scope, as well as the name of the scripting variable. . The default is page , request page . ,

scope

String

No Optional. The scope for the bean, one of session , or application No

type

String

Optional. The fully qualified type name for the bean (i.e., a superclass or an interface implemented by the bean's class).

Of the optional attributes, at least one of class or type must be specified. If both are specified, class be assignable to type . The beanName attribute must be combined with the type attribute, and is not valid with the class attribute. The action is processed in these steps: 1. Attempt to locate an object based on the 2. Define a scripting language variable with the given id and scope attribute values. id of the specified type or class action .

must

3. If the object is found, the variable's value is initialized with a reference to the located object, cast to the specified type or class . This completes the processing of the action. If the a nonempty body, it is ignored. 4. If the object is not found in the specified scope and neither class nor InstantiationException is thrown. This completes the processing of the action.

element has

beanName is specified, a

page 267

JavaSercer Pages
5. If the object is not found in the specified scope, and the class attribute specifies a nonabstract class with a public no-arg constructor, a new instance of the class is created and associated with the scripting variable and with the specified name in the specified scope. After this, Step 7 is performed. If the object is not found and the specified class doesn't fulfill the requirements, a InstantiationException is thrown. This completes the processing of the action. 6. If the object is not found in the specified scope and the beanName attribute is specified, the instantiate( ) method of the java.beans.Beans class is invoked, with the ClassLoader JSP implementation class instance and the beanName as arguments. If the method succeeds, the new object reference is associated with the scripting variable and with the specified name in the specified scope. After this, Step 7 is performed. 7. If the action element has a nonempty body, the body is processed. The scripting variable is initialized and available within the scope of the body. The text of the body is treated as elsewhere: any template text is passed through to the response, and scriptlets and action tags are evaluated. A common use of a nonempty body is to complete initializing the created instance; in that case, the body typically contains <jsp:setProperty> actions and scriptlets. This completes the processing of the action. Example: <jsp:useBean id="clock" class="java.util.Date" /> A.3.10 Custom Actions A custom action element can be developed by a programmer to extend the JSP language. The examples in this book use custom actions for database access, internationalization, access control, and more. They are described in Appendix C . The general syntax for custom actions is the same as for the JSP standard actions: a start tag (optionally with attributes), a body, and an end tag. Other elements and template text can be nested in the body. Here's an example: <ora:loop name="anArray" loopId="current" className="String"> <li><%= current %> </ ora:loop > The tag library containing the custom actions must be declared by the taglib directive, assigning a prefix for the custom action elements ( ora in this example) before a custom action can be used in a JSP page.

of the

A.4 Comments You can use JSP comments in JSP pages to describe what a scripting element or action is doing: <%-- This is a comment --%> All text between the start and stop tags is ignored by the JSP container and is not included in the response. The comment text can be anything except the character sequence representing the closing tag: Besides describing what's going on in the JSP page, comments can also be used to "comment out" portions of the JSP page, for instance during testing: <jsp:useBean id="user" class="com.mycompany.UserBean" /> <%-<jsp:setProperty name="user" property="*" /> <jsp:setProperty name="user" property="modDate" value="<%= new java.util.Date( ) %>" /> <% boolean isValid = user.isValid( ); %> --%> The action and scripting elements within the comment are not executed.

--%> .

page 268

JavaSercer Pages
A.5 Escape Characters Since certain character sequences are used to represent start and stop tags, you sometimes need to escape a character so the container doesn't interpret it as part of a special character sequence. In a scripting element, if you need to use the characters character with a backslash: <% String msg = "Literal %\> must be escaped"; %> To avoid the character sequence must escape the percent sign: <% template text being interpreted as the start of a scripting element, you in %> literally, you must escape the greater-than

This is template text, and <\% is not a start of a scriptlet. In an attribute value, you must use the following escapes: attr='a value with an escaped \' single quote' attr="a value with an escaped \" double quote" attr="a value with an escaped \\ backslash" attr="a value with an escaped %\> scripting end tag" attr="a value with an escaped <\% scripting start tag"

page 269

Potrebbero piacerti anche