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

Practical Database Programming With Java

.pdf
Скачиваний:
780
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

8.1 A Historical Review about Java Web Application Development 587

<navigation-rule> <from-view-id>/Current.jsp</from-view-id>

<navigation-case> <from-outcome>clickAction</from-outcome> <to-view-id>/Next.jsp</to-view-id> </navigation-case>

</navigation-rule>

Figure 8.26. A part of application configuration resource file.

in the JSF file. Another way that is provided by JSF is to use the application configuration resource file faces-config.xml to build these navigation rules. The task of defining navigation rules involves defining which page is to be displayed after the user clicks on a button or a hyperlink. Each <navigation-rule> element defines how to get from one page as defined by the <form-view-id> to the other pages of the application. A <navigationrule> element can contain any number of <navigation-case> elements that define the page to open next using the <to-view-id> based on a logical outcome defined by the <from-outcome>. This outcome is defined by the action attribute of the component that submits the form (such as the commandButton).

An application configuration resource file, faces-config.xml, is used to define your Java managed beans, validators, converters, and navigation rules.

Figure 8.26 shows a part of an example of an application configuration resource file. The configuration resource file is composed of a sequence tags listed below:

Starting from <navigation-rule> tag, a new navigation rule is defined. The <from- view-id> tag is used to define the navigation source, which is the current page (Current. jsp). The <navigation-case> tag is used to define one of the navigation destinations defined by the <to-view-id> tag based on the output of some clicked buttons or links triggered by the action tag in the current page. Those outputs are defined by the <fromoutcome> tag.

You can use the design tools such as PageFlow to do this navigation plan graphically and directly. Refer to Section 5.3.5.12 in Chapter 5 to get more detailed information about using the design tools to build this configuration file graphically.

8.1.7.2 Sample JavaServer Face Page Files

Two JSF files are shown in Figures 8.27 and 8.28. In Figure 8.27, a Current.jsp page that works as a receiving page to get the username is shown. In Figure 8.28, a Next.jsp that works as a responding page to select and return a matched password based on the username to the Current.jsp page.

The function of the Current.jsp page is:

A.In order to use JSF tags, you need to include the taglib directives to the html and core tag libraries that refer to the standard HTML renderkit tag library, and the JSF core tag library, respectively.

B.A body tag with the bgcolor attribute is defined.

C.A page containing JSF tags is represented by a tree of components whose root is the UIViewRoot, which is represented by the view tag. All component tags must be enclosed

588 Chapter 8 Developing Java Web Applications to Access Databases

<html>

<head>

<title>Current Page</title> </head>

A<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

B<body bgcolor=”white”>

C<f:view>

D<h:form id="QueryForm" >

E<h:inputText id="userName" value="#{QueryBean.userName}"

validator="#{ QueryBean.validate}"/>

F

<h:commandButton id="Query" action="success"

 

value="Query" />

G

<h:message style="color: red; font-family: 'New Century Schoolbook',

 

serif; font-style: oblique; text-decoration: overline"

 

id="QueryError" for="userName"/>

 

</h:form>

 

</f:view>

 

</body>

 

</html>

Figure 8.27. The codes for the Current.jsp page.

<html>

<head>

<title>Next Page</title> </head>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<body bgcolor=”white”> <f:view>

A<h:form id="ResponseForm" >

B<h:graphicImage id="ResponseImg" url="/Response.jpg" />

C<h:outputText id="QueryResult" value="#{QueryBean.passWord}" />

D<h:commandButton id="Back" action="success"

value="Back" />

</h:form>

</f:view>

</body>

</html>

Figure 8.28. The codes for the Next.jsp page.

in the view tag. Other content such as HTML and other JSP pages can be enclosed within that tag.

D.A typical JSP page includes a form, which is submitted to the next page when a button is clicked. The tags representing the form components (such as textfields and buttons) must be nested inside the form tag.

E.The inputText tag represents an input text field component. The id attribute represents the ID of the component object represented by this tag, and if it is missing, then the implementation will generate one.The validator attribute refers to a method-binding expression

8.1 A Historical Review about Java Web Application Development 589

pointing to a Java backing bean method that performs validation on the component’s data. The Java backing bean’s property userName is bound to the value attribute by using the Unified Expression Language (EL) value expression.

F.The commandButton tag represents the button used to submit the data entered in the text field. The action attribute helps the navigation mechanism to decide which page to

