Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Java.JDK.5.Edition (Wrox)

.pdf
Скачиваний:
32
Добавлен:
29.02.2016
Размер:
12.07 Mб
Скачать

Chapter 7

<tr>

<td valign=”top”>

•  <a href=””>Test1</a><br> •  <a href=””>Test2</a><br>

</td>

</tr>

</table>

These tag files can be important components for header and footer implementations that contain common information that can be easily propagated to the Web pages in your project.

JSP Page Extensions (*.jspx)

Java Server Pages that have *.jspx extensions are meant to advocate the use of XML syntax to generate XML documents in JSP 2.0 compliant Web containers.

The code specified below 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 test.tag file below is used to invoke the JSP fragments using the <jsp:doBody> standard action:

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

336

Developing Web Applications Using the Model 1 Architecture

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 code example below, 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>

The LotteryPickTag application below 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:

337

Chapter 7

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

338

Developing Web Applications Using the Model 1 Architecture

JSP 1.2

 

Backwards compatibility issues

extends

 

Tag Library

 

 

 

 

 

Servlet 2.4

Validation

Tag coercion

 

 

 

Specification

 

 

 

rule adherence

Expression

support

I18N behavior

 

Language (EL)

 

differences

 

Support

 

 

web.xml

 

*.tag and *.tagx

 

 

 

 

JSP page

support for

Lack of EL

JSP interpretation

reuse

support in JSP

of *.jspx files by

extensions

 

 

1.2 pages

default

(*.jspx)

 

 

 

 

 

Simple Invocation

‘/$’ support now

 

Protocol for script-

longer there, returns

 

less pages

 

‘$’

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 above, but this section will concentrate 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.

Expression Language (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 table below 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”/>

 

 

339

Chapter 7

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>

The parameter param.Comments is checked to see if it is greater than 250; if so, then 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 below 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 on in great depth, so this chapter will concentrate 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 storage and retrieval operations so that the SQL Actions libraries are implemented and the Function Tag Library operations are used for string manipulation. So the latter will be discussed too.

340

Developing Web Applications Using the Model 1 Architecture

Function Tag Library

The Function Tag Library capabilities were introduced with the JSP 2.0 specification to allow developers to extend Expression Language (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.

Function [fn:]

Description of Function

 

 

fn:contains(string, substring)

If the substring exists in a specified string value, true

 

will be returned to the user, otherwise false.

 

Example, fn:contains(“independence”, “depend”)

 

returns true

fn:containsIgnoreCase(string, substring)

Ignoring case differences, if a substring exists in a

 

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

 

ters in a string as an integer value

 

Example, fn.length(“architecture”) returns 12

fn:replace(string, before, after)

Returns a new string after replacing all occurrences

 

of the 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”

 

 

 

Table continued on following page

341

Chapter 7

Function [fn:]

Description of Function

 

 

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

fn:substring(string, begin, end)

Returns a substring of a string based upon specified

 

index values

 

Example, fn:substring(“practical”, 2,5) returns act

fn:substringAfter(string, substring)

Returns a string value that follows a specified

 

substring

 

Example, fn:substringAfter(“peppermint”,”pepper”)

 

returns mint

fn:substringBefore(string, substring)

Returns a string value that precedes a specified sub-

 

string 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

 

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

 

 

Since 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; we’ll demonstrate that with the Add Contact component below. 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.

342

Developing Web Applications Using the Model 1 Architecture

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>

 

 

343

Chapter 7

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 on above 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 operations 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

Our code example below demonstrates the use of SQL actions mentioned previously. The first course of action in our code is to establish a data source object that will allow the application to connect to the picture database so that 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” %>

<HTML><HEAD><TITLE>Contact Management Tool</TITLE> <link href=”CMT.css” rel=”stylesheet” type=”text/css”>

<sql:setDataSource

344

Developing Web Applications Using the Model 1 Architecture

var=”pictures”

driver=”org.gjt.mm.mysql.Driver”

url=”jdbc:mysql://localhost/picture”

user=””

password=””

scope=”page”/>

After the data source has been established, a query is performed using the database reference ${pictures} where the result set is stored in the results variable:

<sql:query var=”results” dataSource=”${pictures}”> select * from picture

</sql:query>

<br>

<br>

The result set variable is then used to iterate through the individual database entries so that they can be shown on the user display:

<table cellSpacing=0 cellPadding=4 align=center><tr><td bgColor=#7b849c> <table border=”0”><tr><td>

<c:forEach var=”row” items=”${results.rows}” varStatus=”counter”> <tr class=”row1”>

<td>

<table cellSpacing=”0” cellPadding=”0” border=”0”> <td valign=”top”><b>${counter.count}.</b></td> <td>

<table width=”500” border=”0”> <tr>

<td class=”smallblue” noWrap align=”middle”> <a href=””>${row.marking}</a>

</td>

<td>

<u>Attributes:</u>

</td>

</tr>

<tr>

<td align=”middle”> <a href=””>

<img src=”./images/${row.name}” width=50 border=0> </a>

</td>

<td>

<table>

<tr>

<td>Phone Number:</td> <td>${row.telephone_num}</td>

</tr>

<tr>

<td>Comments:</td> <td>${row.comments}</td>

345

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]