包含在查找更多文档专项支持资源 | 以 PDF 格式下载本书 (1277 KB)
Chapter 5 Developing JavaServer PagesThis chapter describes how to use JavaServer Pages (JSPTM) page templates in a Web Server application. This chapter has the following sections: Introducing JSPsJSPs 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 CompilerWeb 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
The following table shows the basic options for the jspc command. Table 5–2 Basic 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. Package Names Generated by the JSP CompilerWhen 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 ParametersFor 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 JSPsWhen 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 TagsWeb 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 TagsJSP 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 TagThe 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. AttributesThe following table describes attributes for the cache tag. Table 5–3 cache Attributes
ExampleThe 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 TagThis 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. AttributesThe 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
ExamplesTo flush the entry with key="foobar":
To flush the entire cache:
JSP Search TagsWeb 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 TagThis 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. AttributesThe 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 TagThis 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. AttributesThe 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 TagThis 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. AttributesOptional - 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 TagThis tag displays the name and label of one collection item. This tag must be used inside the collection tag. AttributesProperty - 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 TagThis tag creates an input box. AttributesThe queryBox tag uses the following attributes:
Usage<s1ws:queryBox size="30"/> This example creates an inputbox with default name qt and size=30. submitButton TagThis tag creates a submit button. AttributesThe 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 TagThis tag performs the following sections:
AttributesThe formAction tag uses the following attributes:
Usage<s1ws:formAction /> formSubmission TagThis tag tests whether the form submission is successful. AttributesThe formsubmission tag uses the following attributes:
Usage<s1ws:formSubmission success="true" >
<s1ws:search>
...
</s1ws:formSubmission>
formActionMsg TagThis tag prints out an error message from formAction, if any. AttributesThe 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 TagThis 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. AttributesThe 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 TagThis 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. AttributesThe resultIteration tag uses the following attributes:
Item TagThis tag retrieves a searchitem from the Results parent tag and outputs its properties as specified by the property attribute. AttributesProperty. Specifies a case-sensitive string representing field names in a search item, such as title, number, score, filename, URL, size, and date. resultStat TagThis tag returns numbers indicating number of records returned and the range currently displayed. AttributesThe resultStat tag uses the following attributes:
resultNav TagThis tag creates a navigation bar. AttributesThe resultNav tag uses the following attributes:
JSP Internationalization IssuesThis section covers internationalization as it applies to the JSPs. JSP Character EncodingA 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. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||