open next. Exactly, the next page has been defined in the application configuration resource file faces-config.xml using the <to-view-id> tag above, which is the Next.jsp.

G.The message tag displays an error message if the data entered is not valid. The for attribute refers to the component whose value failed validation.

An interesting thing in step E in this piece of sample codes is that an embedded backing bean property userName has been bound to the value attribute of the inputText tag. Recall that we used either the getAttribute() method of a JSP implicit object session (session.getAttribute()) or the getProperty() method of a Java bean to hook to the value attribute of this text field tag in the previous sample codes to enable this text field’s value to be updated automatically. However, in this JSF file, we directly bind one of backing bean’s properties, userName, with the value attribute of this text field by using the value-binding expressions that is called expression language (EL) and have the syntax #{bean-managed-property} to do this data updating job. One point to be noted is that the JSF EL bindings are bidirectional when it makes sense. For example, the UI component represented by the inputText tag can get the value of a bean property userName and present it to the user as a default value. When the user submits the QueryForm data, the UI component can automatically update the bean property userName so that the application logic can process the new value. You can see how easy it is now to set up a connection between a component in a JSF page and the related property in the backing bean object when using this binding for a JSF file. In fact, you can bind not only the bean’s properties, but also the bean’s methods, to certain UI components in the JSP pages.

The codes for the Next.jsp file are shown in Figure 8.28. The detailed function of this piece of codes is:

A.The form id is defined as a ResponseForm.

B.An image is added into this page with the image id and the image URL. The forward slash “/” before the image name Response.jpg indicates that this image is located at the current project folder.

C.An outputText tag is equivalent to a label in a Web page.The selected password is assigned to the value attribute using the value-binding expressions that have the syntax #{bean- managed-property}. In fact, this value has been bound with a property password in the backing bean QueryBean class.

D.The commandButton Back is used to direct the page to return to the Current.jsp page as it is clicked by the user. This returning function has been defined in the application configuration source file faces-config.xml we discussed above.

The real tracking issue is that there is no username–password matching process occurred in either of these two pages.Yes, that is true! All of those data matching processes, or as we called them, business logics, occured in the backing Java bean QueryBean class.

When a user entered a valid username into the input textbox and clicked the Submit button in the Current.jsp page, all input data are sent to the next page Next.jsp. Of

590 Chapter 8 Developing Java Web Applications to Access Databases

course, you can handle this data matching in the Next.jsp page based on the passed username. However, in order to separate the presentations from business logics, JSF uses JSF pages as views and assigns the business logics to the Java beans who work as controllers to handle those data matching jobs. In fact, since the userName has been bound to the value attribute of the inputText tag by using the value-binding expressions that have the syntax #{bean-managed-property}, any change of this data item will be immediately reflected to the associated property userName defined in the Java bean QueryBean class. The Java bean will perform the password matching process based on that username and send the matched password to the passWord property in that bean class. As soon as the Java bean finished the password matching processing and sent the matched password to the passWord property, it can be immediately updated and displayed in the outputText QueryResult in the Next.jsp page using the value-binding expressions #{QueryBean.passWord}.

8.1.7.3 The Java Bean Class File

The java bean class used in JSF pages is very similar to the FacultyBean class we built in Section 8.1.5.3. Like most Java bean classes, it should contain setter and getter methods, as well as some special methods to process the business logics.

In addition, the Java beans need to be configured in the application configuration resource file faces-config.xml so that the implementation can automatically create new instances of the beans as needed. The <managed-bean> element is used to create a mapping between a bean name and class. The first time the QueryBean is referenced, the object is created and stored in the appropriate scope. You can use the code elements shown in Figure 8.29 to register a Java bean in the faces-config.xml file:

Besides to register the Java bean class, you also need to use this configuration file to configure and define all properties created inside this Java bean. In this example, only two properties, userName and passWord, have been defined in this Java bean.Therefore, you need to use the <managed-property> element to do this configuration, as shown in Figure 8.30.

<managed-bean-name>QueryBean</managed-bean-name> <managed-bean-class>LogInQuery.QueryBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope>

Figure 8.29. A piece of sample codes to register a Java bean.

<managed-property> <property-name>userName</property-name> <property-class>string</property-class> <value>null</value>

</managed-property>

<managed-property> <property-name>passWord</property-name> <property-class>string</property-class> <value>null</value>

</managed-property>

Figure 8.30. A piece of codes to define all properties in a Java bean class.

