Using JavaServer Faces Technology for Java

Một phần của tài liệu practical database aprogramming with java (Trang 459 - 471)

JAVA RUNTIME OBJECTS METHOD

8.1.7 Using JavaServer Faces Technology for Java

JavaServer Faces (JSF) provides new techniques and components for building User Interfaces ( UI ) for server - side applications. In fact, JSF is a server - side technology for developing Web applications with rich user interfaces. Before JavaServer Faces, develop- ers who built Web applications had to rely on building HTML user interface components with Servlets or JSP. This is mainly because HTML user interface components are the lowest common denominator that Web browsers support. One of the defects of using HTML or JSP techniques to build Web applications is that such Web applications do not have rich user interfaces, compared with standalone fat clients, and therefore less func- tionality and/or poor usability are involved in those Web applications. One of possible solutions is to use Applets to develop rich user interfaces; however, in most cases, Web application developers do not always know whether those Applets are signed or unsigned applets, and whether they can access the local database fi les or not. This will greatly limit the roles and implementations of Applets in Java Web database applications.

A good solution is to use JavaServer Face technique that provides a set of rich GUI components and can be installed and run in the server side. The GUI components pro- vided by JSF are represented by a collection of component tags. All component tags are defi ned and stored in the UIComponent class. A model - view - controller ( MVC ) mode is applied to the JSF technique.

The JSF technology consists of following main components:

• JSF APIs used to represent UI components, manage state, handle events, and validate input.

The UI components are represented and implemented using JSF tags. The API has support for internationalization and accessibility.

• A special Servlet class FacesServlet that is located at the server side and works as a controller to handle all JSF - related events.

• JSP pages that contain rich user interface components represented by customer tags and work as views. The GUI of a JSF page is one or more JSP pages that contain JSF component tags.

• Two JSP custom tag libraries used for expressing the JSF user interface (UI) components within a JSP page, and for wiring components to server - side objects. Page authors can easily add UI components to their pages.

• Java bean components used to work as model objects.

• Application confi guration resource fi le faces - confi g.xml used to defi ne the navigation rules between JSP pages and register the Java backing beans.

• Web deployment descriptor fi le web.xml used to defi ne the FaceServlet and its mapping.

JavaServer Face technology is basically built based on JavaServer Page and Servlet techniques. It uses JSP pages as the GUI and FacesServlet as the Web container. A high - level architecture of JSF is shown in Figure 8.25 .

It can be found from Figure 8.25 that a JSF Web application is composed of JSP pages representing the user interface components using the JSF custom tag library and FacesServlet Web container, which can be considered as a part of Servlet class and takes care of the JSF related events.

JSF defi nes two standard tag libraries (Core and HTML) that you have to declare in your JSP pages with the < %@taglib% > directive. Two tag libraries are:

• html_basic.tld : A JSP custom tag library for building JSF applications that render to an HTML client.

• jsf_core.tld : A JSP custom tag library for representing core actions independent of a par- ticular render kit.

The JSF core library contains tags that do not depend on any markup language, while the JSF HTML library was designed for pages that are viewed in a Web browser. The standard prefi xes of the two tag libraries are f for the JSF Core and h for the JSF HTML.

All JSF tags must be nested inside a < f:view > element. The < f:view > tag allows the JSF framework to save the state of the UI components as part of the response to a HTTP request.

To use these customer tags to represent JSF components in JSP pages, one needs to indicate them by using the following two taglib directive on the top of each JSF fi le:

• < %@ taglib uri= “ http://java.sun.com/jsf/html ” prefi x= “ h ” % >

• < %@ taglib uri= “ http://java.sun.com/jsf/core ” prefi x= “ f ” % >

The uri is used to indicate the locations of the customer tag libraries.

JavaServer Face (JSF) pages are just regular JSP pages that use the standard JSF tag libraries or other libraries based on the JSF API. When using JSF tag components to build a JavaServer Page, a component tree or a view is created in the server side memory, and this tree will be used by the JSF frameworks to handle the requests coming from the clients and send responses to the clients. Each JSF tag component is mapped to a com- ponent class defi ned in the UIComponent class. In fact, each tag is an instance of the mapped class in the UIComponent .

JSF utilized an MVCarchitecture, which means that it uses Java beans as models to stored application data, and JSF GUI as the view and the Servlet as the controller.

8.1.7.1 The Application Confi guration Resource File faces - confi g.xml

The navigation from one page to another can be done in two ways. One way is directly to use the codes by writing the JSP tag such as < jsp:forward / > or the HTML hyperlink

Figure 8.25. High - level architecture of JSF.

