APPENDIX A JSP Syntax Reference

THISAPPENDIX DESCRIBES the syntax for JavaServer Pages (JSP) 2.0. Dur intention is to provide you with a reference that's complete and useful but more compact than the specification. (The JSP 2.0 specification weighs in at 478 pages!)

NOTE j5P specifica tions front version 2.0 011 are avai/able by visiting http://java .sun .com/products/jsp/.

This appendix looks in turn at the following:

• Various preliminary details: The notation we use, how you specify uniform resource locators (URLs) in JSP code, and the various types ofcommenting you can use.

• The JSP directives: The page, taglib, and include directives.

• JSP scripting elements: Declarations, scriptlets, and expressions.

• JSP standard actions: The , , , , and actions.

• Tag libraries: A briefreview ofthe syntax for using tag libraries.

• Implicit objects: The implicit objects that are available within a JSP page such as request, response, session, and application. Appendix B covers these in more detail.

• Attributes:Various predefined request and application attributes that you may find useful.

363 AppendixA Preliminaries

Before getting stuck in the details, the following sections make a few miscelIa­ neous observations.

Notation

This appendix uses the following notation:

• ltalics show what you'll have to specify.

• Bold shows the default value of an attribute. Attributes with default values are optional ifyou're using the default; sometimes, where the default value is a little complicated, we use default to indicate that the default is described in the following text.

• When an attribute has a set of possible values, those are delimited by I:

import="package .dass, package . *, session="truelfalse"

URL Specifications

URLsspecified within JSP tags can be of two sorts:

• Context-relative paths start with /; the base URLis provided by theWeb appli­ cation to which the JSPpage belongs. For example, in aWeb application hosted at http://localhost:8080/begjsp-appendixA/, the URL/pageurl. jsp would be equivalenttohttp://localhost:8080/begjsp-appendixA/pageurl.jsp.

• Page-relative paths are relative to the JSP page in which they occur. Unlike context-relative paths, page-relative paths don't start with /; for instance, a page application hosted at http://localhost:808o/begjsp-appendixA/ morespecs/urlspec .jsp might give a page as subfolder/urlspec.jsp, which would be equivalent to http://localhost:808o/begjsp-appendixA/morespecs/ subfolder/urlspec.jsp.

364 JSPSyntax Reference Comments

Two sorts of comments are allowed in JSP code: JSPand HTMLcomments:

<%-- JSP comments are hidden from the final client page --%>

