Sun Java System Web Server 7.0 Update 5 Developer's Guide to Java Web Applications

Chapter 5 Developing JavaServer Pages

This chapter describes how to use JavaServer Pages (JSPTM) page templates in a Web Server application.

This chapter has the following sections:

Introducing JSPs

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.

Compiling JSPs Using the Command-Line Compiler

Web Server provides the following ways of compiling JSP 2.1-compliant source files into servlets:

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.

Package Names Generated by the JSP Compiler

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.

Other JSP Configuration Parameters

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.

Debugging JSPs

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.

JSP Tag Libraries and Standard Portable Tags

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

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:

cache Tag

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.

Attributes

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.

Example

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/>

flush Tag

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.

Attributes

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.

Examples

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 />
 <% } %/>

         

JSP Search Tags

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:


Note –

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.


searchForm Tag

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.

Attributes

The searchForm tag uses the following attributes:

Usage

<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:

CollElem Tag

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.

Attributes

The CollElem tag uses the following attributes:

Usage

<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.

collection Tag

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.

Attributes

Optional - A comma-delimited string representing the search collections available. The tag retrieves all collections available on the server if the attribute is empty.

Usage

<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.

colIItem Tag

This tag displays the name and label of one collection item. This tag must be used inside the collection tag.

Attributes

Property - Specifies a keyword indicating which property the tag should output. Valid inputs include name, display name, and description. Default is name.

Usage

<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.

queryBox Tag

This tag creates an input box.

Attributes

The queryBox tag uses the following attributes:

Usage

<s1ws:queryBox size="30"/>

This example creates an inputbox with default name qt and size=30.

submitButton Tag

This tag creates a submit button.

Attributes

The submitButton tag uses the following attributes:

Usage

<s1ws:submitButton cssClass="navBar" style="padding: 0px; margin: 0px; width: 50px">

This example creates a submit button with default name sb.

formAction Tag

This tag performs the following sections:

Attributes

The formAction tag uses the following attributes:

Usage

<s1ws:formAction />

formSubmission Tag

This tag tests whether the form submission is successful.

Attributes

The formsubmission tag uses the following attributes:

Usage

<s1ws:formSubmission success="true" >
         <s1ws:search>
         ...
   </s1ws:formSubmission>

formActionMsg Tag

This tag prints out an error message from formAction, if any.

Attributes

The formActionMsg tag uses the following attributes:

Usage

<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.

search Tag

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.

Attributes

The search tag uses the following attributes:

Usage

<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.

resultIteration Tag

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.

Attributes

The resultIteration tag uses the following attributes:

Item Tag

This tag retrieves a searchitem from the Results parent tag and outputs its properties as specified by the property attribute.

Attributes

Property. Specifies a case-sensitive string representing field names in a search item, such as title, number, score, filename, URL, size, and date.

resultStat Tag

This tag returns numbers indicating number of records returned and the range currently displayed.

Attributes

The resultStat tag uses the following attributes:

resultNav Tag

This tag creates a navigation bar.

Attributes

The resultNav tag uses the following attributes:

JSP Internationalization Issues

This section covers internationalization as it applies to the JSPs.

JSP Character Encoding

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.