8.1 A Historical Review about Java Web Application Development 591

In fact, you do not need to worry about these configurations if you are using an IDE such as the NetBeans IDE, and the NetBeans IDE can do these configurations automatically for you as you built the Java bean class file.

Next, let’s take a look at the Web deployment descriptor file.

8.1.7.4 The Web Deployment Descriptor File web.xml

Before you can use and access a Servlet such as FacesServlet in the server side from a Web browser, you need to map the FacesServlet to a path in your deployment descriptor file web.xml. By using this deployment descriptor file, you can register Servlet and

FacesServlet, and register listeners and map resources to URLs. Figure 8.31 shows a piece of example codes used in the web.xml file for the FacesServlet class.

Most codes in this file will be created automatically if you are using the NetBeans IDE to build your Web applications.

As we discussed in Section 8.1.6.1, regularly, JSP pages use the <jsp:useBean> tag to instantiate JavaBeans. When using the JSF framework, you do not have to specify the Java bean class names in your web pages anymore. Instead, you can configure your bean instances in the application configuration resource file faces-config.xml using the <managed-bean> element. You may use multiple configuration files if you develop a large application. In that case, you must add a javax.faces.CONFIG_FILES parameter in the deployment descriptor file web.xml.

Now that we have worked through all main techniques of JSF, now let’s have a full picture about the complete running procedure of JSF Web applications.

8.1.7.5 A Complete Running Procedure of JSF Web Applications

As we mentioned, a UI component represented by a JSF tag in a JSP page can be bound to a Java bean’s property or a Java bean’s method. To separate the presentations and business logics, we can use JSP pages to present our GUI and the Java beans to store our data to perform business related logics.Therefore, we can divide methods into two categories: data access methods (business methods) and action methods.The data access methods

<web-app>

<display-name>JSF LogIn Application</display-name> <description>JSF LogIn Application</description>

<!-- Faces Servlet --> <servlet>

<servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup> 1 </load-on-startup>

</servlet>

<!-- Faces Servlet Mapping --> <servlet-mapping>

