Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 77 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
77
Dung lượng
1,63 MB
Nội dung
<description>PIG-Latin</description> <name>pigLatin</name> <function-class>examples.el.StringMethods</function-class> <function-signature> java.lang.String pigLatin( java.lang.String ) </function-signature> </function> <function> <description>Dirty Word Replacement</description> <name>dwReplacement</name> <function-class>examples.el.StringMethods</function-class> <function-signature> java.lang.String dwReplacement( java.lang.String ) </function-signature> </function> </taglib> As this example demonstrates, EL library extensions are powerful features that strengthen developer’s capabilities for web development. The function methods described here are easily mapped to public static methods in Java classes that can be accessed by EL constructs throughout your web application. Code Reuse with .tag and .tagx Files The implementation of .tag and .tagx file syntax delivered with JSP 2.0 implementations allows for better code reuse by enabling developers to encapsulate common behavior that can be easily shared across components. Those familiar with older code conventions used to craft custom tag libraries should recog- nize this and embrace these amendments for defining reusable custom actions with great enthusiasm. The following code snippet demonstrates how tag files can be implemented for reuse by other web applications. In this example, a portlet-like visualization component is crafted using a tagged file named portlet.tag. Two parameters, title and color, are passed into the portlet tag file to dynamically alter those properties in the component display: <%@ taglib prefix=”tags” tagdir=”/WEB-INF/tags” %> <html> <head><title>tagx test</title> </head> <body> <table width=”100%”><tr><td> <tags:portlet title=”Portlet” color=”#0000ff”> Test 1 </tags:portlet> </td></tr></table> </body> </html> The portlet.tag file encapsulates the portlet component and renders the title and color features passed into the file by the preceding script: <! portlet.tag > <%@ attribute name=”title” required=”true” %> <%@ attribute name=”color” required=”true” %> <table width=”250” border=”1” cellpadding=”2” cellspacing=”0”> <tr bgcolor=”${color}” color=”#ffffff”> 361 Chapter 7: Developing Web Applications Using the Model 1 Architecture 12_777106 ch07.qxp 11/28/06 10:47 PM Page 361 <td nowrap> ${title} </td> </tr> <tr> <td valign=”top”> • <a href=””>Test1</a><br> • <a href=””>Test2</a><br> </td> </tr> </table> After this code is run, a simple portlet-like component is displayed with two test references embedded in it. What the reader should take away from this is how easily this syntax can be implemented to gener- ate custom tags and share them across a project’s code base. Consideration might be given for imple- menting tag files in header and footer implementations that contain common information that can be easily propagated to the other web pages with their inclusion. JSP Page Extensions (.jspx) Java Server Page 2.0 syntax has included .jspx extensions that are meant to advocate the use of XML syn- tax to generate XML documents in JSP 2.0-compliant web containers. The following code describes how .jspx files can be implemented when you develop web applications to generate user displays: <! forms.jspx > <?xml version=”1.0”?> <tags:test xmlns:tags=”urn:jsptagdir:/WEB-INF/tags” xmlns:jsp=”http://java.sun.com/JSP/Page” xmlns:c=”http://java.sun.com/jsp/jstl/core” xmlns=”http://www.w3.org/1999/xhtml”> <jsp:directive.page contentType=’text/html’/> <head><title>Form Test</title></head> <body> <c:choose> <c:when test=’${param.name == null} and ${param.address == null}’> <form action=”form.jspx”> Please enter your name and address:<br/> <input name=”name” size=”40”/><br/> <input name=”address” size=”40”/><br/> <input type=”submit”/> </form> </c:when> <c:otherwise> User entered name=${param.name}, address=${param.address}<br/> </c:otherwise> </c:choose> </body> </tags:test> The following test.tag file is used to invoke the JSP fragment using the <jsp:doBody> standard action. After the script has been run, a form will be rendered so that name and address can be entered by the user and captured by the script for execution: 362 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_777106 ch07.qxp 11/28/06 10:47 PM Page 362 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML Basic 1.0//EN” “http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <jsp:doBody/> </html> As the JSP 2.0 specification indicates, web applications that contain files with an extension of .jspx will have those files interpreted as JSP documents by default. Simple Invocation Protocol This API enhancement was developed to exploit the use of scriptless pages among web developers using JSP libraries in their development activities for implementing tag files. In the following code example, the <lottery:picks/> tag file invocation demonstrates how simple it is to incorporate logic into a web page using tag libraries: <%@ taglib uri=”/WEB-INF/tlds/lottery.tld” prefix=”lottery” %> <html> <head> <title>Lottery Picks</title> </head> <body> <h2>Lottery Picks</h2> Lottery number generated is <lottery:picks/> </body> </html> The lottery tag library descriptor file, lottery.tld, outlines the lottery tag file application invoked from the preceding web application: <! lottery.tld > <?xml version=”1.0” encoding=”UTF-8” ?> <taglib xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd” version=”2.0”> <description> Lottery picks </description> <jsp-version>2.0</jsp-version> <tlib-version>1.0</tlib-version> <short-name>picks</short-name> <uri></uri> <tag> <name>picks</name> <tag-class>lottery.LotteryPickTag</tag-class> <body-content>empty</body-content> <description>Generate random lottery numbers</description> </tag> </taglib> 363 Chapter 7: Developing Web Applications Using the Model 1 Architecture 12_777106 ch07.qxp 11/28/06 10:47 PM Page 363 The LotteryPickTag application illustrates how the SimpleTagSupport class can be extended to allow developers to craft tag handlers. The doTag() method is invoked when the end element of the tag is realized. In the sample Lottery application, the getSixUniqueNumbers() method is called from the doTag() method, which in turn displays the string output of six unique lottery numbers generated in random fashion: package lottery; import java.io.*; import java.util.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.SimpleTagSupport; public class LotteryPickTag extends SimpleTagSupport { public LotteryPickTag(){} public void doTag() throws JspException, IOException { getJspContext().getOut().write(“Random #’s =” + getSixUniqueNumbers()); } public String getSixUniqueNumbers() { StringBuffer sb = new StringBuffer(); int count = 0, number = 0; int numbers[] = {0,0,0,0,0,0,0}; boolean found; while (count < 6) { number = (int)(Math.random()*59) + 1; found = false; for (int i=0; i < numbers.length; i++) if (numbers[i] == number) found = true; if (!found) { if (count != 0) sb.append(“ - “); sb.append(number); numbers[count++] = number; } } return sb.toString(); } } JSP tag files are converted into Java code by the JSP container in the same fashion that JSP scripts are translated into servlets. It should be fairly evident from this example how easily tag files can be con- structed for deployment in web components for enterprise systems because they hide the complexity of building custom JSP tag libraries, which makes them easier to maintain in the long run. Figure 7-2 outlines visually some of the enhancements of the JSP 2.0 specification along with some of the backwards compatibility issues that are addressed in the JSP 2.0 specification. Certainly, the JSP 2.0 upgrade, with its ready-made Expression Language implementations, along with improvements in Java Server Pages Standard Tag Libraries, will enhance developer’s abilities to build cohesive and robust web components. 364 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_777106 ch07.qxp 11/28/06 10:47 PM Page 364 Figure 7-2 Integrated Expression Language (EL) The following section concentrates on the Expression Language (EL) and its implementation in JSP applications. Certainly, there is ample content in the JSP 2.0 specification to discuss and demonstrate, especially some of the Servlet 2.4 features that were discussed briefly earlier, but this section concen- trates on EL implementations because they are exploited prominently in the Contact Management Tool. Some of the other aspects of that specification are fairly involved and extend beyond the scope of this chapter. EL expressions can be used with three different attribute values. First, they can be applied when an attribute value has a single expression; second, they can be used when the attribute value contains one or more expressions surrounded or separated by text; and lastly, they can be used when the attribute value contains only text. The following table shows how these operations can be implemented. EL Expressions Implementation Single expression <xyz.tag value=”${expression}”/> One or more expressions <xyz.tag value=”abc${expression}text${expression}”/> Text only <xyz.tag value=”abc text”/> JSP 2.0 scripts allow EL expressions to perform conditional operations on your web page variables. An example of this follows: <c:if test=”${param.Comments > 250}”> </c:if> Lack of EL support in JSP 1.2 pages JSP interpretation of *.jspx files by default ‘/$’ support no longer there, returns ‘$’ Tag Library Validation Tag coercion rule adherence Servlet 2.4 Specification support *.tag and *.tagx support for reuse Simple Invocation Protocol for script- less pages JSP page extensions (*.jspx) Expression Language (EL) Support extends JSP 1.2 Backwards compatibility issues I18N behavior differences web.xml 365 Chapter 7: Developing Web Applications Using the Model 1 Architecture 12_777106 ch07.qxp 11/28/06 10:47 PM Page 365 The parameter param.Comments is checked to see if it is greater than 250; if so, the logic that lies between the if statement is executed. The JSTL core tag libraries can also be used for variable output. Here is an example of this: <c:out value=”${testELexpression}”/> JSP 2.0 pages implement several different implicit objects through EL expressions; the table that follows lists some examples. Implicit Object Description pageContext Accesses the PageContext object, which provides access to all the namespaces associated with a JSP page pageScope A Map that contains page-scoped attribute names and values requestScope A Map that contains request-scoped attribute names and values sessionScope A Map that contains session-scoped attribute names and values applicationScope A Map that contains application-scoped attribute names and values param A Map that correlates parameter names to single String parameter values paramValues A Map that correlates parameter names to a String[] of all values of that parameter header A Map that contains header names in a String headerValues A Map that contains header names in a String array component cookie A Map that contains web cookie objects initParam A Map that holds context initialization parameter names and their values Implicit objects (for example, objects that don’t need to be declared and are declared automatically) allow developers to access web container services and resources. JSTL 1.1 Overview Capabilities of the Java Standard Template Library (JSTL 1.1) specification are too numerous to elaborate in great depth, so this chapter concentrates on two tag library capabilities that are helpful in the sample Contact Management Tool (CMT). The CMT application persists data in a MySQL database during stor- age and retrieval operations so the SQL Actions libraries are implemented and the Function Tag Library operations are used for string manipulation. The latter is discussed as well. Function Tag Library The Function Tag Library capabilities were introduced with the JSP 2.0 specification to allow developers to extend EL functionalities with string manipulation libraries. The JSTL 1.1 specification outlines these functions as follows. The following table demonstrates some of the new method functions available as part of the expression language support in JSP 2.0. 366 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_777106 ch07.qxp 11/28/06 10:47 PM Page 366 Function [fn:] Description of Function fn:contains If the substring exists in a specified string value, true (string, substring) will be returned to the user, otherwise false. Example, fn:contains(“independence”, “depend”) returns true. fn:containsIgnoreCase Ignoring case differences, if a substring exists in a (string, substring) specified string value, true will be returned to the user, otherwise false. Example, fn:containsIgnoreCase(“independence”, “DEPEND”) returns true. fn:endsWith(string, suffix) Tests the end of a string with the suffix specified to determine if there is a match. Example, fn:endsWith(“whirlyjig’, “jag”) returns false. fn:escapeXml(string) Escape characters that might be XML. Example, fn.escapeXml(“<test>yea</test>”) returns converted string. fn:indexOf(string, substring) Returns integer value of the first occurrence of the specified substring in a string. Example, fn:indexOf(“democratic”, “rat”) returns 6 fn:join(array, separator) Joins elements from an array into a string with a specified separator. Example, array[0]=”X”, array[1]=”Y” fn:join(array,”;”) returns String = “X;Y” fn:length(item) Returns a collection count or the number of characters in a string as an integer value. Example, fn.length(“architecture”) returns 12. fn:replace Returns a new string after replacing all occurrences of the (string, before, after) before string with the after string. Example, fn:replace(“downtown”, “down”, “up”) returns uptown. fn:split(string, separator) Returns an array where all the items of a string are added based on a specified delimiter. Example, fn:split(“how now brown cow”,” “) returns array[0]=”how”, array[1]=”now”, array[2]=”brown”, array[3]=”cow” fn:startsWith(string, prefix) Returns a Boolean value (true/false) depending on whether or not a string contains a specified prefix value. Example, fn:startsWith(“predicament”, “pre”) returns true. Table continued on following page 367 Chapter 7: Developing Web Applications Using the Model 1 Architecture 12_777106 ch07.qxp 11/28/06 10:47 PM Page 367 Function [fn:] Description of Function fn:substring Returns a substring of a string based upon specified (string, begin, end) index values. Example, fn:substring(“practical”, 2,5) returns act. fn:substringAfter Returns a string value that follows a specified substring. (string, substring) Example, fn:substringAfter(“peppermint”, ”pepper”) returns mint. fn:substringBefore Returns a string value that precedes a specified substring (string, substring) value. Example, fn:substringBefore(“peppermint”, “mint”) returns pepper. fn:toLowerCase(string) Converts all the characters of a specified string to lowercase. Example, fn:toLowerCase(“Design Patterns”) returns design patterns. fn.toUpperCase(string) Converts all the characters of a specified string to uppercase. Example, fn:toUpperCase(“Patterns”) returns PATTERNS. fn:trim(string) Eliminates leading and trailing white space from a specified string. Example, fn:trim(“ almost done “) returns “almost done”. Because text manipulation is so prevalent in web applications, these function libraries are invaluable components for your development and deployment operations. Many of these functions mirror the same APIs that the Java String class possesses, so they should be learned fairly easily. SQL Actions A general rule of thumb for SQL transactions on enterprise systems is to handle database operations within business logic operations (as demonstrated with the Add Contact web application in Figure 7-6, later in this chapter). But sometimes you might want to perform those activities with the SQL tag libraries that are part of the JSTL 1.1 libraries. JSTL SQL Actions allow developers to interact with databases on the presentation layer. An overview of its capabilities include the ability to perform queries through SELECT statements, database updates with insert, update, and delete operations, and transactional activities that allow the aggregation of database operations. 368 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_777106 ch07.qxp 11/28/06 10:47 PM Page 368 The following table illustrates the SQL Action tags for establishing a data source. Tag Description <sql:setDataSource> This tag exports a data source. <sql:setDataSource {datasource=”dataSource” | url = “jdbcUrl” [driver = “driverClassName”] [user = “userName”] [password = “password”] } [var=”varName”] [scope=”{page|request|session|application}”]/> The following table illustrates the SQL Action tags for query operations. Tag Description <sql:query> This tag queries the database. Without body content <sql:query sql=”queryString” var=”varName” [scope=”{page|request|session|application}”] [maxRows=”maxRows”] [startRow=”startRow”] /> With a body for query parameters <sql:query sql=”queryString” var=”varName” [scope=”{page|request|session|application}”] [maxRows=”maxRows”] [startRow=”startRow”] <sql:param> actions </sql:query> With a body for query parameters and options <sql:query sql=”queryString” var=”varName” [scope=”{page|request|session|application}”] [maxRows=”maxRows”] [startRow=”startRow”] query optional <sql:param> actions </sql:query> 369 Chapter 7: Developing Web Applications Using the Model 1 Architecture 12_777106 ch07.qxp 11/28/06 10:47 PM Page 369 The following table illustrates the SQL Action tags for update operations. Tag Description <sql:update> This tag executes an INSERT, UPDATE, or DELETE statement. Without body content <sql:update sql=”updateString” [datasource=”datasource”] [var=”varName”] [scope=”{page|request|session|application}”]/> With a body for query parameters <sql:update sql=”updateString” [datasource=”datasource”] [var=”varName”] [scope=”{page|request|session|application}”] <sql:param> actions </sql:update> With a body for query parameters and options <sql:update sql=”updateString” [datasource=”datasource”] [var=”varName”] [scope=”{page|request|session|application}”] update statement optional <sql:param> actions </sql:update> The SQL Action tags elaborated in the preceding tables certainly are powerful mechanisms to perform SQL transactions inside your JSP web components without having to worry about back-end JavaBean applications to perform the same duties. Ultimately, developers must decide during their coding opera- tions if they opt to perform script or JavaBean queries in their deployments. Fortunately, the Contact Management Tool illustrates both to facilitate your design decisions. Developing Your Web Application Visualizations with JSTL 1.1 The following code example demonstrates the use of SQL actions mentioned previously. The first course of action in your code is to establish a data source object that will allow the application to connect to the picture database so queries can collect data for visualization on your JSP page: <%@ page language=”java” contentType=”text/html” import=”java.util.*,java.lang.*,java.io.*” %> <%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core_rt” %> <%@ taglib prefix=”sql” uri=”http://java.sun.com/jstl/sql” %> <link href=”CMT.css” rel=”stylesheet” type=”text/css”> <sql:setDataSource 370 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_777106 ch07.qxp 11/28/06 10:47 PM Page 370 [...]... metadata associated with that image into the picture database for future retrieval: The Test .java bean component creates an ArrayList of six randomly generated numbers that can be retrieved with the getData() method: package com.ajax; import java. util.*; public class Test { private ArrayList list = new ArrayList(); private final int NUMBERS = 6; public Test() {} public String getData() { 383 Part II: A Broad Understanding of Java APIs, Tools, and Techniques... is to encapsulate complicated business logic in JavaBean components written in Java that are entirely devoid of scriplet syntax so display scripts are not obfuscated with complicated logic that might make your code hard to decipher for maintenance purposes Naturally, your JavaBean code artifacts will transfer across platforms because they are written in Java, which accommodates reuse in your overall... Developing Web Applications Using the Model 1 Architecture function textCounter(field, countfield, maxlimit) { if (field.value.length > maxlimit) { field.value =... dwr.xml file illustrates how DWR generates interfaces to the back-end JavaBean DAO components The ContactMgmtToolDAO class is defined here within the tag so the front-end JavaScript component can communicate with it The tag is implemented so the ContactMgmtTool Plain Old Java Object (POJO) can be transformed into JavaScript associative arrays for data marshalling operations: . expression language support in JSP 2.0. 366 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 12_7771 06 ch07.qxp 11/28/ 06 10:47 PM Page 366 Function [fn:] Description of Function fn:contains. language= java contentType=”text/html” import= java. util.* ,java. lang.* ,java. io.*” %> <%@ taglib prefix=”c” uri=”http:/ /java. sun.com/jstl/core_rt” %> <%@ taglib prefix=”sql” uri=”http:/ /java. sun.com/jstl/sql”. data insertion: package com.model1; import java. io.*; import java. net.*; import java. sql.*; import java. util.*; import java. util.logging.*;; import javax.naming.*; public class FileManager { private