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

Professional Java.JDK.5.Edition (Wrox)

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

Chapter 6

.addClass(Post.class)

.addClass(Topic.class);

//Create a new SessionFactory factory = cfg.buildSessionFactory();

//Open Session

Session sn = factory.openSession();

Transaction transaction = null;

try {

tx = sn.beginTransaction();

//Create a new Post object with a specified Topic ID Post post = new Post(lTopicID);

//Populate the post object before saving it post.setPostDate(new java.sql.Date(System.currentTimeMillis())); post.setPostMsg(sPost);

post.setPostAuthor(sAuthor);

//Save the Post object

sn.save(post);

// Commit the transaction and close the session transaction.commit();

sn.close();

}catch (Exception e) {

if (transaction!= null) { transaction.rollback(); throw e;

}finally { sn.close();

}

}

The post.jsp allows the user to view posts for a specific topic. It utilizes the following code, which queries the data source for posts that have the same topic id associated with them as the topic id that is being passed to the viewPosts method:

public void viewPosts(JspWriter out, Long catID, Long topID) throws Exception {

// final Driver test = new Driver(); SessionFactory factory;

Configuration cfg = new Configuration()

.addClass(Category.class)

.addClass(Post.class)

.addClass(Topic.class);

factory = cfg.buildSessionFactory();

Session s = factory.openSession();

326

Persisting Your Application Using Databases

Transaction tx=null;

try {

tx = s.beginTransaction();

List list = s.createCriteria(Post.class)

.add( Expression.eq(“TopicID”, topID) )

.list();

if (list.size()==0) return; Iterator it = list.iterator();

while (it.hasNext()) {

Post post = (Post) it.next();

out.write(“<tr>”);

//Insert information from Post object here to display

//to the user.

out.write(“</tr>”);

tx.commit(); } catch (Exception e) {

if (tx!=null) tx.rollback(); throw e;

}finally { s.close();

}

}

The forum example that was just demonstrated is a lightweight use of Hibernate’s capabilities. Its main intent was to help you get your feet wet with Hibernate and provide you with an end-to-end example that doesn’t cover the query language or mapping collections in great depth. These particular topics will be covered in greater detail later on in the book.

Summar y

Developing applications that are required to persist data to relational database management systems is a need that continues to grow throughout the IT industry. This chapter provided you with a strong sense of how Java technologies and open source products are being used to solve data persistence issues. Java 2 SDK 1.5 edition provides extensive data persistence support through its new and improved JDBC API. The different features that the JDBC API provides were discussed in-depth and intuitive examples were created that should help you choose the best features to fit your particular application’s architecture.

Through the use of Hibernate, this chapter was able to show you just how easy it is to utilize an object with the relational mapping technology in your application. It also explored why Hibernate is one of the most popular tools on the market based on its ability to provide scalability and performance benefits with little effect on your existing applications code.

Simple Web applications were also used to demonstrate Hibernate’s persistence. In the next couple chapters, your focus will turn more toward Web applications themselves. Chapter 7 starts with building Web applications using the Model 1 Architecture.

327

Developing Web

Applications Using the

Model 1 Architecture

Software development activities generally involve domain-driven speculations that attempt to tackle complexity by aggregating knowledge of a subject matter so that it can be handled for your own purposes. This reflection generally involves experimentation by software and domain experts to organize knowledge for use by development teams. Ultimately, these modeling tasks involve the abstraction and filtering of nonessential data and the attainment of purposeful knowledge so that developer needs are served and proper deployments are made to customers.

This chapter will demonstrate how you can overcome speculation over how to construct a Web application using the Model 1 Architecture by constructing a hands-on Contact Management Tool. Two different types of Java syntax, JSTL 1.1 and JSP 2.0, will be utilized to craft the sample GUI component that will allow users to manage contact information through upload and query activities. The sample application’s use of Model 1 was chosen to suit design and implementation needs for a quick prototype that can be implemented by novice Java Web developers in an easy fashion, and to demonstrate some of the new Java language enhancements that were delivered with the JSTL 1.1 and JSP 2.0 specifications.

What Is Model 1? Why Use It?

The Model 1 Architecture is a page-centric approach where page flows are handled by individual Web components. This means that request and response processing are hard-coded into pages to accommodate user navigations in a Web application. With Model 2 Architecture, navigation flows are generally handled by a servlet controller that works in conjunction with configuration files to dictate page renderings during application operations.

Chapter 7

Naturally, this presents maintenance problems when logic modifications are needed to accommodate changes in requirements and end-user needs. Those changes would oblige developers to comb through code to ensure that all logic flows are properly handled as users navigate through a Web application. Along with the responsibilities of maintaining navigation flow in Model 1 deployments is the need to manage concerns regarding security and application state.

Model 1 Architecture concerns are certainly difficult design decisions to tackle at the inception of a project, but limitations in your team’s development expertise, the scope of your application, and time to delivery might persuade you to adopt this development philosophy to get your project going. Adoption of the Model 1 philosophy is not necessarily a bad decision depending on your predicament and your estimation of what and how your team will deliver in an allotted delivery schedule. Model 2 implementations would most likely help you overcome maintenance issues in the long run, so it is paramount that your team overcomes its deficiencies by practicing with Model 2 frameworks and their configurations to better understand their intricacies so that your earlier Model 1 applications can be migrated fairly easily.

Figure 7-1 provides a high-level overview of a Model 1 template used for the sample Contact Management application that will be built to demonstrate Web application assembly combining JSP and JSTL technologies. Notice the individual JSP components (header, leftNav, content, and footer) that are all aggregated in the home page. As a user navigates the taxonomy in the application, indexes are established and passed along all of the individual pages so that operations can be performed inside those pages based on those indexes.

home.jsp (aggregates all *.jsp pages)

JSP / Servlet

header.jsp

Container

JavaBean

Content placed here.

*.XML

leftNav.jsp

content.jsp

Database

footer.jsp

Figure 7-1

330

Developing Web Applications Using the Model 1 Architecture

On many Web application components, content is typically retrieved from Java Bean components that persist data on the back-end tier of an enterprise system for visualization on the client tier. The sample application modeled in Figure 7-1 aggregates content from a MySQL database by using indexes from the left panel drill-down to determine proper page inclusion demonstrated in the content.jsp code shown below. When a user clicks on the initial Tasks link in the left panel, three navigation links will be presented (Add Profile, Add Contact, and View Contacts) so that contact names can be saved and queried:

<!--content.jsp -‡

<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %>

<link href=”CMS.css” rel=”stylesheet” type=”text/css”>

<c:if test=”${param.taxonomyIndex == ‘101’}”> <jsp:include page=”addProfile.jsp”/>

</c:if>

<c:if test=”${param.taxonomyIndex == ‘102’}”> <jsp:include page=”addContact.jsp”/>

</c:if>

<c:if test=”${param.taxonomyIndex == ‘103’}”> <jsp:include page=”viewContacts.jsp”/>

</c:if>

The Expression Language (EL) construct <c:if> is used in content.jsp to evaluate the three different test conditions so that the appropriate JSP script will be included, which will in turn collect the proper content for visualization.

Java Server Page (JSP) 2.0 and Java Standard Template Library (JSTL) 1.1 are both important Web application components for constructing dynamic content on J2EE platforms. JSP 2.0 scripts can easily construct HTML content and access JavaBean properties through Expression Language libraries. JSTL components encapsulate functionalities that allow developers to iterate through data, perform XSLT transform operations, and access both database and object data. Both technologies can be combined to craft presentationtier components to display and interact with back-end data models.

This section will discuss JSP 2.0 and JSTL 1.1 technologies by presenting overviews of their capabilities followed by some individual components of their libraries and demonstrate their usage in figures and source code listings.

JSP 2.0 Overview

The viability of the Model 1 Architecture depends heavily on a number of the new features in the JSP 2.0 specification. In this section you will learn about the following:

Servlet 2.4 specification support

Expression Language (EL) support

Code reuse with *.tag and *.tagx files

JSP page extensions (*.jspx)

Simple Invocation Protocol

331

Chapter 7

The introduction of these new script language constructs with the JSP 2.0 and JSTL 1.1 specifications was meant to eliminate the need to include Java expressions in script code, which would result in scriptless page development. These enhancements will certainly provide more controlled interactions and flexibility with other components as well as reusability among common actions.

Servlet 2.4 Support

The JSP 2.0 specification uses the Servlet 2.4 specification for its syntax, which allows applications to handle Expression Language (EL) expressions as native syntax.

The following table describes some of the ServletRequest methods that were introduced with the Servlet 2.4 specification to determine client connection attributes.

Method

Description

 

 

getRemotePort()

Method that returns the IP address of the port that sent a request

getLocalName()

Method that returns the hostname of the IP address from which the

 

request was received

getLocalAddr()

Method that returns the IP Address from which the request was received

getLocalPort()

Method that returns the IP port number from which the request was

 

received

 

 

This code segment illustrates how these methods can be implemented to realize these client connection values:

<html>

<head>

<title>Servlet 2.4 Features</title> </head>

<body>

<h2>Servlet 2.4 Features</h2> <%

out.println(“Remote Port : “ + request.getRemotePort() + “<br>”); out.println(“Local Name : “ + request.getLocalName() + “<br>”); out.println(“Local Address : “ + request.getLocalAddr() + “<br>”); out.println(“Local Port : “ + request.getLocalPort() + “<br>”); %>

</body>

</html>

Additionally, Servlet 2.4 support includes the introduction of new features for the RequestDispatcher and ServletRequest listener classes, as well as login capabilities related to the HttpSession class.

Expression Language Support

The Expression Language implementation in JSP 2.0 allows easy access to data from JSP scripts. This enhancement has allowed developers to avoid writing scriptlets inside their pages, which should result in cleaner and more readable JSP pages.

332

Developing Web Applications Using the Model 1 Architecture

Expression Language syntax is purported to be more user-friendly than Java and was introduced to encourage its use for accessing data over Java language implementations. The power of Expression Language constructs is that they allow users to embed Java code in a Java Server Page through scripting elements. Three types of scripting elements are shown in the following table.

Scripting Element

Example

 

 

expressions

<jsp:expression> objectRef.loadValues() </:jsp:expression>

scriptlets

<% for (int increment = 0; increment < 25; increment++) { }

declarations

<%! boolean firstPass = true; %>

 

 

The following code examples use Expression Language features to perform pig Latin word translations and string replacement operations. The tag library prefix test is used to access the pigLatin and dwReplacement methods to perform string operations on user specified text that is saved in the sampleText parameter:

<%-- index.jsp --%>

<%@ taglib prefix=”test” uri=”/WEB-INF/el-taglib.tld”%>

<html>

<head>

<title>Expression Language Examples</title> </head>

<body>

<h1>Expression Language Examples</h1>

<form action=”functions.jsp” method=”GET”> sampleText = <input type=”text” name=”sampleText”

value=”${param[‘sampleText’]}”> <input type=”submit”>

</form>

<table border=”0”> <tr>

<td bgcolor=”#ffff99”>Pig-Latin = </td>

<td bgcolor=”#ffff99”>${test:pigLatin(param[“sampleText”])} </td> </tr>

<tr>

<td bgcolor=”#ffff99”>Dirty Word Replacement = </td>

<td bgcolor=”#ffff99”>${test:dwReplacement(param[“sampleText”])} </td> </tr>

</table>

</body>

</html>

The Java method below performs regular expression string manipulation operations on the text expressions specified by the user in the text field components of index.jsp. For the pigLatin method, a check is performed on the first character of the string passed in to see if that character is a vowel; if so, then the

333

Chapter 7

string will be returned with the word “way” appended to the end of it. Strings that start with consonants will have their first character moved to the end of the string and then have “ay” added to the end of string:

// [StringMethods.java] package examples.el;

import java.util.*; import java.util.regex.*;

public class StringMethods {

public static String pigLatin( String text) { // works for one word ONLY

Pattern pattern = Pattern.compile(“^([aeiouAEIOU])”); Matcher matcher = pattern.matcher(text);

if (matcher.find()) return text+”way”;

else

return text.replaceAll(“^([^aeiouAEIOU])(.+)”, “$2$1ay”);

}

public static String dwReplacement( String text ) {

Pattern pattern = Pattern.compile(“(darn|damn|stupid|dummy)”); Matcher matcher = pattern.matcher(text);

text = matcher.replaceAll(“#%&@”); return text;

}

}

The tag library definition file below defines the two different text functions, pigLatin and dwReplacement, that are invoked in the index.jsp file and defined in StringMethods.java:

<!-- el-taglib.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>Function Examples</description> <tlib-version>1.0</tlib-version>

<short-name>Function Examples</short-name> <uri>/el</uri>

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

334

Developing Web Applications Using the Model 1 Architecture

</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, Expression Language library extensions are powerful features that strengthen developer’s capabilities for Web development. The function methods described here are mapped to public static methods in Java classes that can be accessed through Expression Language constructs throughout your Web application.

Code Reuse with *.tag and *.tagx Files

The implementation of *.tag and *.tagx files allows for better code reuse among developers. With these tags, developers can encapsulate common behavior that will support reuse activities.

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”> <td nowrap>

${title} </td>

</tr>

335

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