<servlet-name>Faces Servlet</servlet-name> <url-pattern>/login/*</url-pattern> </servlet-mapping>

Figure 8.31. An example coding for the Web deployment descriptor file.

592 Chapter 8 Developing Java Web Applications to Access Databases

should be located at the Java bean side, and the action methods should be located at the JSF page side. Each data access method defined in the Java bean can be called by an associated action method defined in an action attribute of a submit button tag in the JSP page if that submit button has been bound to the action attribute.

Here, we use a login process to illustrate the operational procedure using the JSF technique. Two JSP pages, the LogIn.jsp and Selection.jsp, and a Java bean class LogInBean.java, are involved in this procedure. Two JSP pages work as views and are used to display the input and output login information, and the Java bean works as a model to handle the database-related processing and business logics. The functional procedure of this example application is:

1.When the user entered a username/password pair into the Username/Password input text fields in the LogIn.jsp page, and clicked on the LogIn button, a query request is sent to the Web server with all form data (Username and Password) for processing.

2.After the server received the request, if the validation is passed, all form data (Username and Password) will be stored into the associated properties of the Java bean.

3.The action method that is bound to the LogIn button will call the data access method defined in the Java bean to perform the database query to find the matched login information in the LogIn table.

4.If the data access method is successful, the next page, Selection.jsp, should be displayed.

To run this procedure using JSF technique, we need to have a clear picture between the JSF pages and Java beans, and the page-to-page navigation schedule.

8.1.7.5.1 The Java Bean—JSF Page Relationship and Page Navigations Table 8.1 lists all data access methods and action methods used in this example.

A Java bean can be connected to a JSF page by using the value attribute of an UI component represented by a JSF tag in that page. Exactly, a property or a method defined in a Java bean class can be mapped to a value attribute of a UI component in a JSF page. This relationship can be triggered and set up when a submit button in the JSF page is clicked by the user and all form data will be sent to the Web server. Refer to Figure 8.32; the operational procedure of executing a request is:

1.The data access method LogInQuery() is defined in the Java bean class LogInBean and will be called by the action method LogInBean.LogInAction() defined in the JSF page LogIn. jsp as the user clicks the LogIn button. Since the action method LogInBean.LogInAction() has been bound to the LogIn command button, all form data including the Username and Password entered by the user to the JSF page will be submitted to the FacesServlet as the LogIn button is clicked by the user.

2.After the FacesServlet received the form data, it will validate them and return the form back to the client if any error encountered.

Table 8.1. The relationship between the data access method and the action method

Data Access Method

Action Method

JSF Page

LogInQuery()

LogInBean.LogInAction()

LogIn.jsp

8.1 A Historical Review about Java Web Application Development 593

FacesServlet

LogIn.jsp

21. Validate the form data (username and password). 2. If the validation is failed, sends the form back.

Username

3. If the validation is successful, save form data (username

 

Password

3

and password) to the associated properties in the Java

1

 

bean class LogInBean.

4

 

 

LogIn

 

public class LogInBean()

 

 

 

LogInBean.java

 

5

private string userName;

action="#{LogInBean.LogInAction}" />

 

 

 

 

private string passWord;

 

 

 

 

 

 

public string LogInAction()

 

Selection.jsp Page

 

{

6

 

string result = LogInQuery();

 

 

 

7

if a matched login information found,

 

 

 

 

return “Selection”;

 

 

else

 

 

return null;

8

 

}

 

public string LogInQuery()

 

 

 

 

{

 

 

……. Query matched login information from database…

 

 

return query_result;

 

 

}

Figure 8.32. The operational procedure of executing a request using JSF.

3.Otherwise, the validated form data, including the Username and Password, will be stored to the associated properties in the Java bean class. Then JSF engine will call the action method LogInBean.LogInAction() that has been bound to the LogIn button, and in turn, to call the data access method LogInQuery() to perform database-related query to find matched login information.

4.After a piece of matched login information has been found, the associated properties, userName and passWord, which are defined inside the Java bean class, will be updated by assigning the matched username and password to them. These updating occurred in the Java bean side will be immediately reflected to the value attributes of the Username and Password inputText fields in the JSF page, since they have been bound together. Therefore, the content of each inputText tag will also be updated.

5.The action method LogInAction() defined in the LogInBean class will also be called when the LogIn button is clicked by the user, since it is bound to the LogIn button.

6.The data access method LogInQuery() will be executed to perform database-related queries and business logics.

7.Each action method returns a string called “outcome”. JSF uses a navigation handler to determine what it is supposed to do for each outcome string. If an action method returns a null, which means that the execution of that method encountered some problems and the same page must be redisplayed. Otherwise, the desired next page should be displayed, depending on the returned outcome string. The default JSF navigation handler uses a set of navigation rules that are specified in the JSF application configuration file faces-config. xml, which is shown in Figure 8.33. In this example, if a piece of matched login information is found, the action method will return an outcome string “SELECTION” and the next page, Selection.jsp, should be displayed.

8.Otherwise, the query has failed, and no matched login user information can be found. The LogInAction() method returns a null to the JSF engine to redisplay the LogIn page.

594 Chapter 8 Developing Java Web Applications to Access Databases

<faces-config version="2.0"

<managed-bean>

A<managed-bean-name>LogInBean</managed-bean-name>

B<managed-bean-class>JavaWebDBApp. LogInBean</managed-bean-class>

C<managed-bean-scope>session</managed-bean-scope>

</managed-bean> <navigation-rule>

D<from-view-id>/LogIn.jsp</from-view-id> <navigation-case>

E<from-outcome>SELECTION</from-outcome>

F<to-view-id>/Selection.jsp</to-view-id> </navigation-case>

</navigation-rule>

</faces-config>

Figure 8.33. The application configuration resource file faces-config.xml.

The detailed explanation on the codes shown in Figure 8.33 is listed below:

A.Our Java managed bean LogInBean is defined using the <managed-bean-name> tag.

B.The full class name, including the package name and the bean class name, is defined by the

<managed-bean-class> tag.

C.The scope of this Java bean is defined by using the <managed-bean-scope> tag.

D.The current JSF page LogIn.jsp is defined by using the <from-view-id> tag.

E.The outcome string SELECTION, which is mapped to the next page Selection.jsp, is defined by using the <from-outcome> tag and should be returned by the action method LogInAction() if a matched login user has been found.

F.The name of the next page, Selection.jsp, is defined by using the <to-view-id> tag.

The points to be noted for this configuration file are:

1.Both outcome string and the next page should be defined inside the <navigationcase> tag, and all navigation pages should be defined inside the <navigation-rule> tag.

2.The forward-slash symbol “/” before each page name is used to indicate that those pages are located at the current location as the JSF project is located.

3.You can create and edit this configuration file using either the XML editor or the PageFlow design tool.

In order to use the PageFlow design tool to build the navigation rules in the faces-config. xml file, sometimes you need to close and reopen the NetBeans IDE to do this.

The codes for a sample LogIn.jsp page is shown in Figure 8.34. Let’s have a closer look at this piece of codes to see how it works.

A.Two JSF standard customer tag libraries, one is for building JSF applications that render to an HTML client, and another is for representing core actions independent of a particular

8.1 A Historical Review about Java Web Application Development 595

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LogIn Page</title>

</head>

A<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <body>

B<f:view>

C<h:form id="LogInForm">

D<h:inputText id="userName" required="true" value="#{LogInBean.userName}" size="10" maxlength="40">

E<f:validateLength minimum="1" maximum="40"/> </h:inputText>

F<h:inputSecret id="passWord" required="true" value="#{LogInBean.passWord}" size="10" maxlength="20">

G<f:validateLength minimum="6" maximum="20"/>

</h:inputSecret>

H <h:commandButton id="LogIn" action="#{LogInBean.LogInAction}" value="LogIn" />

</h:form>

</f:view>

</body>

</html>

Figure 8.34. The codes of a sample LogIn.jsp page.

render kit, are declared first at this page using the <%@taglib%> directive. The uri is used to indicate the valid sites where both libraries are located.

B.All of JSF tag components are represented by a tree of components whose root is the UIViewRoot, which is represented by the <f:view> tag. All JSF component tags must be enclosed in this <f: view> tag.

C.A JSP form, which is submitted to the Web server when a button is clicked, is represented by the <h:form> tag. The tags representing the form components, such as textfields and buttons, must be nested inside this form tag. The form is identified by its id, here it is a LogInForm.

D.An inputText tag is used to represent an input field to allow the user to enter one line of text string, such as a username in this example. This inputText tag is identified by its id, and the required attribute is set to true. This means that this inputText cannot be empty and must be filled something by the user as the project runs. The value attribute of this inputText tag is bound to the property userName in the Java bean class, LogInBean, by using the EL value expression. Two points to be noted for this tag is: (1) the value of this tag’s id must be identical with the property name userName defined in the Java managed bean LogInBean, and (2) the value attribute of this tag must be bound to the same property userName defined in the Java managed bean LogInBean class, too. In this way, any updating made to this property userName in the Java bean can be immediately reflected to the value of this inputText tag, and furthermore, displayed in this input field.

E.A <f:validateLength> tag is used to make sure that the length of this username is in the range defined by the minimum and maximum attributes.

F.A similar tag is used for the passWord inputText, and it is bound to the passWord

property defined in the Java-managed bean LogInBean class. The only difference between this tag and the userName inputText tag is that a <h:inputSecret> tag is used to replace the <h:inputText> tag since this is a way to present a password input style.

596 Chapter 8 Developing Java Web Applications to Access Databases

@ManagedBean(name="LogInBean")

@SessionScoped

public class LogInBean {

/** Creates a new instance of LogInBean */ public LogInBean() {

}

