This chapter describes how to use JavaServer Pages (JSPTM) page templates in a Web Server application.
This chapter has the following sections:
JSPs are browser pages in HTML or XML. These pages contain Java code, which enables them to perform complex processing, conditionalize output, and communicate with other application objects. JSPs in Web Server are based on the JSP 2.1 specification.
In a Web Server application, you can call a JSP from a servlet to handle the user interaction output. Because JSPs have the same application environment access as any other application component, you can use a JSP as an interaction destination.
JSPs are made up of JSP elements and template data. Template data is anything not in the JSP specification, including text and HTML tags. For example, minimal JSP file requires no processing by the JSP engine and is a static HTML page.
Web Server compiles JSPs into HTTP servlets the first time they are called or they can be precompiled for better performance. This processing makes them available to the application environment as standard objects and enables them to be called from a client using a URL.
JSPs run inside the Web Server JSP engine, which is responsible for interpreting tags that are specific to JSP and performing the actions they specify in order to generate dynamic content. This content, along with any template data surrounding it, is assembled into an output page and is returned to the caller.
Web Server provides the following ways of compiling JSP 2.1-compliant source files into servlets:
JSP are automatically compiled at runtime.
The jspc command-line tool, described in this section, enables you to precompile JSPs at the command line.
You must disable dynamic reloading of JSP when deploying a web application archive that has precompiled JSP without the corresponding jsp source files. To do this, set the reload-interval property to -1 in the jsp-config element of the sun-web.xml file. For more information, see JSP Element.
The jspc command-line tool is located under install_dir/bin. The format of the jspc command is as follows:
jspc [options] file_specifier
The following table shows what file_specifier can contain in the jspc command.
Table 5–1 File Specifiers for the jspc Command
File Specifier |
Description |
---|---|
files |
One or more JSP files to be compiled. |
-webapp dir |
A directory containing a web application. All JSPs in the directory and its subdirectories are compiled. You cannot specify a WAR, JAR, or ZIP file. You must first extract such files to an open directory structure. |
The following table shows the basic options for the jspc command.
Table 5–2 Basic jspc Options
Option |
Description |
---|---|
-help |
Enables quiet mode (same as -v0). Only fatal error messages are displayed. |
-v |
Verbose mode. |
-d dir |
Specifies the output directory for the compiled JSPs. Package directories are automatically generated based on the directories containing the uncompiled JSPs. The default top-level directory is the directory from which jspc is invoked. |
-l |
Specifies the name of the JSP on failure. |
-s |
Specifies the name of the JSP on success. |
-p name |
Specifies the name of the target package for all specified JSPs, overriding the default package generation performed by the -d option. |
-c name |
Specifies the target class name of the first JSP compiled. Subsequent JSPs are unaffected. |
-mapped |
Generates separate write() calls for each HTML line in the JSP. |
die(#) |
Generates an error return code (#) on fatal errors (default 1). |
-uribase dir |
Specifies the URI directory to which compilations are relative. Applies only to explicitly declared JSP files. This path is the location of each JSP file relative to the uriroot. If this location cannot be determined, the default is /. |
-uriroot dir |
A directory containing a web application. All JSPs in the directory and its subdirectories are compiled. You cannot specify a WAR, JAR, or ZIP file. You must first extract such files to an open directory structure. |
-compile |
Compiles the generated servlets. |
-genclass |
Generates class files in addition to Java files. |
-webinc file |
Creates a partial servlet mappings in the file. |
-web.xml file |
Creates a complete web.xml structure in the file. |
-ieplugin clsid |
Java Plug-in classid for Internet Explorer. |
classpath path |
Overrides the java.class.path system property |
xpoweredBy |
Add the X-Powered-By response header. |
-trimSpaces |
Trims spaces in text templates between actions and directives. |
-smap |
Generates SMAP info for JSR 45 debugging. |
-dumpsmap |
Dumps SMAP info for JSR45 debugging into a file. |
-compilerSourceVM release |
Provides source compatibility with specified JDKTM release. |
-compilerTargetVMrelease |
Generates class files for specified VM version. |
For example, this command compiles the hello JSP file and writes the compiled JSP under hellodir:
jspc -d hellodir -genclass hello.jsp
This command compiles all of the JSP files in the web application under webappdir into class files under jspclassdir:
jspc -d jspclassdir -genclass -webapp webappdir
To use either of these precompiled JSPs in a web application, put the classes under hellodir or jspclassdir into a JAR file, place the JAR file under WEB-INF/lib, and set the reload-interval property to -1 in the sun-web.xml file.
When a JSP is compiled, a package is created for it. The package name starts with jspc. For example, the generated package name for ~/SOURCE/JSP/myjsps/hello.jsp is precompiled as jspc -webapp ~/SOURCE -d ~/test1/test2/test3. The generated servlet is located in ~/test1/test2/test3/org/apache/jsp/JSP/myjsps/hello_jsp.java and defined in org.apache.jsp.JSP.myjsps. The path for hello.jsp is derived from the directory in which the JSP is located.
In another example, the same hello.jsp is precompiled using the —p option, and is precompiled as jspc -webapp ~/SOURCE -d ~/test1/test2/test3 -p app1.app2.app3. The generated servlet is located in ~/test1/test2/test3/app1/app2/app3/JSP/myjsps/hello_jsp.java and defined inside package app1.app2.app3.JSP.myjsps. Note that the package specified with the -p option (app1.app2.app3) overrides the standard org.apache.jsp but does not affect the package derived from the directory in which the JSP is located. Also, note that the -d option does not affect on the generated package name.
For information about the various JSP configuration parameters you can use, see the section jsp-config Element. The JSP compiler uses the default values for parameters that are not included in the file.
When you use Sun Java Studio Enterprise 8.1 to debug JSPs, you can set breakpoints in a JSP.
For information about setting up debugging in Sun Java Studio Enterprise 8.1, see Using Developer Tools for Debugging.
Web Server supports tag libraries and standard portable tags. For more information about tag libraries, see the JSP 2.1 specification at
http://java.sun.com/products/jsp/download.html.
JSP cache tags enable you to cache JSP page fragments within the Java engine. Each fragment can be cached using different cache criteria. For example, suppose you have page fragments to view stock quotes and weather information. The stock quote fragment can be cached for 10 minutes, the weather report fragment for 30 minutes, and so on.
For more information about response caching as it pertains to servlets, see Caching Servlet Results.
JSP caching uses the custom tag library support provided by JSP 2.1. JSP caching is implemented by a tag library packaged into the install_dir/lib/.jar file, which is always on the server classpath. The sun-web-cache.tld tag description file is in the install_dir/lib/tlds directory and can be copied into the WEB-INF directory of your web application.
JSP caching is available in three different scopes: request, session, and application. The default is application.
To use a cache with the request scope, a web application must specify the com.sun.appserv.web.taglibs.cache.CacheRequestListener in its deployment descriptor, as follows:
<listener> <listener-class> com.sun.appserv.web.taglibs.cache.CacheRequestListener </listener-class> </listener>
To use a cache in session scope, a web application must specify the com.sun.appserv.web.taglibs.cache.CacheSessionListener in its deployment descriptor, as follows:
<listener> <listener-class> com.sun.appserv.web.taglibs.cache.CacheSessionListener </listener-class> </listener>
To use a cache with the application scope, a web application does not need to specify any listener. The com.sun.appserv.web.taglibs.cache.CacheContextListener is already specified in the sun-web-cache.tld file.
The JSP cache tags are as follows:
The cache tag enables you to cache fragments of your JSP pages. It caches the body between the beginning and ending tags according to the attributes specified. The first time the tag is encountered, the body content is executed and cached. Each subsequent time is run, the cached content is checked to see whether it needs to be refreshed. If so, it is executed again, and the cached data is refreshed. Otherwise, the cached data is served.
The following table describes attributes for the cache tag.
Table 5–3 cache Attributes
Attribute |
Default |
Description |
---|---|---|
key |
servletPath_suffix |
(Optional) The name used by the container to access the cached entry. The cache key is added to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page. |
timeout |
60s |
(Optional) The time in seconds after which the body of the tag is executed and the cache is refreshed. By default, this value is interpreted in seconds. To specify a different unit of time, add a suffix to the timeout value as follows: s for seconds, m for minutes, h for hours, and d for days. For example, 2h specifies two hours. |
nocache |
false |
(Optional) If set to true, the body content is executed and served as if no cache tag is active. This offers a way to programmatically decide whether the cached response should be sent or whether the body must be executed, even if the response is not cached. |
refresh |
false |
(Optional) If set to true, the body content is executed and the response is cached again. This setting enables you to lets you programmatically refresh the cache immediately, regardless of the timeout setting. |
scope |
application |
Specifies the scope of the cache. Valid values are request, session, and application. |
The following example represents a cached JSP page.
<%@ taglib prefix="mypfx" uri="/com/sun/web/taglibs/cache" %> <% String cacheKey = null; if (session != null) cacheKey = (String)session.getAttribute("loginId"); // check for nocache boolean noCache = false; String nc = request.getParameter("nocache"); if (nc != null) noCache = "true"; // force reload boolean reload=false; String refresh = request.getParameter("refresh"); if (refresh != null) reload = true; %> <mypfx:cache key="<%= cacheKey %/>" nocache="<%= noCache %/>" refresh="<%= reload %/>" timeout="10m"/> <% String page = request.getParameter("page"); if (page.equals("frontPage") { // get headlines from database } else { ..... %> </mypfx:cache/> <mypfx:cache timeout="1h"/> <h2> Local News </h2> <% // get the headline news and cache them %> </mypfx:cache/>
This tag forces the cache to be flushed. If a key is specified, only the entry with that key is flushed. If no key is specified, the entire cache is flushed.
The following table describes attributes for the flush tag. The left column lists the attribute name, the middle column indicates the default value, and the right column describes what the attribute does.
Table 5–4 flush Attributes
Attribute |
Default |
Description |
---|---|---|
key |
servletPath_suffix |
(Optional) The name used by the container to access the cached entry. The cache key is added to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page. |
scope |
application |
Specifies the scope of the cache. Valid values are request, session, and application. |
To flush the entry with key="foobar":
<mypfx:flush key="foobar"/> |
To flush the entire cache:
<% if (session != null && session.getAttribute("clearCache") != null) { %/> <mypfx:flush /> <% } %/> |
Web Server includes a set of JSP tags that can be used to customize the search query and search results pages in the search interface. This section describes the tags and how they are used.
The search tag library is packaged into the install_dir/lib/webserv-rt.jar file, which is always on the server classpath. The sun-web-search.tld tag description file can be found in the install_dir/lib/tlds directory, you can copy this file into the WEB-INF directory of your web application.
The search tags are as follows:
The Web Server search feature is compliant for internalization, and supports multiple character encoding schemes in the same collection. Custom JSPs that expose search can be in any encoding.
This tag constructs an HTML form that contains default, hidden form elements such as the current search result index and number of records per page by default. The default names for the form, index, and number of records are searchform, si, and ns.
The searchForm tag uses the following attributes:
Name- Specifies the name of the form. The default is searchform. The name of a form is the identifier for all other tags.
Action (Optional) - Specifies the form action.
Method (Optional) - Specifies the method of submission, GET or POST. The default is GET.
elemStart (Optional) - Specifies the name of the hidden Start element. If not specified, the default si will be used.
Start (Optional) - An integer indicating the starting index for displaying the search result. The default is 1.
elemNumShown (Optional) - The name of the nShown element. If not specified, the default ns is used.
numShown. (Optional) - An integer indicating the number of results to be shown per page. The value of the attribute will be retrieved by requesting parameter elemNumShown. The default is 10.
<s1ws:form action="results.jsp" /> ... </s1ws:searchForm>
This example creates an HTML form tag <form name="searchform" action="results.jsp" method="GET">, along with two hidden input boxes:
A hidden input box for starting the index named si with a value from the si parameter or default 1
A hidden input box for the number of records per page named ns with a value from the ns parameter or default 20
This tag creates a hidden inputbox or select box, or multiple checkboxes, depending on the attribute input. If only one collection exists, the tag will create a hidden inputbox by default.
The CollElem tag uses the following attributes:
Name- Specifies the name of the form element created. The default is c.
Items (Optional) - A comma-delimited string representing search collections available. The tag retrieves all collections available on the server if the attribute is empty.
Type (Optional) - The type of form element used for displaying collections. Valid options are hidden, select, and checkbox. The default value is hidden if one collection exists, and checkbox if there are multiple collections.
Rows (Optional) - Represents size if the type is select, or the number of rows. The default behavior is to satisfy the Cols attribute first. That is, the collections will be listed in columns as specified by the Cols attribute.
Cols - Represents number of columns and is only required if type is checkbox. If Cols and Rows are not specified, the collections will be listed horizontally.
Defaults - Specifies a comma-delimited string containing 1s or 0s indicating the selection status of the search collections. An item is selected if the setting is 1, and not selected if the setting is 0. If there is a form action exists , these values will be retrieved from the form elements.
cssClass (Optional) - The class name used in every HTML tag created in this tag. This attribute is particularly useful when the type is checkbox, since an HTML table is used for the layout. See the sample code for details.
<s1ws:collElem type="checkbox" cols="2" values="1,0,1,0" cssClass="body" />
This example creates checkboxes in 2 columns with a default name c with the first and third items selected. Fonts and any other HTML styles are defined in the css class body, which includes tr.body, td.body, and input.body.
This tag retrieves the name of the search collections on the server, iterates through them , and passes each of them to the collectionitem tag. Use this tag with collection item tags write your own HTML search collections.
Optional - A comma-delimited string representing the search collections available. The tag retrieves all collections available on the server if the attribute is empty.
<table border=0> <s1ws:collection> <tr><td><input type=checkbox name="c" value="<s1ws:collItem property="name" />"> <s1ws:collItem property="display name" / ></td></tr> </s1ws:collection> </table>
The above code will display all collections with checkboxes.
<select name=elementname> <s1ws:collection> <option value="<s1ws:collItem property="name" />"> <s1ws:colleItem property="display name" /> </s1ws:collection> </select>
This function iterates through the available collections and passes each item to the collection item tag, which in turn displays the name and display name of the item.
This tag displays the name and label of one collection item. This tag must be used inside the collection tag.
Property - Specifies a keyword indicating which property the tag should output. Valid inputs include name, display name, and description. Default is name.
<select name=elementname> <s1ws:collection> <option value="<s1ws:collItem property="name" />"> <s1ws:collItem property="display name" /> </s1ws:collection> </select>
This function iterates through the available collections and passes each item to the collection item tag, which in turn displays the name and display name of the item.
This tag creates an input box.
The queryBox tag uses the following attributes:
name. (Optional) The name of the inputbox. The default is qt.
default. (Optional) The default value for the query box. If the form is submitted, its value will be set using this setting.
size. (Optional) The size of the inputbox. The default is 50.
maxlength. (Optional) The maxlength of the inputbox. The default is 50.
cssClass. (Optional) The CSS class.
<s1ws:queryBox size="30"/>
This example creates an inputbox with default name qt and size=30.
This tag creates a submit button.
The submitButton tag uses the following attributes:
name. (Optional) The name of the button. The default is sb.
default. (Optional) The default value of the button, which will be search.
cssClass. (Optional) The CSS class name.
style. The CSS style.
image. The optional image for the button.
<s1ws:submitButton cssClass="navBar" style="padding: 0px; margin: 0px; width: 50px">
This example creates a submit button with default name sb.
This tag performs the following sections:
This tag handles form action.
It retrieves all elements on the search form.
Validates that there is at least one collection is selected and the query is not empty, and passes the values on to search and results tags as parents or through the page context.
The formAction tag uses the following attributes:
formId. Specifies the name of the form. If not specified, the default form searchForm will be used.
ElemColl. (Optional) The name of the Collection element. The default name c is used.
elemQuery. (Optional) The name of the Start element. The default name qt is used.
elemStart. (Optional) The name of the Start element. The default name si is used.
elemNumShown. (Optional) The name of the numShown element. The default name ns is used.
<s1ws:formAction />
This tag tests whether the form submission is successful.
The formsubmission tag uses the following attributes:
formId. Specifies the name of the form in question. This name must the name assigned with <formAction>.
success. Indicates if the form submission is successful. The values true or yes represents successful action. All other inputs are rendered as failure.
<s1ws:formSubmission success="true" > <s1ws:search> ... </s1ws:formSubmission>
This tag prints out an error message from formAction, if any.
The formActionMsg tag uses the following attributes:
formId. (Optional) Specifies the name of the form in question. If not specified, the default ID is searchForm.
elem. (optional) Specifies the name of the element. Valid inputs are query and collection. When specified, the tag returns an error message, if any, regarding the element. Otherwise, all of the error messages generated are printed out.
<FormActionMsg elem="query">
This tag displays the message query text not specified if a query is not submitted.
The message is printed from the form action where the tag is placed.
This tag executes a search query and returns search results. The search tag retrieves a query string and collections from either a form parent tag or the query and collection attributes. The search results are saved in the page context with a page or session scope.
The search tag uses the following attributes:
formId. Specifies the name of the form used for the search. The default form is used if the attribute is left empty. If this tag is used without a form, this attribute must be set to provide an identifier for the resultIterate tag.
collection. (Optional) A comma-delimited string representing collections used for a search. If form action exists, this attribute is ignored and the values are retrieved by requesting the collection element.
query. (Optional) Specifies the query text. If not provided, the text is retrieved from the query element.
scope. Specifies an integer indicating the scope of the search results. The value 1, which is the default, indicates page scope. 2 indicates session scope.
<s1ws:search />
This search tag uses the default parameters and executes a search. The search results are saved in pageContext with a page scope.
<s1ws:search Collection="col1, col2" Query="Java Web Service" scope="2" />
This search tag executes a search in col1 and col2 using "Java Web Service" as the query string. The search results are saved in pageContext with a session scope.
This tag retrieves the search results from either the parent search tag or the page context. The tag iterates through the results and passing the searchitems to the item tags.
The resultIteration tag uses the following attributes:
formId. Specifies the name of the form associated with the search results. The default form is used if the attribute is left empty. If this tag is used without a form, this attribute must be set as a reference to the search tag.
start. Specifies an integer representing the starting position in the search results. The default is 0. The value is retrieved from the parent formAction tag or pageContext, or the parameter value.
numShown. Specifies an integer indicating the number of results to be shown in one page. The default is 20. The value is retrieved from the parent formAction tag or pageContext.
This tag retrieves a searchitem from the Results parent tag and outputs its properties as specified by the property attribute.
Property. Specifies a case-sensitive string representing field names in a search item, such as title, number, score, filename, URL, size, and date.
This tag returns numbers indicating number of records returned and the range currently displayed.
The resultStat tag uses the following attributes:
formId. Specifies the name of the form associated. The default form is used if the attribute is left empty. If this tag is used without a form, this attribute must be set as a reference to the search tag.
type. Specifies the type of statistics data. Valid inputs are start, end, range (for example, 1-20), and total.
This tag creates a navigation bar.
The resultNav tag uses the following attributes:
formId. Specifies the name of the form associated with the navigation bar. The default form is used if the attribute is left empty. If this tag is used without a form, this attribute must be set as a reference to the search tag.
type. Specifies the type of navigation bar. Valid values are full, previous, and next. A full navigation bar appears as follows : previous 1 2 3 4 5 6 7 8 9 10 next, where 5 is currently selected. The number of page number links is determined by the offset attribute and the number of pages available.
caption. Only necessary if the type is previous or next and the default text is not needed. caption can be any HTML file.
offset. Specifies the number of page links around the selected page. For example, if offset=2, the navigation bar would appear as follows: previous 3 4 5 6 7 next. Only required for type "full."
This section covers internationalization as it applies to the JSPs.
A JSP page uses a character encoding. For valid encodings to use, see http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html.
The encoding can be described explicitly using the pageEncoding attribute of the page directive. The character encoding defaults to the encoding indicated in the contentType attribute of the page directive, if it is given.