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
• 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" %>
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
<%@ 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
Youcan include code between the
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
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
The
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::
• The page attribute for
• The value attribute for
373 AppendixA The 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
374 JSPSyntax Reference vspace="topBottomPixels" title="title" jreversion="1.2Inumber" nsp1uginurl="pluginURL" iep1uginur1="pluginURL " mayscript="truelfa1se"> 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 • 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 The 375 AppendixA The
If one or more of these actions are used, the body of the tag can be specified onlywith a
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
The 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 You can use the You can use You use cjsp:scriptlet> 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: 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: 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 c) 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("
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
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»,
The
The
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
• An optional <1arge-icor» element eontaining the loeation within the applieation ofa 32X32 pixel icon
The
• An optional «icor» element
• An optional
• An optional
• An optional
• 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
• Zero or more
• An optional
• Zero or more
406 XMLConfiguration Files
• An optional
• Zero or more cerror-pages elements
• Zero or more
• Zero or more cresource-env-ref» elements
• Zero or more cresource-ref» elements
• Zero or more
• An optional <1ogin-config> element
• Zero or more
• Zero or more
• Zero or more cejb-refo elements
• Zero or more
• Zero or more cservtce-refo elements
• Zero or more
• Zero or more
• 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
407 AppendixC
The
•A
•A
• An optional
The
• An optional cicor» element
•A
• An optional
• An optional
•A
• Zero or more dnit-param> elements containing initialization parameters for the filter
Each dnit-param> element contains the following:
•A
•A cparam-values element containing the parameter value
• An optional
Youuse the
408 XMLConfiguration Files
•A
• Either a curl-patterro element containing a URLpattern to match or a
• Zero to four
The
<1istener>
You can use the
•A
•
The cservlet» element declares a servlet. It contains the following :
• An optional «icor» element.
•A
• An optional
• An optional
• Either a cservlet-classs element containing the listener's class name or a
• 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
•
• An optional crun-ass element that specifies the identity under which the servlet should run.
Each dnit-param> element contains the following:
•A
•A
• An optional
A
• An optional
•A crole-names element containing the role name used within the servlet
• An optional
The
•A cservlet-name» element containing the name of a servlet declared by a
•A
410 XMLConjiguration Files
The
• An optional
The
• An
•A
The
• One or more
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
•A clocatior» element containing the location ofthe error page resource within the Web application
411 AppendixC
The
• A
• A
The
•A
•A
The
•A
• An optional
• An optional
• An optional
• 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
• An optional
•A
•A
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
•A cres-ref-name» element containing the name ofthe resource factory reference.
•A
•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
413 AppendixC
The
• An optional
• One or more
• An optional
• An optional
A
•A
• An optional
• One or more curl-patterr» elements, each containing a URLpattern to match
• Zero or more
An
• An optional
• Zero or more crol.e-nameo elements each containing a role referenced in a
A
• An optional
•A
Table C-l.
INTEGRAL The data must not be changed in transit. CONFIDENTIAL Others may not view the data en route.
<1ogin-config>
The
• An optional
• 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
• An optional
•A
The
• An optional
• An
415 AppendixC
• An optional
• An
The cejb-ref» element declares a reference to an Enterprise Iavaßean (EIB).lt contains the following:
• An optional
• 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
• An optional
Youuse
• An optional
• 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
416 XMLConjiguration Files
•A
• An optional
•A
•A
• An optional
• An optional
• An optional
• Zero or more
• Zero or more
•A
417 AppendixC
• A
• A
• A
• An optional
<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
(ommon Elements of the Tag Library Descriptor
The
The
•A
•A cshort-name» element
• An optional
418 XMLConjiguration Files
• An optional
• An optional Icor» element
• An optional
• An optional
• Zero or more
• Zero or more
• Zero or more
• Zero or more cfunctdor» elements that specify an ELfunction
• Zero or more
Child Elements of
The permissible subelements of ctaglil» are as follows.
The
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
419 AppendixC
The
•A
• 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
• An optional
<1istener>
The
•A
•
The
•A
•A etag-elasse element containing the name ofthe tag handler dass.
• An optional
• An optional
420 XMLConjiguration Files
• An optional
• An optlonal c Icor» element.
• An optional
• Zero or more
• Zero or more
• An optional
• An optional
• Zero or more
A
• An optional
• Either a
• An optional
• An optional
• 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
•A cname» element containing the name of the attribute.
421 AppendixC
• An optional
• An optional
• An optional
• An optional
•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
• Zero or more
You use
•A cname» element uniquely identifying this function
•A
•A
422 XMLConjiguration Files
• An optional
• Zero or more dunction-extension> elements that provide information about this tag, mainly for use by tools
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,
Youuse the
• property specifies the name of the bean property to be set.
• value specifies the new property value in astring representation.
The
423 AppendixC
The
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
• An optional The • An optional cdata-sourcess element • An optional cform-beanss element • An optional • An optional • An optional • An optional • An optional • An optional cplug-Ir» element 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 The • 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. 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.) The • 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. The • 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 • 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 • 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 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 • inputForward should be set to true for the input attribute of • 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. • 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 • 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 Java Development Kit 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' 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 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 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 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 Bo All Clasou Packages Bot1yC ontelll j a va 'X' . ~ f" rv l f> r . j I P Clan.s and Illt 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: • Sun Microsystems' 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 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