JSF APP JSF Tags

JSF APP

JSP JSF API

Servlet

c08.indd 586

c08.indd 586 7/20/2011 11:12:25 AM7/20/2011 11:12:25 AM

www.traintelco.com

in the JSF fi le. Another way that is provided by JSF is to use the application confi guration resource fi le faces - confi g.xml to build these navigation rules. The task of defi ning naviga- tion rules involves defi ning which page is to be displayed after the user clicks on a button or a hyperlink. Each < navigation - rule > element defi nes how to get from one page as defi ned by the < form - view - id > to the other pages of the application. A < navigation - rule > element can contain any number of < navigation - case > elements that defi ne the page to open next using the < to - view - id > based on a logical outcome defi ned by the < from - outcome > . This outcome is defi ned by the action attribute of the component that submits the form (such as the commandButton).

An application confi guration resource fi le, faces - confi g.xml, is used to defi ne your Java managed beans, validators, converters, and navigation rules.

Figure 8.26 shows a part of an example of an application confi guration resource fi le.

The confi guration resource fi le is composed of a sequence tags listed below:

Starting from < navigation - rule > tag, a new navigation rule is defi ned. The < from - view - id > tag is used to defi ne the navigation source, which is the current page ( Current.

jsp ). The < navigation - case > tag is used to defi ne one of the navigation destinations defi ned 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 defi ned by the < from - outcome > 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 confi guration fi le graphically.

8.1.7.2 Sample JavaServer Face Page Files

Two JSF fi les 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 user- name 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 defi ned.

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

Figure 8.26. A part of application confi guration resource fi le.

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

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 textfi elds and buttons) must be nested inside the form tag.

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

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

<html>

<head>

<title>Current 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>

<h:form id="QueryForm" >

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

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

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

value="Query" />

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

A B C D E F G

Figure 8.28. The codes for the Next.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>

<h:form id="ResponseForm" >

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

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

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

value="Back" />

</h:form>

</f:view>

</body>

</html>

A B C D

c08.indd 588

c08.indd 588 7/20/2011 11:12:25 AM7/20/2011 11:12:25 AM

www.traintelco.com

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 Unifi ed Expression Language (EL) value expression.

F. The commandButton tag represents the button used to submit the data entered in the text fi eld. The action attribute helps the navigation mechanism to decide which page to open next. Exactly, the next page has been defi ned in the application confi guration resource fi le faces - confi g.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 attri- bute 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 input- Text 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 fi eld tag in the previous sample codes to enable this text fi eld ’ s value to be updated automatically. However, in this JSF fi le, we directly bind one of backing bean ’ s properties, userName , with the value attribute of this text fi eld 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 user- Name 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 fi le. 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 fi le are shown in Figure 8.28 . The detailed function of this piece of codes is:

A. The form id is defi ned 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 defi ned in the application con- fi guration source fi le faces - confi g.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

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 control- lers 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 imme- diately refl ected to the associated property userName defi ned 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 fi nished the password matching processing and sent the matched password to the passWord property, it can be immediately updated and dis- played 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 confi gured in the application confi guration resource fi le faces - confi g.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 fi rst 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 - confi g.xml fi le:

Besides to register the Java bean class, you also need to use this confi guration fi le to confi gure and defi ne all properties created inside this Java bean. In this example, only two properties, userName and passWord , have been defi ned in this Java bean. Therefore, you need to use the < managed - property > element to do this confi guration, as shown in Figure 8.30 .

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

<managed-bean-name>QueryBean</managed-bean-name>

<managed-bean-class>LogInQuery.QueryBean</managed-bean-class>

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

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

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

c08.indd 590

c08.indd 590 7/20/2011 11:12:26 AM7/20/2011 11:12:26 AM

www.traintelco.com

In fact, you do not need to worry about these confi gurations if you are using an IDE such as the NetBeans IDE, and the NetBeans IDE can do these confi gurations automati- cally for you as you built the Java bean class fi le.

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

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 fi le web.xml . By using this deployment descriptor fi le, 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 fi le for the FacesServlet class.

Most codes in this fi le 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 confi gure your bean instances in the application confi guration resource fi le faces - confi g.xml using the < managed - bean > element. You may use multiple confi guration fi les if you develop a large application. In that case, you must add a javax.faces.CONFIG_FILES parameter in the deployment descriptor fi le 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 catego- ries: data access methods (business methods) and action methods. The data access methods

Figure 8.31. An example coding for the Web deployment descriptor fi le.

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

Một phần của tài liệu practical database aprogramming with java (Trang 459 - 471)

Tải bản đầy đủ (PDF)

(791 trang)