Remember too that within scriptlets (inside <% %» , you can use standard Java comments:

<% /* This Java comment starts with a slash asterisk, and continues until we come to a closing asterisk slash */

// Comments starting with a double slash continue to the end of the line %>

Directives

Directives are instructions to the JSP container regarding setting page properties, importing tag libraries, and including content within a JSP; because directives are instructions rather than in-out processes, they can't produce any output via the out stream.

The page Directive

The pagedirective specifies attributes for the page; all the attributes are optional, and the essential ones have default values, shown in bold:

<%@ page language="java" extends="package .dass" import="package .dass, package .*, session="trueIfalse" buffer="noneldefaultlsizekb" autoFlush="true Ifalse" isThreadSafe="truelfalse" info="Sample JSP to show tags"

365 AppendixA

isErrorPage="trueI false" errorPage="ErrorPage .jsp" contentType= "TYPEI TYPE; charset=CHARSETI text/html; charset=ISO-8859-1" pageEncoding="default" isELIgnored="trueI false" %>

Bear the following in mind when using this directive:

• The default buffer size is defined to be at least 8 kilobytes (KB) .

• The errorPage attribute contains the relative URLfor the error page to which this page should go if there's an unhandled error on this page.

• The specified error page file must declare isErrorPage="true" to have access to the Exception object.

• The contentType attribute sets the MIMEtype and the character set for the response. The default value is "t ext / html" for standard JSP pages and "text/xml " when implementing JSP documents in Extensible Markup Language (XML) format.

• The pageEncoding attribute defines the character encoding for the JSP page. The default is that specified in the contentType attribute or "150-8859-1" if none was specified there.

This is an example of the code that may be used for an error page:

<%@ page language="java" isErrorPage="true" %>

<%= exception.toString() %> cbr»

<%= exception .getMessage() %>

The page will print the error message received . 366 JSPSyntax Reference

This directive can also switch on support for scripting and EL in the JSP document, using the isELIgnored attribute, which sets Expression Language (EL) support. Settings in web. xml may influence the behavior of this attribute. For this attribute, a value of true enables support, and false disables it. The default value is true.

The taglib Directive

A tag library is a collection of tags used to extend a JSPcontainer functional model. The taglib directive defines a tag library namespace for the page, mapping the uniform resource indicator (UR!) of the tag library descriptor to a preflx that can be used to reference tags from the library on this page.

<%@ taglib ( uri="tagLibraryURI" I tagdir="tagDir" ) prefix="tagPrefix" %>

JSP content

Youcan assume that the tag library descriptor (TLD) defines a tagName element. tagdir indicates this prefix is for identifying tag extensions installed in the IWEB-INF/tagsl directory or a subdirectory. Ifa TLD is present in the specified directory, it's used. Otherwise, an implicit tag library descriptor, generated by the container, is used.A translation error must occur if the value doesn't start with IWEB-INF/tags/. A translation error must occur ifthe value doesn't point to a directory that exists. A translation error must occur if used in conjunction with the uri attribute.

The tag Directive

Youcan use most JSPdirectives in simple tag handler code files. Note that the page directive itself isn't used; instead, you use the tag directive, which may only be used in tag files. Here's the syntax:

367 AppendixA

tag_directive_attr_list ::= { display-name="display-name" } { body-content="scriptlessltagdependentlempty" } { dynamic-attributes="name" } { small-icon="small-icon" } { large-icon="large-icon" } { description="description" } { example="example" } { language="scriptingLanguage" } { import="imporUist" } { pageEncoding="peinfo" } { isELIgnored="truelfalse" }

This is an example tag directive:

<%@ tag name="msg" display-name= "Message" body-content="scriptless" dynamic-attributes="user" small-icon="/WEB-INF/small-icon.jpg" large-icon="/WEB-INF/large-icon .jpg" description="Simple usage of a tag directive" %>

The include Directive

There are two include tags: the include directive and the j sp: include action. The include directive includes a static file at translation time, adding any JSP in that file to this page for run-time processing:

<%@ include file="header .html" %>

See also the jsp:include action.

The attribute Directive

The attribute directive is analogous to the cattr.ibutes element in the TLDand allows you to declare custom action attributes. This is the syntax:

368 JSPSyntax Reference

<%@ attribute attribute_directive_attr_list %> attribute-directive--attr list ..- name= "attribute-name" { required="true Ifalse" } { fragment="truelfalse" } { rtexprvalue="truelfalse" } { type="type" } { description="description" }

The variable Directive

The variable directive is analogous to the element in the TLD and allows you to define a variable exposed by the tag handler. This is the syntax:

<%@ variable variable_directive_attr_list %> variable- directive--attr list :: = ( name -given="output-name" I ( name-from-attribute="attr-name" alias="local-name"» { variable-class="output -type" } { declare="truelfalse" } { scope= "AT_BEGINIAT_ENDINESTED"} { description="description" }

Scripting Elements

Youuse scripting elements to include snippets of Java code within a JSP:to declare variables and methods, to execute arbitrary Java code, and to display the result of Java expressions.

Declarations

The following syntax allows you to declare variables and methods for the page. These are placed in the generated servlet outside the _jspService() method; in other words, variables declared here will be instance variables of the servlet. Declarations don't produce any output. This is an example of declaring a variable:

<%1 String message; %>

369 AppendixA

The following code declares a variable and initializes it:

<% 1 String message = "variable declarared"; %>

You can define a method for use on the global page like so:

<% 1 public String showMessage() { return message; } %>

Declaration tags are mainly used in conjunction with scriptlets.

Scriptlets

Scriptlets enclose Java code (on however many lines) that's evaluated within the generated servlet's -ispServiceO method to generate dynamic content:

<% II Java code %>

Take care when using adjacent scriptlet blocks; this code:

<% if(user.isLoggedln) { %>

Hi!

<% } %> <% else { %>

Please log in first.. .

<% } %>

isn't legal because you've broken the else block into two scriptlets.

Expressions

Expressions return a value from the scripting code as aString to the page:

Hello there, <%= userName %> Good to see you .

370 JSPSyntax Reference Standard Actions

The standard actions provide various facilities for manipulating JavaBeans com­ ponents, including and forwarding control to other resources at request time and generating HTMLto use the Java plug-in.

The tag checks for an instance of a bean ofthe given class and scope. If a bean of the specified dass exists, it references it with the id; otherwise it instan­ tiates it. The bean is available within its scopewith its id attribute:

Youcan include code between the tags, as shown in the second example: this code will be run only if the tag successfully instanti­ ated the bean:

There's a lot of flexibility in specifying the type of the bean (indicated by typeSpecijication previously) .Youcan use the following:

• class="package. class"

• type="typeName"

• class="package.class" type="typeName" (and with terms reversed)

• beanName="beanName " type="typeName" (and with terms reversed) where the following is true:

371 AppendixA

• typeName is the dass of the scripting variable defined by the id attribute, that ls, the dass that the bean instance is cast to (whether the dass, a par­ ent dass, or an interface the dass implements).

• beanName is the name ofthe bean, as used in the instantiateO method of the java , beans . Beans dass.

The tag used previously sets the property of the bean refer­ enced by name using the value:

The propertyExpression can be any of the following:

• property="*"

• property="propertyName"

• property="propertyName" param="parameterName"

• property="propertyName" value="propertyValue"

where the following is true:

• The * setting tells the tag to iterate through the request parameters for the page, setting any values for properties in the bean whose names match parameter names.

• The param attribute specifies the parameter name to use in setting this property.

• The value attribute can be any run-time expression as long as it evaluates to aString.

• Omitting value and param attributes for a property assumes that the bean property and request parameter name match.

• The value attribute String can be automatically cast to boolean, byte, char, double, int, float, long, and their dass equivalents. Other casts will have to be handled explicitly in the bean's setPropeItyNameO method.

372 JSPSyntax Reference

The final bean-handling action is , which gets the named prop­ erty and outputs its value for indusion in the page as aString:

The action is used within the body of , , and to supply extra name/value parameter pairs to the induded or forwarded page. It has the following syntax::

To forward the dient request to a static resource, whether it's an HTML file, a JSP page, or a servlet dass in the same context as the page, use the following syntax::

or this syntax::

where the following is true:

• The page attribute for can be a run-time expression.

• The value attribute for can be a run-time expression.

373 AppendixA

The action indudes a static or dynamically referenced fileat run time:

or the following:

where the following is true:

• The page attribute can be the result of some run-time expression.

• The optional flush attribute determines whether the output buffer will be flushed before induding the specified resource. The default value is "false", (Note that in JSP l.l this attribute was mandatory, and the only permissible value was "true".)

• The jsp:param tag allows parameters to be appended to the original request, and if the parameter name already exists, the new parameter value takes precedence in a comma-delimited list.

The action enables the JSP to indude a bean or an applet in the dient page. It has the following syntax:

374 JSPSyntax Reference

vspace="topBottomPixels" title="title" jreversion="1.2Inumber" nsp1uginurl="pluginURL" iep1uginur1="pluginURL " mayscript="truelfa1se"> Prob1em with p1ugin

Most of these attributes are direct from the HTMLspecification (http:// www.w3 .org/TR/htm141); the exceptions are type, jreversion, nspluginurl, and iepluginurl:

• The name, archive, align, height, width, hspace, vspace, jreversion, nspluginurl, and iepluginurl attributes are optional.

• The tag's value attribute can take a run-time expression.

• The jreversion is the Java Runtime Environment specification version that the component requires.

• nspluginurl and iepluginurl are the URLswhere the Java plug-in can be downloaded for Netscape Navigator and Internet Explorer.

jsp:fallback can occur only as a direct child ofthe element. Using the jsp:fallback element in any other context will result in a translation­ time error. The element indicates the content to be used bythe dient browser ifthe plug-in can't be started.

The action dynamically defines the value of the tag of an XML ele­ ment. This action can be used in JSP pages, tag files, and JSP documents. This action can have the and actions as its body. They're optional:

jsp:attribute* jsp:body?

375 AppendixA

The action has two uses: The page author can define an action's attribute in the body of an XML element instead of in the attribute of the open­ ing tag. It also allows the page author to specify the attributes of the element when used inside a action (see the previous section) . This action may only appear as a subelement of standard and custom actions:

Matthew Moodie

If one or more of these actions are used, the body of the tag can be specified onlywith a action. Ifthis is omitted, then the body ofthe tag is empty.

The body of an action is normally defined as the body of the tag. Then you can also define the body of an action using the standard action. This is required if one or more elements appear in the body ofthe tag.

The standard action can be used only in tag files. It takes the name of a fragment and invokes the fragment, sending the output of the result to the JspWriter or to a scoped attribute. If the fragment identified by the given name is null, will behave as though it was passed a fragment that produces no output:

fragment is the name used to identify this fragment during this tag invocation. var is the name of a scoped attribute in which to store the result of the fragment invocation, as a java.lang. String object. varReader is the name of a scoped attribute

376 JSPSyntax Reference in which to store the result of the fragment invocation, as a java. io. Reader object. scope acts as other scope attributes.

The action behaves like 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 ofthe tag, there's no name attribute for this stan­ dard action, though its other attributes are identical to .

You can use the action to enclose template data in a JSP page, a JSP document, or a tag file. It has no attributes and can appear anywhere that tem­ plate data can.

You can use only in JSP documents and in tag files in XML syntax. It's used to modify properties of the output of a JSP document or a tag file. In JSP 2.0 there are four properties that can be specified, all of which affect the output ofthe XML prolog:

doctypeDecl :: = ( doctype-root-element="rootElement" doctype-public="PubidLiteral" doctype-system="SystemLiteral" ) I ( doctype-root-element="rootElement" doctype-system="SystemLiteral" )

can appear only as the root element in a JSP document or in a tag file in XMLsyntax. However, they don't need a element as their root element; there are two reasons for using : indicatingXML content and accommo­ dating the generation of content that isn't a single XMLdocument. This element has a mandatory version attribute indicating which version of JSP the page is using. It can have any number of xmlns attributes:

body 377 AppendixA

You use to declare scripting language constructs that are avail­ able to all other scripting elements. It has no attributes, and its body is the declaration itself:

Date now = new Date()j

cjsp:scriptlet>

has no attributes, and its body is the scriptlet. It's used on XML JSP pages to include scriptlets:

out.print("Hello, world"};

has no attributes, and its body is the expression:

session.getAttribute("user")j

Tag Libraries

The syntax for using tag libraries is similar to that for the standard actions except of course that the tag names and attributes are defined in the tag library itself rather than by the JSP standard. Each tag library is associated with aprefix by using the taglib directive to map the prefix to a UR1 identifying the tag library. For example, using the Jakarta Taglibs project's request tag library (http ://jakarta•apache .org/ taglibs/doc/request-doc/intro.html) looks like this:

<%@ taglib uri=''http ://jakarta.apache.org/taglibs/request-l.o'' prefix="req" %>

Within the JSP, you can then use tags from the library by using the prefix defined in the taglib directive and the tag's name. For example:

Name : Value:

378 JSPSyntax Reference

Youcan set up the mapping between a partieular URI (as used in the taglib directive) and the tag library descriptor in one oftwo ways. In JSP, it's possible to package tag libraries so that the mapping is automatie, based on settings con­ tained in the tag library descriptor file. Alternatively, you can make an entry in the web. xml file to map a URI to a tag library descriptor file:

http://jakarta.apache.org/taglibs/request-1.o /WEB-INF/request.tld

Implicit Objects

JSP defines a number of implicit objects that JSP scripting elements can use:

• request,oftypejavax.servlet.http.HttpServletRequest

• response, of type javax. servlet.http.HttpServletResponse

• out, oftype javax.servlet.jsp.JspWriter

• session, oftype javax.servlet.http.HttpSession

• application, oftype javax. servlet.ServletContext

• exception, of type java .lang.Throwable

• config, of type javax. servlet.ServletConfig

• page, a reference to the implementing servlet dass for the JSP

• pageContext, oftype javax.servlet.jsp.PageContext

Appendix B gives details of these objects and the methods that each makes available. The JSP and servlet specifications define many more classes and inter­ faces; to find out more about them, you should consult the online documentation as described in Appendix D.

379 APPENDIX B JSP Implicit Objects

THE }AVASERVER PAGES (JSP) TECHNOLOGY defines a number of impIicit objects that scripting elements can use. This appendix gives details of these objects and the methods that each of them exposes. The JSP and servlet specifications define many more classes and interfaces; to find out more about them, you should con­ sult the onIine documentation as described in Appendix D.

NOTE This appendix lists all th e m ethods auailable for each object (except those defin ed in java.lang.Object), irrespective 0/tulrich d ass or interface defines the methods.

The impIicit objects are as follows:

• request

• response

• out

• session

• application

• exception

• config

• page

• pageContext

381 AppendixB The request Object

The request object is an instance of a dass that implements the javax.servlet.http.HttpServletRequest interface.1t represents the request made by the dient and makes the following methods available. getAttributeO returns the value ofthe specified request attribute name. The return value is an Object or sub dass if the attribute is available to the invoking ServletRequest object or null ifthe attribute isn't available:

public Object getAttribute(String name)

getAttributeNamesO returns an Enumeration containing the attribute names available to the invoking ServletRequest object:

public java.util.Enumeration getAttributeNames()

getAuthTypeO returns the name ofthe authentication scheme used in the request or null if no authentication scheme was used. 1treturns one of the con­ stants BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, or DIGEST_AUTH, or it returns null if the request wasn't authenticated:

public String getAuthType()

getCharacterEncodingO returns aString object containing the character encoding used in the body of the request or null if there's no encoding:

public String getCharacterEncoding()

getContentLengthO returns the length ofthe body ofthe request in bytes or - 1 ifthe length isn't known:

public int getContentLength()

getContentType() returns aString object containing the Multipurpose Internet Mail Extensions (MIME) type ("text/plain", "t ext / ht ml", "image/gif", etc.) ofthe body of the request or null if the type isn't known:

public String getContentType()

getContextPath() returns the part ofthe request uniform resource indicator (UR!) that indicates the context path of the request. The context path is the first part of the URI and always begins with the I character. For servlets running in the root context, this method returns an empty String. For example, ifthere's an incoming request from request http://localhost/guide/suburbs/index.jsp, then getContextPathO would return "/gui de": 382 JSP Implicit Objects public String getContextPath()

getCookies() returns an array containing any Cookieobjects sent with the request or null if no cookies were sent: public Cookie[] getCookies()

getDateHeaderO returns a long value that represents the date specified in the named header and is the number ofmilliseconds since January 1,1970, Greenwich mean time (GMT).This method is used with a header that contains a date, and it returns -1 ifthe request doesn't contain the specified header: public long getDateHeader(String name)

getHeaderO returns the value ofthe specified header expressed as aString object or null if the request doesn't contain the specified header: public String getHeader(String name)

The following is an example Hypertext Transfer Protocol (HTTP) request:

GET /search ?index=servlets+jsp HTTP/1.1 Accept : image/gif, image/jpg, */* Accept-Encoding : gzip Connection: Keep-Alive Cookie: userID=id66589 Host : www .mycompany .com Referer: http://www.mycompany.com/getproducts.html User-Agent : Mozilla/4.6 [en] (WinXPj U)

For example, ifthe usage is getRequest("Connection"), it'd return "Keep-Alive". getHeaderNames () returns an Enumeration containing all of the header names used by the request: public java.util.Enumeration getHeaderNames()

getHeaders() returns an Enumeration containing all of the values associated with the specified header name. The method returns an empty enumeration if the request doesn't contain the specified header: public java.util.Enumeration getHeaders(String name)

getInputstreamO returns a serv1etInputstream object that can be used to read the body of the request as binary data:

383 AppendixB

public ServletlnputStream getlnputStream() throws java.io .IOException

getIntHeaderO returns the value ofthe specified header as an int. It returns -1 ifthe request doesn't contain the specified header, and it throws a NumberFormatException if the header value can't be converted to an int. This method was made for convenience when the header type is known to be an integer; this way it can be absorbed by the code without any conversion:

public int getlntHeader(String name)

getLocalAddrO returns the Internet Protocol (IP) address of the server where the request was received :

public String getLocalAddr()

getLocaleO returns the preferred Iocale ofthe dient that made the request:

public java.util.Locale getLocale()

getLocalesO returns an Enumeration containing, in descending order ofpref­ erence, the Iocales that are acceptable to the dient machine:

public java.util.Enumeration getLocales()

getLocalNameO returns the hostname ofthe server where the request was received:

public String getLocalName()

getLocalPortO returns the port on the server where the request was received:

public int getLocalPort()

getMethod () returns the name of the HTTP method used to make the request. Typical return values are "GET", "POST", or "PUT" :

public String getMethod()

getParameter() returns aString object containing the value of the specified parameter or null if the parameter doesn't exist:

public String getParameter(String name)

384 JSP Implicit Objects

getParameterMapO returns a Map containing the request parameters: public java.util.Map getParameterMap()

getParameterNamesO returns a Enumeration containing the parameters con­ tained within the invoking ServletRequest object: public java.util.Enumeration getParameterNames()

getParameterValues () is used when a parameter may have more than one value associated with it. The method returns aString array containing the val­ ues ofthe specified parameter or null if the parameter doesn't exist : public string[] getParameterValues(string name)

getPathlnfoO returns any additional path information contained in the request uniform resource locator (URL). This extra information will be after the servlet path and before the query string. It returns null ifthere's no additional path information. For example, in the incoming request from http://localhosti innersuburbs/, getPathlnfo() would return"linnersuburbs": public string getPathlnfo()

getPathTranslatedO returns the same information as the getPathlnfoO method, but translated into areal path: public string getPathTranslated()

getProtocol() returns the name and version ofthe protocol used by the request.A typical return string would be "HTIP/1.1": public string getProtocol()

getquerystrfngf) returns the query string that was contained in the request URLwithout any decoding from the container or null if there was no query string: public string getQueryString()

getReaderO returns a BufferedReader object that can be used to read the body of the request as character data: public java .io.BufferedReader getReader() throws java .io.IOException

385 AppendixB

getRemoteAddrO returns aString object containing the IP address ofthe dient machine that made the request:

public string getRemoteAddr()

getRemoteHostO returns aString object containing the name ofthe dient machine or the IP address if the name can't be determined:

public string getRemoteHost()

getRemotePortO returns the port number ofthe dient or last proxy that sent the request:

public int getRemotePort()

getRemoteUserO returns the login ofthe user making the request or null if the user hasn't been authenticated:

public string getRemoteUser()

getRequestDispatcherO returns aRequestDispatcher object that acts as a wrapper around the resource located at the specified path. The path must begin with / and can be a relative path:

public RequestDispatcher getRequestDispatcher(string path)

getRequestedsessionldO returns the session ID that was specified by the dient or null if the request didn't specify an ID:

public string getRequestedSessionld()

getRequestURIO returns a subsection ofthe request URL, from the protocol name to the start ofthe query string (the query string isn't included):

public string getRequestURI()

getRequestURLO reconstructs the URLused to make the request including the protocol, server name, port number, and path, but excluding the query string:

public StringBuffer getRequestURL()

getschemeO returns the scheme ("http", "https", "ftp", and so on) used to make the request:

public String getScheme() 386 JSP Implicit Objects

getServerNameO returns aString object containing the name ofthe server that received the request: public String getServerName()

getServerPort() returns the port number that received the request: public int getServerPort()

getServletPathO returns the part ofthe request URLthat was used to call the servlet, without any additional information or the query string: public String getServletPath()

getSessionO returns the HttpSession object associated with the request. By default, if the request doesn't currently have a session, calling this method will create one. Setting the booleanparameter create to false overrides this: public HttpSession getSession(boolean create) public HttpSession getSession()

getUserPrincipalO returns a java.security. Principal object containing the name of the current authenticated user. If the user hasn't been authenticated, the method returns null: public java.security.Principal getUserPrincipal()

isRequestedSessionldFromCookieO returns true ifthe session ID came in from a cookie: public boolean isRequestedSessionldFromCookie()

isRequestedSessionldFromURLO returns true ifthe session ID came in as part of the request URL: public boolean isRequestedSessionldFromURL()

isRequestedSessionldValidO returns true ifthe session ID requested by the dient is still valid: public boolean isRequestedSessionldValid()

isSecureO returns true ifthe request was made using a secure channel, for example, HTTPS: public boolean isSecure() 387 AppendixB

isUserInRoleO returns true ifthe authenticated user has the specified Iogical role or false ifthe user isn't authenticated:

public boolean isUserlnRole(String role)

removeAttributeO makes the specified attribute unavailable to the invoking ServletRequest object. Subsequent calls to the getAttributeO method for this attribute will return null:

public void removeAttribute(String name)

setAttributeO binds a value to a specified attribute name. Note that attrib­ utes will be reset after the request is handIed:

public void setAttribute(String name, Object 0)

setCharacterEncodingO overrides the character encoding used in the body of this request:

public void setCharacterEncoding(String env) throws java .io.UnsupportedEncodingException

The following String constants are used to identify the different types of authentication that may have been used to protect the servlet. They have the values BASIC, FORM, CLIENT_CERT, and DIGEST, respectively:

public static final String BASIC_AUTH public static final String FORM_AUTH public static final String ClIENT_CERT_AUTH public static final String DIGEST_AUTH

These methods are deprecated and shouldn't be used in new code-they exist for compatibilitywith existing code:

public String getRealPath(String path) public boolean isRequestedSessionldFromUrl()

Use ServletContext.getRealPath(java .lang.String) instead of getRealPath (String path), and use ServletContext.isRequestedSessionIdFromURlO insteadofisRequestedSessionIdFromUrl().

388 JSP Implicit Objects The response Object

The response object is an instance of a dass that implements the j avax.servlet.http. HttpServletResponse interface. It represents the response to be made to the dient, and it makes the following methods available. addCookieO adds the specified cookie to the response (you can add more than one cookie): public void addCookie(Cookie cookie)

addDateHeaderO adds a response header containing the specified header name and the number of milliseconds since Ianuary 1, 1970, GMT.Youcan use this method to assign multiple values to a given header name: public void addDateHeader(String name, long date)

addHeaderO adds a response headerwith the specified name and value.You can use this method to assign multiple values to a given header name: public void addHeader(String name, String value)

addlntHeader() adds a response header with the specified name and int value. This method can assign multiple values to a given header name: public void addlntHeader(String name, int value)

containsHeaderO returns true ifthe response header includes the specified header name.Youcan use this method before calling one ofthe sett) methods to determine if the header value has already been set: public boolean containsHeader(String name)

encodeRedirectURLO encodes the specified URLor returns it unchanged if encoding isn't required. This method is used to process a URLbefore sending it to the sendRedirectO method: public String encodeRedirectURL(String url)

encodeURLO encodes the specified URLby including the session ID or returns it unchanged if encoding isn't needed. AllURLsgenerated by a servlet should be

389 AppendixB

processed through this method to ensure compatibility with browsers that don't support cookies:

public String encodeURL(String url)

flushBufferO causes any content stored in the buffer to be written to the dient. Calling this method will also commit the response, meaning that the sta­ tus code and headers will be written:

public void flushBuffer() throws java.io .10Exception

getBufferSize () returns the buffer size used for the response or 0 if no buffering is used:

public int getBufferSize()

getCharacterEncodingO returns aString object containing the character

encoding used in the body ofthe response. The default is "1SO-8859-1" I which corresponds to Latin-I:

public String getCharacterEncoding()

getContentTypeO returns the MIMEtype ofthis response. The content type must have been set using setContentTypeO for this method to return a value; if no content type has been specified, this method returns null. If character encod­ ing has been specified, the charset parameter is included in the return value. If no character encoding has been specified, the charset parameter is omitted:

public String getContentType()

getLocaleO returns the locale that has been assigned to the response. By default, this will be the default locale for the server:

public java.util.Locale getLocale()

getOutputStreamO returns an object ServletOutputStreamobject that can be used to write the response as binary data:

public ServletOutputStream getOutputStream() throws java.io.10Exception

390 JSP Implicit Objects

getWriterO returns a PrintWriter object that can be used to write the response as character data: pub1ic java.io.PrintWriter getWriter() throws java.io.IOException

isCommitted() returns true ifthe response has been committed, meaning that the status code and headers have been written: pub1ic boo1ean isCommitted()

resett) clears the status code and headers and any data that exists in the buffer. Ifthe response has already been committed, calling this method will cause an exception to be thrown: pub1ic void reset() throws java.1ang.I11ega1StateException

resetBufferO clears the content ofthe response buffer without clearing the headers or status code. It will throw an IllegalStateException ifthe response has been committed: pub1ic void resetBuffer()

sendErrorO sends an error response back to the dient machine using the specified error status code. You can also provide a descriptive message. This method must be called before the response is committed (in other words, before the status code and headers have been written): pub1ic void sendError(int sc, String msg) throws java.io.IOException pub1ic void sendError(int sc) throws java.io.IOException

sendRedirectO redirects the dient machine to the specified URL. This method must be called before the response is committed (in other words, before sending it to the dient): pub1ic void sendRedirect(String loeation) throws java.io.IOException

391 AppendixB

setBufferSizeO requests a buffer size to be used for the response. The aetual buffer size will be at least this large:

public void setBufferSize(int size)

setCharacterEncodingO sets the MIME eharset ofthe response. It overrides any previous eharset setting, no matter how it was applied:

public void setCharacterEncoding(String charset)

setContentLengthOsets the length ofresponse body:

public void setContentLength(int len)

setContentTypeO sets the eontent type ofthe response sent to the server. The String argument specifies a MIMEtype and may also include the type of eharae­ ter eneoding, for example, "text/plain: charset=ISO-8859-1 ":

public void setContentType(String type)

setDateHeaderO sets the time value of a response header for the specified header name. The time is the number of milliseeonds sinee Ianuary 1, 1970,GMT. If the time value for the specified header has been previously set, the value passed to this method will override it:

public void setDateHeader(String name, long date)

setHeaderO sets a response headerwith the specified name and value. Ifthe value for the specified header has been previously set, the value passed to this method will override it:

public void setHeader(String name, String value)

setIntHeaderO sets a response header with the specified name and int value. If the int value for the specified header has been previously set, the value passed to this method will override it:

public void setlntHeader(String name, int value)

setLocaleO specifies the loeale that will be used for the response:

public void setLocale(java.util.Locale loe) 392 JSP Implicit Objects

setStatusO sets the status code and should be one of SC_ACCEPTED, SC_OK, SC_CONTINUE, SC_PARTIAL_CONTENT, SC_CREATED, SC_SWITCHING_PROTOCOLS,or SC NO CONTE NT: public void setStatus(int sc)

The following constants represent the status codes defined in the HTTP specification (visit http://www.w3 .org/TR/htm14011 for more information): public static final int SC_CONTINUE public static final int SC_SWITCHING_PROTOCOLS public static final int SC_OK public static final int SC_CREATED public static final int SC_FOUND public static final int SC_ACCEPTED public static final int SC_NON_AUTHORITATIVE_INFORMATION public static final int SC_NO_CONTENT public static final int SC_RESET_CONTENT public static final int SC_PARTIAL_CONTENT public static final int SC_MULTIPLE_CHOICES public static final int SC_MOVED_PERMANENTLY public static final int SC_MOVED_TEMPORARILY public static final int SC_SEE_OTHER public static final int SC_NOT_MODIFIED public static final int SC_USE_PROXY public static final int SC_BAD_REQUEST public static final int SC_UNAUTHORIZED public static final int SC_PAYMENT_REQUIRED public static final int SC_FORBIDDEN public static final int SC_NOT_FOUND public static final int SC_METHOD_NOT_ALLOWED public static final int SC_NOT_ACCEPTABLE public static final int SC_PROXY_AUTHENTICATION_REQUIRED public static final int SC_REQUEST_TIMEOUT public static final int SC_CONFLICT public static final int SC_GONE public static final int SC_LENGTH_REQUIRED public static final int SC_PRECONDITION_FAILED public static final int SC_REQUEST_ENTITY_TOO_LARGE public static final int SC_REQUEST_URI_TOO_LONG public static final int SC_UNSUPPORTED_MEDIA_TYPE public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE public static final int SC_EXPECTATION_FAILED 393 AppendixB

public static final int SC_INTERNAl_SERVER_ERROR public static final int SC_NOT_IMPlEMENTED public static final int SC_BAD_GATEWAY public static final int SC_SERVICE_UNAVAIlABlE public static final int SC_GATEWAY_TIMEOUT public static final int SC_HTTP_VERSION_NOT_SUPPORTED public static final int SC_TEMPORARY_REDIRECT

These methods are deprecated and shouldn't be used in new code-they exist for compatibilitywith existing code:

public String encodeUrl(String url) public String encodeRedirectUrl(String url) public void setStatus(int sc, String sm)

The out Object

The out object is an instance ofthe javax.servlet.jsp.JspWriter dass. It's used to create the content returned to the dient and has the following useful methods available. clear() clears the contents ofthe buffer; it throws an exception if some data has already been written to the output stream:

public abstract void clear() throws java .io.IOException

clearBufferO clears the contents ofthe buffer but doesn't throw an excep­ tion if some data has already been written to the output stream:

public abstract void clearBuffer() throws java .io.IOException

close() flushes and then closes the output stream:

public abstract void close() throws java.io.IOException

flush() flushes the output buffer and sends any bytes contained in the buffer to their intended destination. flushf) will flush all the buffers in a chain ofWriters and OutputStreams:

394 JSP Implicit Objects public abstract void flush() throws java.io.IOException

getBufferSizeO returns the size in bytes ofthe output buffer: public int getBufferSize()

getRemainingO returns the number ofbytes still contained in the buffer. It will return 0 if it's unbuffered: public abstract int getRemaining()

iSÄutoFlushO returns true ifthe buffer flushes automaticallywhen an over­ flow condition occurs: public boolean isAutoFlush()

newLineO writes a new Unecharacter to the output stream: public abstract void newLine() throws java.io.IOException

printO prints the specified primitive data type, Object, or String to the dient: public abstract void print(boolean b) throws java.io.IOException public abstract void print(char ) throws java.io.IOException public abstract void print(int i) throws java.io.IOException public abstract void print(long 1) throws java.io.IOException public abstract void print(float f) throws java.io.IOException public abstract void print(double d) throws java.io.IOException public abstract void print(char[] 5) throws java.io.IOException public abstract void print(String 5) throws java.io.IOException public abstract void print(Object obj) throws java.io.IOException

395 AppendixB

Here's an example:

<% try { boolean b = false; out.print(b);

} catch(java.io.IOException ioe) { IICatch error. } %>

The previous will printfalse in the browser window. printlnO prints the specified primitive data type, Object, or String to the dient, followed by a new line character at the end. The no-argument version simply writes a new line character:

public abstract void println() throws java.io.IOException public abstract void println(boolean x) throws java.io .IOException public abstract void println(char x) throws java.io .IOException public abstract void println(int x) throws java.io.IOException public abstract void println(long x) throws java.io.IOException public abstract void println(float x) throws java.io.IOException public abstract void println(double x) throws java.io.IOException public abstract void println(char[] x) throws java.io .IOException public abstract void println(String x) throws java.io .IOException public abstract void println(Object x) throws java.io .IOException

For example:

<% try {

396 JSP Implicit Objects

out. println("Page Title") j } catch(java.io.IOException ioe) { //Catch error. } %>

The session Object

The session object is an instance of a dass that implements the javax.servlet.http.HttpSession interface.Youcan use it to store session state for auser, and it makes the following methods available. getAttributeO returns the Object bound to the specified name in this session or null if it doesn't exist: public Object getAttribute(String name)

getAttributeNames() returns an Enumeration of String objects containing the names of all the objects bound to this session: public java.util.Enumeration getAttributeNames()

getCreationTimeO returns the time when the session was created in milli­ seconds since midnight Ianuary 1, 2003, GMT: public long getCreationTime()

getIdO returns aString object containing a unique identifier for this session: public String getId()

getLastAccessedTimeO returns the last time a dient request associated with the session was sent. The return value is the number of milliseconds since mid­ night Ianuary 1, 1970, GMT: public long getLastAccessedTime()

getMaxInactiveInterva10 returns the number of seconds the server will wait between dient requests before the session is invalidated. A negative return value indicates that the session will never time out: public int getMaxInactiveInterva1()

397 AppendixB

getServletContext() returns the ServletContext ofthis session:

public ServletContext getServletContext()

invalidateO invalidates the session and unbinds any objects bound to it:

public void invalidate()

isNew() returns true if the server has created a session that hasn't yet been accessed by a dient:

public boolean isNew()

removeAttributeO removes the Object bound to the specified name from this session:

public void removeAttribute(String name)

setAttributeO binds an Object to the specified attribute name in this session. Ifthe attribute name alreadyexists, the Object passed to this method will replace the previous Object:

public void setAttribute(String name, Object value)

setMaxlnactivelnterval0 specifies the number of seconds the server will wait between dient requests before the session is invalidated. If a negative value is passed to this method, the session will never time out:

public void setMaxlnactivelnterval(int interval)

These methods are deprecated and shouldn't be used in new code-they exist for compatibility with existing code:

public HttpSessionContext getSessionContext() public Object getValue(String name) public String[] getValueNames() public void putValue(String name, Object value) public void removeValue(String name)

398 JSP Implicit Objects The application Object

The application object is an instance of a dass that implements the javax.servlet.ServletContext interface, and it allows the page to obtain and to set data information about theWeb application in which it's running. It makes available the following methods. getAttributeO returns the value ofthe specified attribute name. The return value is an Object or subdass ifthe attribute is available to the invoking ServletContext object or null ifthe attribute isn't available: public Object getAttribute(String name)

getAttributeNamesO returns an Enumeration containing the attribute names available to the invoking ServletContext object: public java.util.Enumeration getAttributeNames()

getContextO returns the ServletContext object for the resource at the speci­ fied path on the server. The path argument is an absolute URL beginning with /: public ServletContext getContext(String uripath)

getInitParameterO returns aString object containing the value ofthe speci­ fied initialization parameter or null ifthe parameter doesn't exist: public String getlnitParameter(String name)

getInitParameterNamesO returns a Enumeration containing the initialization parameters associated with the invoking ServletContext object: public java.util.Enumeration getlnitParameterNames()

getMajorVersion 0 returns the major version of the Java servlet API that the server supports. For servers supporting version 2.3 of the servlet specification, this method will return 2: public int getMajorVersion()

getMimeTypeO returns the MIME type ofthe specified file or null ifthe MIME type can't be ascertained. Typical return values will be "text/plain", "text/html", and "image/jpg": public String getMimeType(String file)

399 AppendixB

getMinorVersion () returns the minor version of the Java servlet API that the server supports. For servers supporting version 2.3 of the servlet specification, this method will return 3:

public int getMinorVersion()

getNamedDispatcherO returns aRequestDispatcher object that will be wrapped around the named servlet:

public RequestDispatcher getNamedDispatcher(String name)

getRealPathO returns aString object containing the real path, in a form appropriate to the platform on which the servlet is running, corresponding to the given virtual path. An example of a virtual path might be "/blah.html":

public String getRealPath(String path)

getRequestDispatcherO returns aRequestDispatcher object that acts as a wrap­ per around the resource located at the specified path. The path must begin with / and is interpreted relative to the current context root:

public RequestDispatcher getRequestDispatcher(String path)

getResourceO returns a URL object that's mapped to the specified path or null if there's no resource mapped to the path. The path must begin with / and is interpreted relative to the current context root:

public java.net.URL getResource(String path) throws java.net.MalformedURLException

getResourceAsStreamO returns the resource at the specified path as an InputStream object:

public java.io.lnputStream getResourceAsStream(String path)

getResourcePaths0 returns all the paths to resources held in theWeb appli­ cation as String objects beginning with a /:

public java.util.Set getResourcePaths()

getServerlnfo() returns aString object containing information about the server on which the servlet is running. At aminimum, the String will contain the servlet container name and version number:

400 JSP Implicit Objects pub1ic String getServerlnfo()

The following will display Apache Tomcat/5.0.16 for Tomcat 5.0.16:

<% out.print(app1ication.getServerlnfo()) ; %>

getServ1etContextNameO returns the name oftheWeb application, as speci­ fied in the element in web.xml: public String getServ1etContextName()

Iogf) is used to write a message to the servlet engine's log file.The second version writes both an explanatory message and a stack trace for the specified Throwable exception to the log file: public void log(String msg) pub1ic void log(String message, Throwable throwable)

removeAttributeO makes the specified attribute unavailable to the invoking ServletContext object. Subsequent calls to the getAttributeO method for this attribute will return null : pub1ic void removeAttribute(String name)

setAttributeO binds a value to a specified attribute name: pub1ic void setAttribute(String name, Object object)

These methods are deprecated and shouldn't be used in new code-they exist for compatibility with existing code: pub1ic Serv1et getServ1et(String name) throws Serv1etException pub1ic java.uti1.Enumeration getServ1etNames() pub1ic java.uti1.Enumeration getServ1ets() pub1ic void log(Exception exception, String msg)

401 AppendixB The exception Object

The exception object is an instance ofthe java.lang.Throwable dass. It's available in error pages only, and it represents the exception that occurred that caused contral to pass to the error page. Its most useful methods are as follows. getLocalizedMessageO returns a localized description ofthis Throwable object. In many cases, this will return the same result as getMessageO :

public String getlocalizedMessage()

getMessageO returns the errar message string ofthis Throwable object:

public String getMessage()

printStackTrace() prints information about this Throwable object, along with a listing of the method calls that led to the error condition arising. The output can be directed to the standard errar stream or to a specified PrintStreamor PrintWriter object:

public void printStackTrace() public void printstackTrace(PrintStream ps) public void printStackTrace(PrintWriter pw)

toStringO returns a short description ofthis Throwable object:

public String toString()

If an error message was supplied when the object was created, the result is the Throwable class's name, followed by a colon and aspace, followed by that message. For example, the following:

<% try { throw new Exception ("Here' 5 my Exception") j } catch(Exception e) { out.print(e.toString(»j } %>

outputs the following:java.lang.Exception:Here's my Exception.

402 JSP Implicit Objects The config Object

The config object is an instance of the j avax. servlet. ServletConfig interface. Youcan use it to make initialization parameters available, and it has the follow­ ing methods. getInitParameterO returns the value ofthe specified initialization parameter or null if the parameter doesn't exist: public String getlnitParameter(String name)

getInitParameterNames () returns an Enumeration of String objects containing the names of all of the servlet's initialization parameters: public java .util.Enumeration getlnitParameterNames()

getServletContextO returns the ServletContext object associated with the invoking servlet. A ServletContext object contains information about the envi­ ronment in which the servlet is running: public ServletContext getServletContext()

getServletNameO returns the name ofthe servlet. Ifthe servlet is unnamed, the method will return the servlet's dass name: public String getServletName()

The page Object

The page object is a reference to the servlet object that implements this JSP page. JSPpage authors don't often use this object because it's very expensive memory-wise.

The pageContext Object

The pageContext object is an instance ofthe javax.servlet.jsp.PageContext dass and is used by the container-generated servlet code for your JSPpage to access the various scopes available within the JSP page. JSP page authors don't often use this object because they were intended to be generated by the container, but it's important when writing tag libraries:

<% HttpSession thisSession = pageContext.getSession()j %>

403 APPENDIX C XML Configuration Files

THIS APPENDIX DOCUMENTS in detail the three most commonly used Extensible Markup Language (XML) configuration files in JavaServer Pages (JSP) applications:

TheWeb application deployment descriptor IDe (web.xml): This is a configuration file used by servlet containers that meet the Java 2 Enterprise Edition (J2EE) specification, such as Apache Tomcat. The servlet container reads this file on startup. This file is placed in the WEB -INF folder ofyourWeb application.

Tag Iibrarydescriptor (.tld) flles: This is adescriptor file for a tag library. This file describes the tag library implementation contained in a Java Archive (JAR) file to the servlet container. This file too is generally stored in the WEB-INF folder of yourWeb application.

The Struts configuration IDe (struts-config.xml): This file configures Web applications based on the Struts framework, discussed in Chapter 10. The Struts framework is an open-source Model-View-Controller (MVC) implementation using JSP servlet technology.

Common Elements of web .xml

The cdescrdptior», , and «icor» elements can occur in several places as subelements of other elements within web.xml.

The element appears in a number of places within the web. xml file to provide a description of its parent element.

The element contains a short name for its parent element and is displayed by graphical user interface (GUn tools.

405 AppendixC

dcon>

The «lcor» element referenees icons that will be used by a GUl tool to represent its parent element. It contains the following:

• An optional element eontaining the loeation within the applieation ofa 16X16 pixel ieon

• An optional <1arge-icor» element eontaining the loeation within the applieation ofa 32X32 pixel icon

: Root Element

The element is the root element ofthe web.xm1 file, This means that every web. xml flle must eontain one and only one such element, and all other elements must be eontained within it. It eontains the following:

• An optional «icor» element

• An optional element

• An optional element

• An optional element

• Zero or more ccontext-parae» elements

• Zero or more dilter> elements

• Zero or more dilter-mapping> elements

• Zero or more <1istener> elements

• Zero or more elements

• Zero or more elements

• An optional element

• Zero or more elements

406 XMLConfiguration Files

• An optional element

• Zero or more cerror-pages elements

• Zero or more elements

• Zero or more cresource-env-ref» elements

• Zero or more cresource-ref» elements

• Zero or more elements

• An optional <1ogin-config> element

• Zero or more elements

• Zero or more elements

• Zero or more cejb-refo elements

• Zero or more elements

• Zero or more cservtce-refo elements

• Zero or more elements

• Zero or more elements

• Zero or more <1ocal-encoding-mapping-list> elements

Child Elements of

The following sections cover the permissible child elements that cweb-apps may have (other than those already described).

The element, if present, declares that this Web application can be deployed in a distributed servlet container or servlet container executing across multiple Java virtual machines (NMs) running either on the same host or on dif­ ferent hosts.

407 AppendixC

The element declares a context initialization parameter. It con­ tains the following:

•A element containing the parameter's name

•A element containing the parameter's value

• An optional element (see earlier description)

The element declares a filter. Afilter is a Java class that preprocesses the request data received from clients. This preprocessing may include decryption, formatting, or other processes. This element contains the following:

• An optional cicor» element

•A element containing the filter's name

• An optional element

• An optional element

•A element containing the filter's class name

• Zero or more dnit-param> elements containing initialization parameters for the filter

Each dnit-param> element contains the following:

•A element containing the parameter name

•A cparam-values element containing the parameter value

• An optional element

Youuse the element to map a filter to a servlet or a set of uniform resource locators (URLs).It contains the following:

408 XMLConfiguration Files

•A element containing the name of a filter declared by a element

• Either a curl-patterro element containing a URLpattern to match or a element containing the name of a servlet declared by a cservlet» element

• Zero to four elements

The elements can have one ofthe followingvalues : FORWARD, REQUEST, INCLUDE, and ERROR. FORWARD applies the filter to RequestDispatcher. forward0 calls. REQUEST applies the filter to ordinary client calls to the path or servlet. INCLUDE applies the filter to RequestDispatcher. includeO calls. ERROR applies the filter to the error page mechanism. If the element is omitted, the default value is REQUEST.

<1istener>

You can use the element to declare an application listener. It contains the following:

•A element containing the listener's class name

, , and dcon> elements cservl.et»

The cservlet» element declares a servlet. It contains the following :

• An optional «icor» element.

•A element containing the servlet's name.

• An optional element.

• An optional element.

• Either a cservlet-classs element containing the listener's class name or a element containing the location within the Web application of a JSP file.

• dnit-param> elements.

409 AppendixC

• An optional <1oad-on-startup> element indicating that the servlet should be loaded when theWeb application starts up and containing an optional positiveinteger value indicating the order in which servlets should be started. Ifa was specified, then the JSP should be precompiled and loaded.

elements.

• An optional crun-ass element that specifies the identity under which the servlet should run.

Each dnit-param> element contains the following:

•A element containing the parameter name

•A element containing the parametervalue

• An optional element

A element maps a role name called from within the servlet and the name of a security role defined for the Web application. It con­ tains the following:

• An optional element

•A crole-names element containing the role name used within the servlet

• An optional element containing the name of a role defined in a element

The element maps a servlet to a URL pattern. It contains the following:

•A cservlet-name» element containing the name of a servlet declared by a element

•A element containing a URL pattern to match

410 XMLConjiguration Files

The element configures the session tracking for theWeb appli­ cation. It contains the following :

• An optional element containing the default session time­ out for this Web application, which must be a whole number of minutes. The default behavior of the containerwithout this attribute is to never time out.

The element maps a filename extension to a Multipurpose Internet Mail Extensions (MIME) type. It contains the following :

• An element containing a filename extension

•A element containing a defined MIME type

The element defines an ordered list ofwelcome files. It con­ tains the following :

• One or more elements containing a filename to use as a welcome file

The cerror-pages element maps an error code or exception type to a resource terror page) to use if that error condition arises. It contains the following :

• Either an cerror-codes element containing an HTTP error code or an element containing the dass name of a Java exception type

•A clocatior» element containing the location ofthe error page resource within the Web application

411 AppendixC

The element declares JSP eonfiguration options. lt eontains the following:

• A element eontaining tag library information

• A element for specifying properties eommon to a group of JSPs

The element eontains the following subelements:

•A element eontaining a uniform resouree indicator (UR!) to identify the tag library

•A element eontaining the loeation within theWeb appli­ eation ofthe tag library deseriptor file (.Ud file)

The element has the following subelements:

•A element specifyingwhich resourees should be eovered by this set of properties.

• An optional element that should be set to true or false. If true, then Expression Language (EL) terms are ignored.

• An optional element that specifies the page eneoding. A translation-time error will oeeur if a page direetive's pageEncoding attribute is different from the value specified in web. xml.

• An optional element that disables seripting on a page.

• An optional ds-xml> element that specifies that the pages are XML.

• Zero or more dnclude-prelude> elements that include the specified resouree at the beginning of eaeh file in this JSP group.

• Zero or more dnclude-coda> elements that include the specified resouree at the end of eaeh file in this JSPgroup.

412 XMLConjiguration Files

The element declares that the Web application references an administered object such as a Java Message Service UMS) resource destination. It contains the following:

• An optional element.

•A element containing the name ofthe resource environment.

•A element containing the type ofthe resource environment reference. J2EEWeb containers are required to support javax.jms.Topic and javax.jms.Queue

The cresource-ref» element declares that the Web application references an external resource such as a data source reference. It contains the following:

• An optional element.

•A cres-ref-name» element containing the name ofthe resource factory reference.

•A element specifying the type ofthe data source.

•A cres-auths element indicating whether the application code signs on to the resource programmatically or whether the container should sign on based on information supplied by the application deployer. Contents must be either Application or Container.

• An optional element specifying whether connections can be shared. Contents must be either Shareable (the default) or Unshareable.

413 AppendixC

The element applies security constraints to one or more collections ofWeb resources. It contains the following:

• An optional element

• One or more elements

• An optional element

• An optional element

A element identifies a set ofresources within the application; it can be qualifled by specifying particular Hypertext Transfer Protocol (HTTP) methodts) such as GET or POST. (By default, the security constraint applies to all HTTP methods.) It contains the following:

•A element containing the name oftheWeb resource collection

• An optional element

• One or more curl-patterr» elements, each containing a URLpattern to match

• Zero or more elements, each containing the name of an HTTPmethod

An element indicates that certain user roles should be permitted to access theseWeb resources. It contains the following:

• An optional element

• Zero or more crol.e-nameo elements each containing a role referenced in a element or the special name *that indicates all roles in this application

A element indicates how data transmitted between the dient and the application should be protected. It contains the following:

• An optional element

•A element, which can have one ofthe three values in Table C-l 414 XMLConjiguration Files

Table C-l. Values Value Description NONE No transport guarantee is required.

INTEGRAL The data must not be changed in transit. CONFIDENTIAL Others may not view the data en route.

<1ogin-config>

The element configures the authentication mechanism for this application. It contains the following:

• An optional element specifying the authentication mecha­ nism. It must contain the text BASIC, DIGEST, FORM, or CLIENT-CERT.

• An optional crealm-nameo element specifying the realm name for HTTP basic authorization.

• An optional dorm-login-config> element to configure form-based authen­ tication. It contains a dorm-login-page> element specifying the login page and a dorm-error-page> element specifying the error page used if login is unsuccessful.

The element declares a security role used in theWeb application's security-constraints. It contains the following:

• An optional element

•A element containing the name of the role

The element declares an application's environment entry. It contains the following:

• An optional element.

• An element containing the environment entry's name.

415 AppendixC

• An optional element containing the environment entry's value.

• An element containing the environment entry value's Iava type. Legalvalues are java .lang. Boolean, java .lang.String, java. lang. Integer, java.lang.Double, and java. lang. Float.

The cejb-ref» element declares a reference to an Enterprise Iavaßean (EIB).lt contains the following:

• An optional element

• An cejb-ref-name» element containing the Iava Naming and Directory Interface ONDI) name of the EIB

• An cejb-ref-types element containing the expected type ofthe EIB, either Entity or Session

•A chome» element containing the type (the name ofthe class) ofthe EIB's horne interface

•A element containing the type ofthe EIB'sremote interface

• An optional element specifying that this EIB reference is linked to the named EIBin the encompassing 12EE application.

Youuse to declare a reference to an EIB'slocal horne. The decla­ ration consists of the following:

• An optional element

• An cejb-ref-name» element containing the INDI name ofthe EIB

• An cejb-ref-types element containing the expected type ofthe EIB, either Entity or Session

•A element used to specify the local horne interface ofthe EIB

416 XMLConjiguration Files

•A element used to specify the local interface of the EJB

• An optional element used to specify the referenced EJB csexvice-re]»

declares reference to a Web service. It contains the following:

•A element used to specify the name oftheWeb service. This should begin with /service/.

•A element used to define the fully qualified class name of the interface on which the client depends.

• An optional element used to specify the path to a Web Service Description Language (WSDL) file.

• An optional element containing the name of a file that describes the JavaAPlfor XML-Based RPC (JAX-RPC) mapping between the Java interfaces used by the application and the WSDLdescription in the element.

• An optional used to specify theWSDLservice element.

• Zero or more elements declaring a client dependency on the container.

• Zero or more elements declaring the handler for a port component.

declares a message destination. It contains the following:

•A element used to specify the name of a message destination

contains a declaration of a message destination. It contains the following:

417 AppendixC

• A element that specifies the IDNI name of a message destination

• Aelement specifying the type ofthe destination.

• A element specifying the use ofthe message destination

• An optional element that links adestination to a message referenee or message EIß

<1ocale-encoding-mapping-list> eontains mappings between the loeale and the eneoding. It eontains the following:

• One or more <1ocale-encoding-mapping> elements used to specify a sin­ gle mapping

<1ocale-encoding-mapping> eontains the following subelements:

•A <1ocale> element used to specify the loeale

• An element used to specify the eneoding

(ommon Elements of the Tag Library Descriptor

The , , and «lcor» elements ean oeeur in several plaees in a Tag Library Deseriptor (TLD) file, and they have the same meanings deseribed for web .xml.

: Root Element

The element is the root element of a .tld file. It eontains the following:

•A element

•A cshort-name» element

• An optional element

418 XMLConjiguration Files

• An optional element

• An optional Icor» element

• An optional element

• An optional element

• Zero or more elements

• Zero or more elements

• Zero or more elements that specify tag files in this library

• Zero or more cfunctdor» elements that specify an ELfunction

• Zero or more elements that provide information about this taglib, mainly for use by tools

Child Elements of

The permissible subelements of ctaglil» are as follows.

The element contains the version number ofthe tag library.

The cjsp-versior» element contains the JSPversion that the tag library requires (1.2 by default).

The cshcrt-name» element contains a short name for the tag library.

The element contains a URI uniquely identifying the tag library.

419 AppendixC

The element defines a validator to check that a JSP page uses the tag library correctly. It contains the following:

•A element containing the name ofthe TagLibraryValidator dass

• Zero or more dnit-param> elements

An dnit-param> element defines initialization parameters for the validator and contains the following:

•A cparam-name» element containing the parameter name

•A element containing the parameter value

• An optional element

<1istener>

The element defines an event listener for theWeb application using the tag library. It contains the following:

•A element containing the name ofthe listener dass

, , and cicor» elements

The element defines a tag. It contains the following:

•A element containing the tag's name.

•A etag-elasse element containing the name ofthe tag handler dass.

• An optional element containing the name ofthe TagExtraInfo dass for the tag.

• An optional element describing the body content ofthe tag: either tagdependent, JSP, or empty.

420 XMLConjiguration Files

• An optional element.

• An optlonal c Icor» element.

• An optional element.

• Zero or more elements.

• Zero or more elements.

• An optional element specifying whether this tag sup­ ports additional attributes with dynamic names. If true, the etag-elasse must implement the j avax. servlet.j sp, tagext. DynamicAttributes interface; it defaults to false.

• An optional element that shows an example of this tag in use.

• Zero or more elements that provide information about this tag, mainly for use by tools.

A element declares that this tag defines a scripting variable. It contains the following :

• An optional element.

• Either a element containing the name ofthe scripting vari­ able or a element containing the name ofthe tag attribute that will give the scripting variable's name at runtime.

• An optional element containing the class name of the scripting variable. The default is java .Lang,String.

• An optional element whose contents indicate whether the scripting variable is to be defined; the default is true.

• An optional cscopes elementwhose contents indicate the scope of the scripting variable. Possible values are NESTED (the default) , AT_BEGIN, or AT_END.

An cattrtbutes element defines an attribute of the tag. Itcontains the following:

• An optional element.

•A cname» element containing the name of the attribute.

421 AppendixC

• An optional elementwhose contents indicate whether the attribute is required or optional. LegalvaIues are true, false (the default), yes,and no.

• An optional element whose contents indicate whether the attribute value can be a run-time expression scriptlet rather than a static value. Legal values are true, false (the default), yes, and no.

• An optional element containing the type ofthe attribute's value. (For static values, this is always java .lang. String.) This element can occur only with crtexprvalues.

• An optional element specifying whether this attribute is a frag­ ment. It can't be used with either or .

defines an action in this tag library implemented as a .tag file. It con­ tains the following:

•A cname» element uniquely identifying the action name.

•A cpat]» element specifying where to find the .tag file. This must begin with /META-INF/tags ifthe file is in a JAR. Otherwise it must begin with /WEB- INF /tags/.

• An optional element showing an example of the tag in use.

• Zero or more elements that provide information about this tag, mainly for use by tools.

You use to provide information on each ftmction in the tag library that's to be exposed to the EL.It contains the following:

•A cname» element uniquely identifying this function

•A element specifying the Java dass that defines this ftmction

•A element specifying the Java language signature of this function

422 XMLConjiguration Files

• An optional element showing an example of the tag in use

• Zero or more dunction-extension> elements that provide information about this tag, mainly for use by tools

provides information about this taglib, mainly for use by tools. They must not affect the behavior of a container.

Common Elements of the Struts Config File

Note that within the Struts configuration file the ordering of elements is signifi­ cant.Youshould additionally note the following:

• AllURLpaths are context-relative; in other words, they must start with a / and are relative to the root of theWeb application.

• In addition to the attributes listed next, all elements in the Struts configu­ ration file have an implied id attribute.

The cset-propertys, cdescr.iptioro, , cicoro, cl.arge-Icor», and elements can occur in several places within the Struts configuration file, so we'll describe them only once.

Youuse the element to configure JavaBeans components by spec­ ifyinga property name and value. It has no content but has the followingattributes:

• property specifies the name of the bean property to be set.

• value specifies the new property value in astring representation.

The element contains a description ofthe parent element.

423 AppendixC

The element contains a short name for its parent element for GUI tools to display.

dcon>

The ctcor» element references icons that will be used by a GUI tool to represent its parent element. It contains the following :

• An optional element containing the location, relative to the file, of a 16X16 pixel icon

• An optional

: Root Element

The element is the root element ofthe Struts configuration file. It contains the following :

• An optional cdata-sourcess element

• An optional cform-beanss element

• An optional element

• An optional element

• An optional element

• An optional element

• An optional element

• An optional cplug-Ir» element

and

The «Iata-sourcess element describes a set ofDataSource objects. You configure the individual DataSourceobjects through nested cdata-sources elements.

424 XMLConjiguration Files

Eaeh «iata-sources element deseribes a DataSource objeet that will be instanti­ ated, eonfigured, and made available as a servlet eontext attribute. Any objeet ean be specified as long as it implements javax,sql ,DataSource and ean be eonfigured entirely from JavaBean properties. The followingattributes are required:

• className is the eonfiguration bean for this DataSource objeet. If specified, the objeet must be a subdass of the default eonfiguration bean.

• keyis the servlet eontext attribute key under which this data souree will be stored.

• type is a fully qualified Java dass name for this DataSource objeet. The dass must implement javax.sql.DataSource, and the objeet must be eonfigurable entirely from JavaBean properties.

Several additional attributes are now depreeated (that ls, no longer reeom­ mended) beeause they applied only to the default DataSource dass. «iata-sources has an optional subelement.

and

The element deseribes a set of exeeptions that rnight be thrown by an Action objeet. You eonfigure the handling of individual exeeption types through ehild elements. An cact ior» element may override a global exeeption handler by registering a loeal exeeption handler for the same exeeption type. The element registers an ExceptionHandler for an exeeption type. The following are the important attributes:

• className is the eonfiguration bean for this ExceptionHandler objeet. If specified, className must be a sub dass ofthe default eonfiguration bean org.apache.struts.config.ExceptionConfig.

• handler is the fully qualified Java dass name for this exeeption handler (org.apache.struts.action.ExceptionHandler).

• keyis the key to use with this handler's message resouree bundle that will retrieve the error message template for this exeeption.

• path is the module-relative URI to the resouree that will eomplete the request/response ifthis exeeption oeeurs.

• scope is the eontext (request or session) to aeeess the ActionError objeet (org.apache.struts.action .ActionError) for this exeeption.

425 AppendixC

• type is the fully qualified Java dass name of the exeeption type to register with this handler.

• bundleis the resouree bundle to use with this exeeption. The default is Globals.MESSAGES KEY.

and

The cform-beans» element deseribes the set of form bean deseriptors for this appli­ eation module. An attribute ealled type is defined for this element, but this attribute is depreeated in Struts 1.0. This element has cform-bear» ehild elements that eaeh define a form bean that will be eonfigured to handle form submissions. It may have the following attributes:

• className allows you to override the default dass Struts uses to represent a form bean internally.

• name specifies a unique identifier for this form bean, which will be used to referenee it in cactior» elements. (This is required.)

• type specifies the name of the form bean dass to be used; it must extend org. apache.struts.action .ActionForm. (This is required.)

and

The element eontains zero or more ehild elements, specifying named forwards that will be available to all Struts aetions (unless over­ ridden within an element). It also has a type attribute, but this is again depreeated in Struts 1.0. The element maps a logical name to a Web resouree and has the following attributes:

• className allows you to override the default dass Struts uses to represent a forward internally. You won't eommonly use this attribute.

• name specifies a unique identifier for this forward, which will be used to referenee it within your applieation. (This is required.)

• path specifies the loeation oftheWeb resouree. (This is required.)

426 XMLConjiguration Files

• redirect allows you to specify whether control should be redirected to this resource (value true) , rather than forwarding to it (false). The default is false.

• contextrelative is set to true if, in a modular application, the path attribute starts with a slash (I) and should be considered relative to the entireWeb application rather than the module.

and

The element contains zero or more cact ior» elements, which map request URLsto Action dasses. It also has a type attribute, which represents a fully qualified Java dass to use when instantiating ActionMapping objects. Each cact äor» element maps arequest path to an Action dass. Its attributes are listed next; exactly one of forward, include, or type must be specified:

• type specifies the dass name of the action dass (which must extend org.apache.struts.action.Action) to be used to process requests for this mapping if the forward or include attribute isn't included,

• forward specifies the path of the servlet or JSPthat will process this request, instead of instantiating and calling the Action dass specified by type.

• include specifies the path ofthe servlet or JSPthat will process this request, instead of instantiating and calling the Action dass specified by type.

The remaining attributes are as follows:

• path (which is required) defines the path of the submitted request that will be processed by this action, starting with a / character. IfStruts was used with an extension-based element, then the filename extension should be omitted here.

• name specifies the name of the form bean (ifany) associated with the action.

• attribute specifies the name ofthe request-scope or session-scope attribute under which the form bean is accessed if it's something other than the bean's specified name. It's optional if name is specified but other­ wise isn't allowed.

• scopespecifies the scope (request or session) in which the form bean is located, if any. I1's optional if name is specified but otherwise isn't allowed.

427 AppendixC

• input specifies the path ofthe input form to which control should be returned if a validation error is encountered. It's required if name is specified and the input bean returns validation errors, is optional if name is specified and the input bean doesn't return validation errors, and isn't allowed if name isn't specified.

• parameter specifies configuration information for the action.

• prefix specifies aprefix used to match request parameter names to form bean properties, if any. It's optional if name is specified but otherwise isn't allowed.

• suffix specifies a sufflx used to match request parameter names to form bean properties names, if any. It's optional if name is specified but otherwise isn't allowed.

• unknown specifies whether this action should be configured to handle all requests not handled by another action.

• validate specifies whether the form bean's validateO method should be called prior to calling the action.

• className allows you to override the default dass Struts uses to represent an action mapping internally. You won't commonly use this attribute.

• roles is a comma-delimited list of roles that are allowed to access this ActionMapping.

The ccontrol.Ier» element describes the controller bean that encapsulates an application module's run-time configuration. The following attributes are defined:

• bufferSize is the size ofthe input buffer used when processing file uploads.

• className is the fully qualified Java dass name ofthe ControllerConfig sub­ dass for this controller object. If specified, the object must be a subdass of org.apache.struts.config.ControllerConfig.

• contentTypeis the default content type (and optional character encoding) to be set on each response. It may be overridden by the action, JSP page, or other resource to which the request is forwarded.

428 XMLConjiguration Files

• forwardPattern is the replacement pattern defining how the path attribute of a element is mapped to a context-relative URLwhen it starts with a slash (and when the contextRelative property is false).

NOTE forwardPattern may consist 01any com bination ofthe folloi olng: "$M ", tuhiclt m ean s it 's replaced by the module prefix 01this module; "$P", iohlch m eans it 's replaced by th e path attribute 01the selected element: and "$$", uniich causes a literaI dollar sign to be rendered. lfnot specified, Oie default forwardPattern is "$M$P ", umicli is consistent tuitli the previous beltauior offonuards.

• inputForward should be set to true for the input attribute of elements to be the name of a local or global ActionForward, which will then be used to calculate the final URL. Set this to false (the default) to treat the input para­ meter of cactior» elements as a module-relative path to the resource to be used as the input form.

• locale should be set to true for aloeale object to be stored in the user's session if not already present.

• maxFileSize is the maximum size (in bytes) of a file to be accepted as a file upload. This can be expressed as a number followed by a "K", "M", or "G", which are interpreted to mean kilobytes, megabytes, and gigabytes, respectively.

• memFileSize is the maximum size (in bytes) of a file whose contents will be retained in memory after uploading. Files larger than this threshold will be written to some alternative storage medium, typically a hard disk. This can be expressed as a number followed by a "K" , "M", or "G", which are inter­ preted to mean kilobytes, megabytes, and gigabytes, respectively.

• multipartClass is the fully qualified Java dass name of the multipart request handler dass to be used with this module.

• nocache should be set to true ifyou want the controller to add HTTP head­ ers for avoiding caching to every response from this module.

• pagePattern is the replacement pattern defining how the page attribute of custom tags are mapped to a context-relative URLofthe corresponding resource.

429 AppendixC

NOTE pagePattern may consist 0/any com bination 0/thefolloi ulng: "$M". iohich means it 's replaced by the module preflx ojthls module; "$P", tohicl: means it's replaced by the ualue 0/the pageattribute; and "$$".tuhlch causes a literal dolla r sign to be rendered.Ifnot specified, the default forwardPattern is "$M$P", uihicl; is consistent tuitlr previous behauior 0/URL eualuation for page attributes.

• processorClass is the fully qualified Java dass name ofthe RequestProcessor subdass to be used with this module.

• tempDir is the temporary working direetory to use when proeessing file uploads.

deseribes a MessageResources objeet with message templates for this module. The following attributes are defined:

• className is the eonfiguration bean for this message resourees objeet. If specified, the objeet must be a subdass of org. apache.struts.config. MessageResourcesConfig.

• factory is the fully qualified Java dass name ofthe MessageResourcesFactory subdass to use for this message resourees objeet.

• key is the servlet eontext attribute under which this message resourees bundle will be stored. The default attribute is Globals .MESSAGES KEY. The applieation module prefix (if any) is appended to the key (${key}${prefix}).

• null should be set to true for the message resourees to return a null string for unknown message keys or false to return a message with the bad key value.

• parameter is the eonfiguration parameter to be passed to the createResourcesO method of the faetory objeet.

cplug-Ir» specifies the fully qualified Java dass name of an applieation plug-in module that reeeives notifieation of applieation startup and shutdown. An instanee of the specified dass is ereated for eaeh element, and it can be eonfigured with nested elements. The following attribute is supported:

is the fully qualified dass name ofthe plug-in objeet.

430 APPENDIX D Getting More Information

THIS APPENDIX SHOWS you where you can find more information about JavaServer Pages OSP) and Java.

Java Development Kit Documentation

Youshould definitely download and install the ODK) doc­ urnentation; it provides a huge amount of information about the Java platform itself, such as the following:

• Instructions for using the Java command-Iine tools (javac, java, and so on).

• Guides to Java features such as input/output (I/O), networking, .jar files, and so on.

• Most important, documentation on the various classes that make up the Java platform. These are commonly known as Javadocs because they're generated by a tool known as javadoc.

Youcan download the documentation from http://java.sun.com/j2se/1.4.2/ docs/index.html. Ifyou're usingWindows, the file comes in the form ofa .zip file, which you should unzip into your JDKdirectory (for example, into C:\jdk1.4. 2); alternatively, packages in .rpm and .gzip format are also availablefor Linuxusers. Once this is done, you can browse to the index.html file to start reading-typically this means pointing yourWeb browser to C:\jdk1.4.2\docs\index.html, as shown in Figure D-l.

431 AppendixD

I!li J

J ava TM 2 SDK, Standard Edition tlJ Documentation ..Download 111IS ~ Do cu m ~ n t a l i o n .=, V Java Version 1.4.2

Search Generalinfo API & Language Guide to Features Tool Docs DemosfTutorials

Yourfeedback is importent to US. Please send u s comments : l"onte.ct JaY.1Softw.ue.

Figure D-1. Java 2 Standard Edition (J2SE) 1.4.2 documentation

As you'll see if you scroll down this page, there's a lot of Information: it's weIl worth spending some time exploring what's available, We'Il focus on one partieu­ lar part of the documentation, the application pragramming interface (API) guide. If you seraIl down to the API & Language Documentation section, you'Il find the Java 2 Platforrn API Specification link. Clieking this link takes you to a page like the one shown in Figure D-2.

.j,' •

i~- "!< tcl< _ ~ ~ _ il<><>I:""'_I:'_~ <><>Is__~~~ ------~~- --- .=ci~-j· 1 ~ ~ i • ~J .' f I-t. 'lo' II/C '/lM< r.q docs/ap/rdex t-mI ::1 ~- Se_ eh I• 1'1, 8><>- R<.. RoIo>d S>,.' M .....

T TU Java " 2 Platform :::J 'omtt'lPackage Ctass Use Tree ~ re c al e d Index Help. Jtn'a 2 P/aJ/omr ~ Std . Ed . v1.4.2 PR'. NEXT "." ES ~ Std: Ed: d ../.2 -'

.Java'" 2 Platform, Standard Edition , v 1.4.2 1 ·. ~a C kaQ1S ~ API Speclfication

:::J Thi. document is theAPI'P.emeation for theJava 2 Platronn, Standard Edrnon,vernon 1.42 s••: Description

Java 2 P latform Packages Provides the classes necessary to ceeatean app let and the cJasses an applet w es to eOllUllUl1lealt: Wlth its applet eonlt: xt COntalll. alIef'the cl..... for a .allng user interfae.s and for painlinggraphies and ima.ges. java.awt.ro)or ProV1des classes for color spaces

Figure D-2.J2SE1.4.2 APIdocumentation

You'Il see a lot of information here because there are a lot of classes and interfaces in the Java platform: in fact, more than 1,800 classes and interfaces are

432 Getting More Information listed! Fortunately, they're all nicely categorized into packages, which makes it easier to find what you're looking for. You'll see that FigureD-2is divided into three areas.The main area, on the right, initially contains a descriptive list of packages; on the top left there's a quick summary of packages, and on the bottom left there's a complete list of classes and interfaces. Ifyou d ick a package's name in the list at the top left, the bottom-left frame is replaced with a list of the classes and interfaces in that package only. Clicking a package's name in the main part ofthe screen replaces that frame with a descrip­ tive overview of that package only. So, sayyou're interested in the java.io.File dass. In the top -left frame, scroll down to j ava. i o, and dick that link. The bottom-left frame now contains a list of the contents of that package only; to get to the overview of that package, dick the text java.io at the top ofthe bottom-left frame, as shown in Figure D-3.

,. , r~ liI ,: tlo tdt \iO ,~ . , l~ , W<~ ~ ~ .~ ~., ~ ..,...... " .. .. "' , -, ~ .; ..~ " . . I ·~ "" /I/C:/I2sd Pt.. 0 t'1 2 Platform .:.t 1~~...!2 -J lava lang fDh" DAl'MI}E teEU PNM(jf ~ ~ SJd Ed. d ../.1 -' E!V~ I~nq ,,,,r 13Va lang renect .:.J Package java.io .]:" mj' .!.I Prevides fer symm tnp ul and curput thrcugh dara streams, sen.alu:allon end the 61e system laYd id Interfaces See : /)a la/rW J Df'Scriprion DIl!ar'.#/M 5~erll8:;za[)1e F/ ~FJ~~{ Interface Summary iiif,riJ"",FIu" ü!;l/t...cr,npyt Tbe Dst.aInput. mterfaceprcvides for readmg bytesfrom a bmM}' stream J)atnlnpUI OtyeC:I.WVdPt13lion and reconstructmgfrom themdau inany of the Java pnmmvetype! (ltyeCf( '!&ptÄ 0lJIecISlre& rr1Co.%1&!" Tbe Dat.llOUt.put.interface providesfor convert:ng data frcm anyof theJava ~.en8~l'!.!i!!;. D~l taO u t PlJ t primrtive types 10 a series of bytes andwnting tbese bytes tc a binary stream ciasses Onlythe identltyof the clu . of an Extemal='ole instance is wntten inIbo BulrereOInputSVe3m BulreredO~tDutStre §l Ext.malizabl. .erialization.treamand it isthe respoll$1bility of lbo das. 10 save and restere . ,. _ _ __ _ ro __j __ • the contents of itsinstances .=J I ft. 'II/C:/l2fd< I·· ·21doc"""jovo/",fpoct----....m i HP-iiit .I,

Figure D-3. java. io package description

Youcan now locate information about the File dass by clicking the appro­ priate link in either the bottom left or the main frames, which takes you to the documentation for that dass, as shown in Figure D-4.

433 AppendixD

~~ ~~ $.u". ....iltY: NEStE O I t.J.W I t.Qldl.B I ~ OETAlL,; tln.2 1t.!W.1lßI ~

~ JonJo

BUl'eredlnputStre3m • Class File BuNereqOuWutS!ream BUl'e redR~ader J l:S v tl . l i!l : I )l . (t)j e ~ t. BIl1tf!r.=:d'Wnter L j dy a . io .l'i.1r EMf;iIr~tStrf': iun IMMrr,,' ut utStre31 AUImplemented Interfaces: Ch3rArTavRe30er C om l .;~ .U: .l e . ~~etiahr.abI~ CM rArra',wr>lP.r [l 3ta ln p ut~'tr e J m Oiita(lt.rn~ l JtStn;"a m E!!!J pubhccla.. F'~. FlieDes( r1Gl or exttnds ~ FlIelnputStream implernents Senah=aHe. C..:..mr.t Mable FlIeülltorJtStre3m Fllepprml s ~ i lJ n F iI ~ R t:n d ~ r - An abstractrepresentanonof lileand du'ectory p.thnames ~ -:..I .!J---- UIrrmterfaces andoDer,atinQ SYStems use rsstem-decendenttxuhname stnnes to nameSIes aad I i":!I/C;,tM

Figure D-4. java.io.FileJavadocs

The documentation for each dass is divided into a number of sections. At the top, there's a summary showing the tree of dasses that has been extended and the interfaces that have been implemented to get you to java .io.File. Below this is a textual description of the dass. Scrolling down, you start to get to the "meat," as shown in Figure D-5.

434 Getting More Information

:; " 'f~~ ~ ue tdt 'l!'>-' iio ~ 1001< ~ 1:1"> r- --~--~ -~---; ---! I~ fko '/I/C'II2Sd r I §l n ... .o ...,.... _...... '.-. .::J f"./I/C'/f2<6I.' .Z/docs/_"'"II'''__ I ' l-O" iI A

Figure D-S. Details ofjava.Io, File fields and constructors

Asyou can see, you're given summaries ofthe flelds, constructors, and meth­ ods declared for this dass, with links to fuller descriptions farther down the page. There's also a seetion listing methods inherited from the parent dass. Finally, toward the bottom, you'll see detailed descriptions of each field, con­ structor, and method, as shown in Figure D-6.

435 AppendixD

~" look ~ ,--_._------? tJIo l ! e.c> IJ. fte,"/C'II2dI.<.2/doc.''''''nd•.,d-.N :::J 2~ ~·an h I

puhlte F t l r ( " l e patent , .~ t n n 2 chlld)

Creates a new T r Ie mstance froma par ent abstract pathname and a c1l11d pathname SU1ng -'

B~redlnpUIStream Ir patent 1S null then tbe new r r Je mstanCt 1$created as Ifby tnvolang the sm,g!e·argument Ftle E!UlreredQutpu!Stream BUlreredR~ad~r censtructor cn the ~cn eblld pathnamc.!ring. Bulte relrWnler Bytf:MrJ"(InplitStJ'':~ln Otherwisethe patent abstract pathnameis taken to denote a directory. and the c h l 1d pathname ""' ,,!OU otsuea stnng 11taken 10 denote erthera dlrectory or a file Ifthe e h l id pathname stnng11absolutethen 11 11 CharArraYReac er Cl'larAAa',fflrltef ccnverted inlo a relative p thnameina system-dependen1 way Ifpar ent is the etnpty abstract [I~ t 3Inpulli'1re 3m pathname thenthe new r l 1e instance is created by conveltin,g chl 1d irrte anabstract pathname OataC11,.'iI?IJtStrl?am and resolvingthe resullag&nst a system-dopenden: defau!ldlrectory. Otherwsse each palhnarne File .!ringis cenverted lIlIO an abstract pathnameand the cluldab.tract pathnameisresolved againsl the AeDe scr1plor FllelnPlJ@ream patent FlleüutptJtStream Flie P enTll$~ iQn Para meters : FiI~R~hd N parent - The parent abstract pathrwne ~ ~ e blld - Tbe d uldpalhnarne s!ring

Figure D-6. Detailsofa java, io . File constructor

The whole set of API documents is liberally hyperlinked, and it's actually very easy to find your way around the documentation.

Tomcat and JSP/Servlet Documentation

Youshould know about the documentation that comes with Tomcat.When you instalied Tomcat 5.0, you may have seen the page shown in Figure D-7.

436 GettingMore Information

The Apache Jakarta Project

h t t p :// j a k a r t a i a o e c n e i o r q r

Link. T he Tomcat 5 Se.." let/JSP Container" ~:b~ •D<-t H "L1t L~i~~ User Guide Documentati on Index Intr oduc:tion • .ll.!:'lh,,

Figure D-7. Tomcat's documentation page

The documentation index has been greatly improved from previous versions, and it now maintains a collection of related documentation, making it very easy to find basic startup information. The two sections of this that are particularly important are the User Guide sec­ tion, which contains great startup configuration guides, and the Reference section, which includes the APIdocumentation for the servlet 2.4 and JSP2.0 packages. The servletAPI contains the Javadocs for javax.servlet, javax.servlet.http, j avax, servlet.jsp, and j avax,servle t .j sp.t agext. You'll find these documents (shown in Figure D-8) to be a handy supplement to the information on JSPimplicit objects given in Appendix B.

437 AppendixD

l; I . 29 l iL~ ldt lio floo'-h 1 I "-. . . . 1~ ""',/floc_'808O/l_"-'/_""'nde, .""" 'a/ IO{>! !:flliL~':-S $1Of~A3!11bUi.\:!d. - HttpS e~~ .;ifJn811 ~fJj rl;JE~ Ht:PS~SSiDnB:nd;m}j-=J .1'" - . r . • N'fli'lrMPackaga Class Usa Tree p...!l!recaled Index Hell! ~.- .:J ...... - · ··- T - ' ~ '(j ,(;

Figure D-B.TheservletAPIIauadocs

Furthermore, the JSPAPIdocumentation contains the Javadocs for the javax.servlet. jsp, javax. servlet. jsp.el, and javax. servlet. jsp.tagext, as shown in Figure D-9.

~ ·' . p~ 'S~ 1-& ..." ,/floc_:808O/l0ft'<0l-'/lSPOOlIndexJtIIi I BoseMel lsp 13"''''' $t:Mel~. O eI .Javaßerver Pages API Documentatlon

All Clasou Packages Bot1yC ontelll j a va 'X' . ~ f" rv l f> r . j I P Clan.s and Illt1 Bol1V1a g~ lJ pp (lft Class.s and 1ll1eJfaC.' for theJSP 2.0 Expr.sSlonLanguag. API 0',nän l/CAt:r1tsufes. java);.'If>I'V}pt.hp.ta;ZlPrf Classes and interfaces Cor the de6nrtion ofJavaServer Page! Tag Lbraries El&.cepu on ELParseEx( eplion - ErmrDar. 1;."P..!.~, slon E).1? r~3'S.l('1nEV3l uatO,. Funct,orl1nfO lom rmPackage ciess Use Tree Qepre_cale_d Inde.l< !"l elp Func i ~W.1aqpe' II'I'iEIJ'NEXT ~~ hUoJSPPao;.­ ftef!1:.on1w C op~t 1.W.Conte.-t 0 1999-2002 The Apoeh. Softwar. Foundanon All Rjght, Reserved ~~llne l rl r fJ Jsr:: E.... l~ ep U Un 1 - ~ ...

Figure D-9. TheJSP APIJavadocs

438 Getting More Information Other Resources

This section lists some other resources you may find helpful as you continue to learn about JSP and Java. A couple of Apress books will help you to take forward from what you've learned in this book.Youmay be particularly interested in the following:

• Beginning Iaua Objects: From Concepts to Code by Jacquie Barker (Apress, 2003) teaches object-oriented programming in Java from the ground up by introdueing you to the concepts of object orientation and how to model your system as a set of objects. It then shows you how to translate this into Java sources.

• Pro JSP, Third Edition by Simon Brown, Sam Dalton, Daniel Iepp, Dave Iohnson, Sing Li, and Matt Raible (Apress, 2003) takes you beyond what has been covered in this bookwith extensive coverage of advanced topics such as using Extensible Markup Language (XML) with Java, implement­ ing servlets, generating nontextual types ofWeb content such as images and Portable Document Format (PDF) files, and using the Struts frame­ work.

• JSPExamples and Best Practices by Andrew Patzer (Apress, 2002) takes basic JSP and applies sound architectural prineiples and design patterns to give the average developer the tools to build scalable enterprise applica­ tions using JSp. This coneise, to-the-point book concentrates on the patterns needed for effective servlet- and JSP-based enterprise development.

• J2EE FrontEnd Technologies: A Programmer's Guide to Servlets,JavaServer Pages, and Enterprise JavaBeans by Lennart Jorelid (Apress,2001) is a con­ eise, to-the-point book that concentrates on the patterns needed for effective servlet- and JSP-based enterprise development.

• Pro Iakarta Struts, Second Edition by John Carnell and Rob Harrop (Apress, 2004) covers version 1.1 of Jakarta Struts, which provides new functionality in areas such as presentation and error handling. This book acts as a roadmap to demonstrate how to use the Iakarta Struts framework to solve everydayWeb application development challenges.

• Pro JSF:JavaServer Facesby KimTopley (Apress, upcoming) begins by describing the JavaServer Faces Hypertext Markup Language (HTML) tag library. It approaches JSFby treating it as a technology for building JSP pages that create HTML, and only much later in the book, when the reader is comfortable with JSF, does it introduce the details of the life­ cycle, UIComponents, and renderers.

439 AppendixD

Next, here are a few Web sites that may be of use:

' officialWeb site provides information about JSP and servlets at http://java. sun.com/products/jspl and http://java.sun.com/ productslservletsi, respectively. This site is particularly useful for official information such as the JSPspecification, servlet specification (hard read­ ing, though), and occasional articles.

• The Jakarta project, http://jakarta.apache.org/, has many useful subprojects offering useful (and free) server-side Java software. Particularly notable are Tomcat, the JSPIservlet container you've been using throughout this book (http://jakarta.apache.org/tomcatl), the Struts framework (http://jakarta.apache.org/strutsl), and the Taglibs project (http://jakarta.apache ,org/taglibsl), which offers a host of ready-made JSP tag libraries ready for you to download and use.

• JSPlnsider, http://www.jspinsider.com/. offers a host ofJSP-related infor­ mation including the helpful articles and useful (free) JavaBeans and tag libraries.

Lastly,you may find mailing lists helpful ifyou run up against problems in yourcode:

• The Jakarta project has mailing lists for their projects; each has a "user" list for questions about using the product, and each has a "developer" list where the people who created the projects live.You'llprobably be mainly interested in the "user" lists: see http://jakarta.apache.org/site/mail.html for more information.

440 Index

Symbols ActionForward dass, 307 drawbacks in creating, 338 ! logical operator, 134 returned by execute method, Action != comparison operator, 134 dass, 325 && logical operator, 134 returning for given name, 331 <and >, using in HTML,25 returning instance to ActionServlet, .jspf extension, 181 327 1:1 (one-to-one relationships), 90 returning object corresponding to l:M (one-to-many relationships), 90 input attribute, action tags, 331 == comparison operator, 134 returning object encapsulating [Iogical operator, 134 destination, 338 ActionMapping dass A conflguring, 325 fIndForward method, 324, 327, 331 abstract dasses, 208 fIndForwards method, 332 access filter, creating, 291 fIndMapping method, 306 action attribute getInputForward method, 331

tags, HTML,41 getParameter method, 332 -chtmkform» tags, 345 org.apache.struts.action package, 331 Action dass, Struts, 307, 427 actions. See standard actions execute method, 325-326, 328, 333 ActionServlet dass, 306, 310 getDataSource method, 316 config parameter, 331 org.apache.struts.action package, 332 org.apache.struts.action package, 330 -caction» element Struts confIguration file, 314 attributes, 326 using Struts in web application, 309 attribute attribute, 427 addCookie method dassName attribute, 428 response implicit object, 389 forward attribute, 427 addDateHeader method indude attribute, 427 response implicit object, 389 input attribute, 428 addHeader method name attribute, 427 response implicit object, 389 parameter attribute, 428 addlntHeader method path attribute, 427 response implicit object, 389 prefix attribute, 428 admin users, MySQL. See root users scope attribute, 427 after method suffix attribute, 428 Calendar dass, 214 type attribute, 427 aliases, IP addresses, 12 unknown attribute, 428 align attribute validate attribute, 428 tags, 375 confIguring ActionMappings, 327, ALTER command nested tags, 327 using with ALTER TABLE command, Struts confIguration file, 313, 325, 107 425,427 ALTER TABLE statements, SQL, 106 element altKey attribute Struts confIguration file, 313, 325, chtml.button» tags, 354 424,427 -chtmkhidden» tags, 347 ActionError dass tags, 348 org.apache.struts.action package, 425 -chtmkradio» tags, 353 ActionForm dass, 306 tags, 350 confIguringActionForm beans, 316 tags, 347 org.apache.struts.action package, 426 -chtmktextarea» tags, 347 validate method, 307, 326, 328

441 Index

Apache Iakarta Tomcat. See Tomcat -cattrfbute» element, TLD, 421 Apache Web server attributes, CGI alternatives built on top of, 16 classes, 189 apostrophes, use of in databases, 334 CSS,31 applets,17 HTML application folders, 256 assigning value to, 25 application implicit object, 399 style attribute, 30 getAttribute method, 399 using tables, 89 getAttributeNames method, 399 XML elements, 227, 231 getContext method, 399 -cauth-constralnts tags, web.xml file, 414 getInitParameter method, 399 -cauth-rnethod» tags, web.xml file, 415 getlnitParameterNames method, 399 AutoComrnit property getMajorVersion method, 399 GenericDataSource dass, 315 getMimeType method, 399 automated support, JavaBeans, 190 getMinorVersion method, 400 AUTO_INCREMENT modifier, SQL, 103, getNamedDispatcher method, 400 105, 118 getRealPath method, 400 getRequestDispatcher method, 400 getResource method, 400 B getResourceAsStream method, 400 background-color attribute, CSS, 31 getResourcePaths method, 400 bean tag library, Struts, 340 getServerInfo method, 400 bean tags, 194 getServletContextName method, 401 -ebean.message» tags, 341, 343 log method, 401 table of attributes, 342 removeAttribute method, 401 beanName attribute setAttribute method, 401 tags, 371 application scope, 62 beans.SeeJavaBeans application servers 20 BIGINTdata type, SQL,101 applications. See web applications binary operators, 148 applicationScope object BLOB data type, SQL, 102 as implicit object, 68 -cbody» tags, HTML,24 archive attribute element, TLD,420 tags, 375 border attribute arg attribute ctable» tags, HTML, 25 tags, 342 -cbr»tags, HTML,27 arithmetic operators, Expression branching statements, 125, 136 Language,69 break statements, 159 Array dass continue statements, 160 java.util package, 132 introducing, 158 length property, 158 return statements, 161 sort method, 132 break statements, 150, 159 arrays labeled break statements, 159 creating, 127-128 browsers,14 elements, 126 bufferSize attribute index values, 127 ccontroller» element, 428 introducing, 126 bundle attribute iterating through, 158 tags, 342 jagged arrays, 131 cexception» tags, 324 multi-dimensional arrays, 129 chtml.errors» tags, 355 one dimensional arrays, 129 chtmkoption» tags, 351 sorting, 132 byte code, 193 two dimensional arrays, 130 ASP (ActiveServer Pages) as alternative to CGI, 17 C JSP as alternative to, 18 tag. See forEach tag attribute attribute tags, 83-84 -caction» element, 326, 427 «c.otherwise» tags, 145 attribute directive, 368 tags, 115,341 442 Index cciparam» tags, 80, 83 code reuse, 167 tags, 80, 84 CSS (Cascading Style Sheets), 178 ud attribute, 83 custom tags, 185 tags, 83, 341 includes, 179 Calendar class, 213 introduction, 168 java.util package, 208 planning for, 169 methods refactoring, 170 after method, 214 Web CatalogApplication, 170 get method, 209 code types, JSP getInstance method, 208 custom tags, 74 getTime method, 209 expressions, 64 set method, 209 JSP tags, 64 Cascading Style Sheets. See CSS scriptlets, 62 case statements, 149 ccob- tags, HTML CDATA sections, XML, 228 attributes, 39 CGI (Common Gateway Interface) ccolgroup» tags, HTML alternatives to, 16 attributes, 39 chaining filters, 296 collections CHAR data type, SQL, 102 iterator tags, (forEach), 78 character data types, SQL, 102 support for in Expression Language, checkboxes, 43,50 66 checked attribute color attribute, CSS, 31 tags, HTML, 48 cols attribute child elements, XML, 226