This chapter describes how to use JavaServer Pages (JSPs) as page templates in a Sun Java System Web Server web application.
This chapter has the following sections:
For information about internationalization issues for JSPs, see Appendix A, Internationalization Issues.
JSPs are browser pages in HTML or XML. They also contain Java code, which enables them to perform complex processing, conditionalize output, and communicate with other application objects. JSPs in Sun Java System Web Server are based on the JSP 1.2 specification.
In a Sun Java System Web Server application, JSPs are the individual pages that make up an application. You can call a JSP from a servlet to handle the user interaction output. You can also use a JSP as an interaction destination as JSPs have the same application environment access as any other application component.
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, the minimal JSP requires no processing by the JSP engine and is a static HTML page.
The Sun Java System Web Server compiles JSPs into HTTP servlets the first time they are called (or they can be precompiled for better performance). This 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 server's JSP engine, which is responsible for interpreting JSP-specific tags 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.
You create JSPs in basically the same way you create HTML files. You can use an HTML editor to create pages and edit the page layout. You make a page a JSP by inserting JSP-specific tags into the raw source code where needed, and by giving the file a .jsp extension.
JSPs that adhere to the JSP 1.2 specification follow XML syntax for the most part, which is consistent with HTML. For a summary of the JSP tags you can use, see JSP Tag Libraries and Standard Portable Tags
JSPs are compiled into servlets, so servlet design considerations also apply to JSPs. JSPs and servlets can perform the same tasks, but each excels at one task at the expense of the other. Servlets are strong in processing and adaptability. However, performing HTML output from them involves many cumbersome println statements that must be coded by hand. Conversely, JSPs excel at layout tasks because they are simply HTML files and can be created with HTML editors, though performing complex computational or processing tasks with them is awkward. For information about servlets, see Chapter 3, Using Servlets
Additional JSP design tips are described in the following sections:
Each JSP can call or include any other JSP. For example, you can create a generic corporate banner, a standard navigation bar, and a left-side column table of contents, where each element is in a separate JSP and is included for each page built. The page can be constructed with a JSP functioning as a frameset, dynamically determining the pages to load into each subframe. A JSP can also be included when the JSP is compiled into a servlet or when a request arrives.
JSPs can be completely portable between different applications and different servers. A disadvantage is that they have no particular application data knowledge, but this is only a problem if they require that kind of data.
One possible use for generic JSPs is for portable page elements such as navigation bars or corporate headers and footers, which are meant to be included in other JSPs. You can create a library of reusable generic page elements to use throughout an application, or even among several applications.
For example, the minimal generic JSP is a static HTML page with no JSP-specific tags. A slightly less minimal JSP might contain some Java code that operates on generic data such as printing the date and time, or that makes a change to the page's structure based on a standard value set in the request object.
If an uncaught exception occurs in a JSP file, Sun Java System Web Server generates an exception, usually a 404 or 500 error. To avoid this problem, set the errorPage attribute of the <%@ page%> tag.
Sun Java System Web Server provides the following ways of compiling JSP 1.2-compliant source files into servlets:
JSPs are automatically compiled at runtime.
The jspc command-line tool, described in this section, allows you to precompile JSPs at the command line.
To allow the JSP container to pick up the precompiled JSPs from a JAR file, you must disable dynamic reloading of JSPs. 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 Elements
The jspc command-line tool is located under install_dir/bin/https/bin (make sure this directory is in your path). The format of the jspc command is as follows:
jspc [options] file_specifier
The following table shows what file_specifier can be in the jspc command. The left column lists file specifiers, and the right column lists descriptions of those file specifiers.
Table 3–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 it to an open directory structure. |
The following table shows the basic options for the jspc command. The left column lists the option, and the right column describes what the option does.
Table 3–2 Basic jspc Options
Option |
Description |
---|---|
-q |
Enables quiet mode (same as -v0). Only fatal error messages are displayed. |
-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. |
-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. |
-uribase dir |
Specifies the URI directory to which compilations are relative. Applies only to explicitly declared JSP files. This is the location of each JSP file relative to the uriroot. If this cannot be determined, the default is /. |
-uriroot dir |
Specifies the root directory against which URI files are resolved. Applies only to explicitly declared JSP files. If this option is not specified, all parent directories of the first JSP page are searched for a WEB-INF subdirectory. The closest directory to the JSP page that has one is used. If none of the JSP’s parent directories have a WEB-INF subdirectory, the directory from which jspc is invoked is used. |
-genclass |
Generates class files in addition to Java files. |
The following table shows the advanced options for the jspc command. The left column lists the option, and the right column describes what the option does.
Table 3–3 Advanced jspc Options
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 _jsps, and each path name component of the JSP is prefixed with an underscore. For example, the generated package name for /myjsps/hello.jsp would be _jsps._myjsps.
For information about the various JSP configuration parameters, see jsp-config The JSP compiler uses the default values for parameters that are not included in the file.
When you use Sun Java Studio to debug JSPs, you can set breakpoints in either the JSP code or the generated servlet code, and you can switch between them and see the same breakpoints in both.
For information about setting up debugging in Sun Java System Studio, see Using Sun Java Studio for Debugging.
Sun Java System Web Server supports tag libraries and standard portable tags. For more information about tag libraries, see the JSP 1.2 specification at:
http://java.sun.com/products/jsp/download.html
For a handy summary of JSP 1.2 tag syntax, see the following PDF file:
http://java.sun.com/products/jsp/syntax/1.2/card12.pdf
JSP cache tags allow you to cache JSP page fragments within the Java engine. Each can be cached using different cache criteria. For example, suppose you have page fragments to view stock quotes, weather information, and so on. 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 1.2. JSP caching is implemented by a tag library packaged into the install_dir/bin/https/jar/webserv-rt.jar file, which is always on the server classpath. The sun-web-cache.tld tag description file can be found in install_dir/bin/https/tlds directory and can be copied into the WEB-INF directory of your web application.
You can add a taglib mapping in the web.xml of your application as follows:
<taglib> <taglib-uri>/com/sun/web/taglibs/cache</taglib-uri> <taglib-location>/WEB-INF/sun-web-cache.tld</taglib-location> </taglib>
You can then refer to these tags in your JSP files as follows:
<%@ taglib prefix="mypfx" uri="/com/sun/web/taglibs/cache" %>
Subsequently, the cache tags are available as <mypfx:cache> and <mypfx:flush>.
The tags are as follows:
The cache tag allows 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 it is run, the cached content is checked to see if it needs to be refreshed and 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. The left column lists the attribute name, the middle column indicates the default value, and the right column describes what the attribute does.
Table 3–4 cache Attributes
Attribute |
Default |
Description |
---|---|---|
key |
ServletPath_Suffix |
(optional) The name used by the container to access the cached entry. The cache key is suffixed 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, 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 there were no cache tag. This offers a way to programmatically decide whether the cached response should be sent or whether the body must be executed, though the response is not cached. |
refresh |
false |
(optional) If set to true, the body content is executed and the response is cached again. This lets you programmatically refresh the cache immediately, regardless of the timeout setting. |
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>
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 3–5 flush Attributes
Attribute |
Default |
Description |
---|---|---|
key |
ServletPath_Suffix |
(optional) The name used by the container to access the cached entry. The cache key is suffixed 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. |
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 > <% } %> |
Sun Java System 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’re used. For more information about using the search feature, see the Sun Java System Web Server 6.1 SP11 Administrator’s Guide.
The search tag library is packaged into the install_dir/bin/https/jar/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/bin/https/tlds directory, and can be copied into the WEB-INF directory of your web application.
The search tags are as follows:
The Sun Java System Web Server search feature is i18n compliant, and supports multiple character encoding schemes in the same collection. Custom JSPs that expose search can be in any encoding.
Constructs an HTML form that contains default and 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.
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 creates an HTML form tag <form name="searchform" action="results.jsp" method="GET"> along with two hidden inputboxes:
A hidden inputbox for starting index named "si" with a value from the "si" parameter or default 1, and
A hidden inputbox for number of records per page named "ns" with a value from the ns parameter or default 20.
Creates a hidden inputbox or select box, or multiple checkboxes depending on the attribute input. If there is only one collection, the tag creates a hidden inputbox by default.
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. If there is only one collection, the default value is hidden else the default value is checkbox.
Rows. (optional) Represents size if type is select, or number of rows if checkboxes. 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, that is, in one row.
Defaults. Specifies a comma-delimited string containing 1s or 0s indicating the selection status of the search collections. An item is selected if 1, and not selected if 0. If there is a form action, these values will be retrieved from the form elements.
cssClass. (optional) The class name that will be used in every HTML tag created in this tag. This is particularly useful when the type is checkbox, since an HTML table will be used for the layout. See the sample code below for details.
<s1ws:collElem type="checkbox" cols="2" values="1,0,1,0" cssClass="body" >
This 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 css classes "body," which includes tr.body, td.body, and input.body.
Retrieves the name of search collections on the server, and iterates through and passes each of them to the collectionitem tag. Users may choose to use this tag along with collection item tags so they can write their own HTMLs.
items. (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 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.
Displays the name and label of one collection item. 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 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.
Creates an inputbox.
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 what has been submitted.
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 creates an inputbox with default name "qt" and size=30.
Creates a submit button.
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 creates a submit button with default name "sb."
Handles form action. It retrieves all elements on the search form. It validates that there is at least one collection selected and the query is not empty. After validation, it passes the values on to search and results tags as parent or through the page context.
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 >
Tests if the form submission is successful.
formId. Specifies the name of the form in question. It must be the same as that for <formAction>.
success. Indicates if the form submission is successful. The values true or yes represents successful action. All other inputs will be rendered as failure.
<s1ws:formSubmission success="true" > <s1ws:search> ... </s1ws:formSubmission>
Prints out an error message from formAction, if any.
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, it prints out all of the error messages generated.
<FormActionMsg elem="query">
This tag will display a message "query text not specified" if a query is not submitted.
The message is printed from the form action where the tag is placed.
Executes a search query and returns search results. The search tag retrieves a query string and collection(s) 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.
formId. Specifies the name of the form used for the search. The default form will be 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 collection(s) used for a search. If there is a form action, this attribute is ignored and the values are retrieved by requesting the collection element.
Query. (optional) Specifies the query text. If not provided, it 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, and 2 indicates session scope.
<s1ws:search >
This search tag uses the default parameters and executes a search. The search results will be saved in pageContext with a page scope.
<s1ws:search Collection="col1, col2" Query="Java Web Service" scope="2" >
This search tag will execute a search in col1 and col2 using "Java Web Service" as the query string. The search results will be saved in pageContext with a session scope.
Retrieves the search results from either the parent search tag or the page context. The tag is responsible for iterating through the results and passing the searchitems to the item tags.
formId. Specifies the name of the form associated. The default form will be 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.
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.
Returns numbers indicating number of records returned and the range currently displayed.
formId. Specifies the name of the form associated. The default form will be 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."
Creates a navigation bar.
formId. Specifies the name of the form associated. The default form will be 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 inputs are "full," "previous," and "next." A full navigation bar looks like this: 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 type is previous or next and the default text is not wanted. Caption can be any HTML.
offset. Specifies the number of page links around the selected page. For example, if offset=2, the sample bar above would look like this: previous 3 4 5 6 7 next . Only required for type "full."