Aprivate String userName; private String passWord;

Bpublic String getPassWord() {

return passWord;

}

C public void setPassWord(String passWord) { this.passWord = passWord;

}

D public String getUserName() { return userName;

}

E public void setUserName(String userName) { this.userName = userName;

}

Fpublic String LogInAction()

{

String result=null; result = LogInQuery();

return result;

}

Gpublic String LogInQuery()

{

//query username from database and assign the queried value to the userName property

//query password from database and assign the queried value to the passWord property

return "SELECTION";

}

}

Figure 8.35. The codes for the Java bean class LogInBean.

G.A <f:validateLength> tag is also used to validate the length of the passWord to make sure that it is in the required range.

H.A <h:commandButton> tag is used to present a submit button component and its action attribute is bound to the action method defined in the Java managed bean LogInBean using the EL value expression “#{LogInBean.LogInAction}”.

8.1.7.5.2 The Detailed Codes for the Java Bean Class The codes for the Java bean class LogInBean.java are shown in Figure 8.35. The functionality of each part of these codes is illustrated below.

A.Two properties, userName and passWord, are defined first, and these two properties must be identical with the id attributes defined in the inputText and inputSecret tags in the JSF page LogIn.jsp we discussed above.

B.The associated getter methods for these two properties are declared and defined in steps B and D, respectively.

C.The associated setter methods for these two properties are defined in steps C and E.

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