40
JavaServer Faces JavaServer Faces Presented by: Presented by: Jim O’Hara Jim O’Hara Ed Kausmeyer Ed Kausmeyer Jingming Zhang Jingming Zhang

JavaServer Faces

  • Upload
    kara

  • View
    84

  • Download
    0

Embed Size (px)

DESCRIPTION

JavaServer Faces. Presented by: Jim O’Hara Ed Kausmeyer Jingming Zhang. Introducing JavaServer Faces (JSF). New and upcoming web application framework for building user interfaces (UI’s) for web applications For building server-side UI’s - PowerPoint PPT Presentation

Citation preview

JavaServer FacesJavaServer Faces

Presented by:Presented by:

Jim O’HaraJim O’Hara

Ed KausmeyerEd Kausmeyer

Jingming ZhangJingming Zhang

Introducing JavaServer Introducing JavaServer Faces (JSF)Faces (JSF)

New and upcoming web application framework for New and upcoming web application framework for building user interfaces (UI’s) for web applicationsbuilding user interfaces (UI’s) for web applications

For building server-side UI’sFor building server-side UI’s Accomplishes the Model-View-Controller (MVC) Accomplishes the Model-View-Controller (MVC)

paradigmparadigm Designed to be flexible and easy to useDesigned to be flexible and easy to use Leverages existing standard UI and web-tier Leverages existing standard UI and web-tier

concepts without limiting developers to a concepts without limiting developers to a particular mark-up language, protocol, or client particular mark-up language, protocol, or client devicedevice

Comparable to the well-known Struts FrameworkComparable to the well-known Struts Framework Features and concepts that are beyond those of Struts, Features and concepts that are beyond those of Struts,

especially the component orientationespecially the component orientation

Introducing JavaServer Introducing JavaServer Faces (JSF)Faces (JSF)

Set of APIs for representing UI components Set of APIs for representing UI components and managing their state, handling events and managing their state, handling events and input validation, defining page and input validation, defining page navigation, and supporting navigation, and supporting internationalization and accessibilityinternationalization and accessibility

A JavaServer Pages (JSP) custom tag library A JavaServer Pages (JSP) custom tag library for expressing a JSF interface within a JSP for expressing a JSF interface within a JSP pagepage JSF version 1.0 relies on JSP 1.2JSF version 1.0 relies on JSP 1.2 Since JSP 2.0 is a superset of JSP 1.2, it is possible Since JSP 2.0 is a superset of JSP 1.2, it is possible

to use JSF 1.0 with JSP 2.0to use JSF 1.0 with JSP 2.0 Future versions of the JSF specification will be Future versions of the JSF specification will be

able to take better advantage of JSP 2.0able to take better advantage of JSP 2.0

Standardization of JSFStandardization of JSF JavaServer Faces Developer Forum: JavaServer Faces Developer Forum:

http://forum.java.sun.com/forum.jspa?forumIDhttp://forum.java.sun.com/forum.jspa?forumID=427=427

JSF APIs are being designed so that they can JSF APIs are being designed so that they can be leveraged by tools that will make web be leveraged by tools that will make web application development even easierapplication development even easier

Developed through the Java Community Developed through the Java Community Process under JSR-127Process under JSR-127 JSRs: Java Specification RequestsJSRs: Java Specification Requests JSR-127: JSR-127: http://www.jcp.org/en/jsr/detail?id=127http://www.jcp.org/en/jsr/detail?id=127 JSR-252: JSR-252: http://jcp.org/en/jsr/detail?id=252http://jcp.org/en/jsr/detail?id=252

A number of important industry players are A number of important industry players are collaborating with Sun to develop the JSF collaborating with Sun to develop the JSF specificationspecification Many prominent tool vendors are part of the expert Many prominent tool vendors are part of the expert

group and are committed to supporting the JSF group and are committed to supporting the JSF technology in their tools, thus promoting the technology in their tools, thus promoting the adoption of the JSF technology standardadoption of the JSF technology standard

JSF User InterfacesJSF User Interfaces

A UI created with JSF handles all the A UI created with JSF handles all the complexities of UI managementcomplexities of UI management Input validation, component-state management, Input validation, component-state management,

page navigation, and event handlingpage navigation, and event handling The UI component classes encapsulate the The UI component classes encapsulate the

component functionality, not the client-component functionality, not the client-specific presentationspecific presentation UI components can be rendered to various UI components can be rendered to various

client devicesclient devices Renderers: define rendering attributes for a Renderers: define rendering attributes for a

specific UI componentspecific UI component

JSF User InterfacesJSF User Interfaces

By combining the UI component functionality By combining the UI component functionality with custom renderers, developers can construct with custom renderers, developers can construct custom tags to a particular client devicecustom tags to a particular client device Device Independence: By defining only component Device Independence: By defining only component

functionality in extensible UI component classes, JSF functionality in extensible UI component classes, JSF allows component developers to extend the component allows component developers to extend the component classes to generate their own component tag libraries classes to generate their own component tag libraries targeted for specific clientstargeted for specific clients

JSF provides a custom renderer and a JSP custom JSF provides a custom renderer and a JSP custom tag library for rendering to an HTML clienttag library for rendering to an HTML client Allows developers of Java 2 Platform, Enterprise Allows developers of Java 2 Platform, Enterprise

Edition (J2EE) applications to use JSF technology in Edition (J2EE) applications to use JSF technology in their applicationstheir applications

Benefits of the JSF Benefits of the JSF DesignDesign

The JSF architecture clearly defines a The JSF architecture clearly defines a separation between application logic and separation between application logic and presentation while making it easy to connect presentation while making it easy to connect the presentation layer to the application the presentation layer to the application codecode

With this simple, well-defined programming With this simple, well-defined programming model, developers of varying skill levels can model, developers of varying skill levels can quickly and easily build Web applications by quickly and easily build Web applications by assembling reusable UI components in a assembling reusable UI components in a page, connecting these components to an page, connecting these components to an application data source, and wiring client-application data source, and wiring client-generated events to server-side event generated events to server-side event handlershandlers

Benefits of the JSF Benefits of the JSF DesignDesign

These web applications handle all of the These web applications handle all of the complexity of managing the UI on the complexity of managing the UI on the server, allowing each member of a web server, allowing each member of a web application development team to focus on application development team to focus on their piece of the development process (i.e., their piece of the development process (i.e., their application code)their application code) Allows a wide range of users, from web-page Allows a wide range of users, from web-page

designers to component developers, to take designers to component developers, to take advantage of JSFadvantage of JSF Example: Web page developers with no programming Example: Web page developers with no programming

expertise can use JSF UI component tags to link to expertise can use JSF UI component tags to link to application code from within a web page without application code from within a web page without writing any scriptswriting any scripts

Division of labor, shorter development cycleDivision of labor, shorter development cycle

Benefits of the JSF Benefits of the JSF DesignDesign

How various developers and web-page designers How various developers and web-page designers can take advantage of JSF's extensibility, ease-of-can take advantage of JSF's extensibility, ease-of-use, and capabilities:use, and capabilities: Page AuthorsPage Authors

Build the UI using component tags from within web pages, such Build the UI using component tags from within web pages, such as JSP pagesas JSP pages

Probably the primary users of the JSF custom tag libraryProbably the primary users of the JSF custom tag library Application DevelopersApplication Developers

Write the application code, including the data-access, event-Write the application code, including the data-access, event-handling, and business logichandling, and business logic

Component WritersComponent Writers Construct reusable UI componentsConstruct reusable UI components Take advantage of the extensibility of the UI component classes Take advantage of the extensibility of the UI component classes

to build custom components that can be targeted for a specific to build custom components that can be targeted for a specific clientclient

Tools VendorsTools Vendors Build tools leveraging JSF technology to make building a UI Build tools leveraging JSF technology to make building a UI

even easiereven easier

JSF and MVC JSF and MVC

JavaServer Faces (JSF) technology JavaServer Faces (JSF) technology is a new user interface framework is a new user interface framework for J2EE applications. It is for J2EE applications. It is particularly suited, by design, for particularly suited, by design, for use with applications based on the use with applications based on the MVC (Model-View-Controller) MVC (Model-View-Controller) architecture. architecture.

MVCMVC(Model-View-Controller)(Model-View-Controller)

MVC was first described by Xerox in a MVC was first described by Xerox in a number of papers published in the late 1980s, number of papers published in the late 1980s, in conjunction with the Smalltalk language. in conjunction with the Smalltalk language. This model has since been used for GUI This model has since been used for GUI applications developed in all popular applications developed in all popular programming languages.programming languages.

The basic idea is to separate the application The basic idea is to separate the application data and business logic, the presentation of data and business logic, the presentation of the data, and the interaction with the data the data, and the interaction with the data into distinct entities labeled the Model, the into distinct entities labeled the Model, the View, and the Controller, respectively.View, and the Controller, respectively.

The MVC design pattern splits an The MVC design pattern splits an application design into three application design into three

separate parts:separate parts: The Model handles data and logic. Model The Model handles data and logic. Model

code accesses and represents data, and code accesses and represents data, and handles business operations. "Business handles business operations. "Business operations" include changes to both operations" include changes to both persistent business data, and to things like persistent business data, and to things like shopping cart contentsshopping cart contents

The View handles output. View code The View handles output. View code displays data to the user.displays data to the user.

The Controller handles input. Controller The Controller handles input. Controller code manipulates the Model or changes the code manipulates the Model or changes the view accordingly in response to user input view accordingly in response to user input (the Controller can also do both). (the Controller can also do both).

These parts have specific These parts have specific relationships to one relationships to one

another: another: The View accesses the Model to retrieve data The View accesses the Model to retrieve data

for display.for display. The Controller receives user input, and makes The Controller receives user input, and makes

business method invocations on the Model.business method invocations on the Model. The Controller updates the View, or selects a The Controller updates the View, or selects a

new View, based on the state of the Model new View, based on the state of the Model and on the its own View navigation rules.and on the its own View navigation rules.

The Model provides data to the View, but The Model provides data to the View, but knows nothing about how that data is knows nothing about how that data is presented. The Model also provides business presented. The Model also provides business services to the Controller, but knows nothing services to the Controller, but knows nothing about user events the Controller might have about user events the Controller might have received. received.

How does JSF fit How does JSF fit into the overall into the overall

MVC architecture?MVC architecture?

Model-View-Controller Model-View-Controller PatternPattern

Model = Persistent dataModel = Persistent data View =JSPView =JSP Servlet =Controller =FacesServletServlet =Controller =FacesServlet

To create a JSF application, To create a JSF application, you typically perform the you typically perform the

following steps: following steps:

1.1. Define and implement the application Define and implement the application Model classes Model classes

2.2. Describe the Model to the framework Describe the Model to the framework

3.3. Create application Views using JSP Create application Views using JSP pages pages

4.4. Define data validation rules Define data validation rules

5.5. Define View navigation for the Define View navigation for the Controller Controller

                                                                                                                                                                         

                                                                                   

                                                                                                                                                                                                                                                

                                       

Defining the Model Defining the Model public class DataBean {public class DataBean { protected String _string;protected String _string; protected long _n_long;protected long _n_long; protected double _n_real;protected double _n_real; public DataBean() {public DataBean() { _string = "Default";_string = "Default"; _n_long = 1000;_n_long = 1000; _n_real = 0.5;_n_real = 0.5; }} public String getString() { return _string; }public String getString() { return _string; } public void setString(String string) { public void setString(String string) { _string = string; }_string = string; } public long getLongnumber() { return _n_long;}public long getLongnumber() { return _n_long;} public void setLongnumber(long n_long) {public void setLongnumber(long n_long) { _n_long = n_long; }_n_long = n_long; } public double getRealnumber() { public double getRealnumber() { return _n_real; }return _n_real; } public void setRealnumber(double n_real) { public void setRealnumber(double n_real) { _n_real = n_real; }_n_real = n_real; } }}

Describe the Model to Describe the Model to JSF JSF

<managed-bean><managed-bean>

<managed-bean-name>data</managed-<managed-bean-name>data</managed-bean-name>bean-name>

<managed-bean-class><managed-bean-class>

com.elucify.tips.mar2004.DataBeancom.elucify.tips.mar2004.DataBean

</managed-bean-class></managed-bean-class>

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

</managed-bean></managed-bean>

Create Application Views Create Application Views <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <html><html> <head><head> <title>Validating JSF Page</title><title>Validating JSF Page</title> </head></head> <body><body> <h1>Please enter the requested data</h1><h1>Please enter the requested data</h1> <f:view><f:view> <h:form><h:form> <b>Enter a string from three to twelve <b>Enter a string from three to twelve characters in length:</b><br/>characters in length:</b><br/> <h:inputText id="string" required="true"<h:inputText id="string" required="true" value="#{data.string}" size="20">value="#{data.string}" size="20"> <f:validateLength minimum="3" maximum="12"/><f:validateLength minimum="3" maximum="12"/> </h:inputText></h:inputText> <h:message for="string" style="color: red;"/><h:message for="string" style="color: red;"/> <br/><br/> <p><p> ...... </f:view></f:view> </body></html></body></html>

Defining Data Validation Defining Data Validation When the user posts an input form to the Controller, the When the user posts an input form to the Controller, the

Controller validates each of the inputs Controller validates each of the inputs

<h:inputText id="string" required="true"<h:inputText id="string" required="true"

value="#{data.string}" size="20">value="#{data.string}" size="20">

<f:validateLength minimum="3" maximum="12"/><f:validateLength minimum="3" maximum="12"/>

</h:inputText></h:inputText>

<h:message for="string" style="color: red;"/><h:message for="string" style="color: red;"/>

<br/><br/>

This example shows how to perform server-side validation. This example shows how to perform server-side validation. JSF also provides a way to perform the requested JSF also provides a way to perform the requested validations on the client side. The default implementation validations on the client side. The default implementation of client-side validation runs as JavaScript in the Web of client-side validation runs as JavaScript in the Web browser. browser.

Defining View Navigation Defining View Navigation for the Controller for the Controller

<h:commandButton id="submit"<h:commandButton id="submit" action="validated"action="validated" value="Submit values"/>value="Submit values"/>

In this case, the commandButton tells the Controller to In this case, the commandButton tells the Controller to execute the "validated" action if all inputs are valid. execute the "validated" action if all inputs are valid.

<navigation-rule><navigation-rule> <from-view-id>/jsp/values.jsp</from-view-id><from-view-id>/jsp/values.jsp</from-view-id> <navigation-case><navigation-case> <from-outcome>validated</from-outcome><from-outcome>validated</from-outcome> <to-view-id>/jsp/valid.jsp</to-view-id><to-view-id>/jsp/valid.jsp</to-view-id> </navigation-case></navigation-case></navigation-rule></navigation-rule>

This rule tells the Controller the following: if you receive This rule tells the Controller the following: if you receive valid inputs from a form in the page /jsp/values.jsp, and the valid inputs from a form in the page /jsp/values.jsp, and the action is 'validated', then go to page /jsp/valid.jsp. action is 'validated', then go to page /jsp/valid.jsp.

Why JavaServer FacesWhy JavaServer Faces The promise of JSF is to bring rapid The promise of JSF is to bring rapid

user-interface development to server-user-interface development to server-side Java.side Java.

JSF has these parts:JSF has these parts: a set of pre-fabricated UI componentsa set of pre-fabricated UI components an event-driven programming modelan event-driven programming model A component model that enables third-party A component model that enables third-party

developers to supply additional componentsdevelopers to supply additional components

A Simple JSF A Simple JSF ApplicationsApplications

Code behind the

page

<body> <h:outputText value="#{msgs.pageTitle}"/> <p> <h:form> <h:dataTable value="#{tableData.names}" var="name"> <h:column> <h:outputText value="#{name.last}"/> <f:verbatim>,</f:verbatim> </h:column>

<h:column> <h:outputText value="#{name.first}"/> </h:column> </h:dataTable> </h:form> </body>

Web Application AnalysisWeb Application Analysis

Web applications have two parts: Web applications have two parts: the presentation layer and the the presentation layer and the business logic.business logic.

The presentation layer is concerned The presentation layer is concerned with the look of the application.with the look of the application. In “browser-speak”, the look is In “browser-speak”, the look is

determined by the HTML tags that determined by the HTML tags that specify the layout, fonts, images and specify the layout, fonts, images and other elements to display the page.other elements to display the page.

Web Application AnalysisWeb Application Analysis

The business logic is implemented in The business logic is implemented in the Java code that determines the the Java code that determines the behavior of the application.behavior of the application.

Web Application AnalysisWeb Application Analysis

Some web application intermingle Some web application intermingle HTML and code.HTML and code.

The approach is easy to implement The approach is easy to implement for simple applications in a single for simple applications in a single file.file.

For serious application development For serious application development projects, mixing markup and code projects, mixing markup and code poses considerable problems.poses considerable problems.

Behind the ScenesBehind the Scenes

UI components are managed on the server in a view, or component tree. The components can be wired directly to the values of JavaBean properties. Components are rendered to the client in HTML.

Graphic ofHTML form

A JSF form is represented internally as a tree

Name:

pw:

Submit

ValidatorsValidators

It is the responsibility of the person It is the responsibility of the person designing the UI to ensure that the user designing the UI to ensure that the user entered the correct type of informationentered the correct type of information

In web design this was usually done In web design this was usually done when validation routines written in when validation routines written in JavaScriptJavaScript

JSF handles validation in three ways:JSF handles validation in three ways: At the UI component levelAt the UI component level By validator methods in backing beansBy validator methods in backing beans By validator classesBy validator classes

Process ValidationsProcess Validations

In the Process Validation phase, JSF In the Process Validation phase, JSF traverses the component tree and traverses the component tree and interrogates each component to interrogates each component to make sure its submitted value is make sure its submitted value is acceptable.acceptable.

Validation is handled either directly Validation is handled either directly by the component or delegated to by the component or delegated to one or more validators.one or more validators.

Some JSF ExamplesSome JSF Examples

JSF JSF Code Samples and AppsCode Samples and Apps http://java.sun.com/j2ee/javaserverfaceshttp://java.sun.com/j2ee/javaserverfaces

/reference/codesamples/index.html/reference/codesamples/index.html

Servlet ConfigurationServlet Configuration

JSF applications require a servlet, JSF applications require a servlet, calledcalledFacesServlet, which acts as a front FacesServlet, which acts as a front controller for the entire application.controller for the entire application.

Servlets are configured in the web Servlets are configured in the web application’s deployment descriptor application’s deployment descriptor file, web.xmlfile, web.xml<web-app>

<servlet>

<servlet-name>Faces Servlet</servlet-name>

<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

</servlet>

Using JSP includesUsing JSP includes

One of JSP’s key features is the One of JSP’s key features is the ability to integrate content for ability to integrate content for multiple JSPs into a single page.multiple JSPs into a single page.<jsp:include page =“disclaimer.jsp”/><jsp:include page =“disclaimer.jsp”/>

……..

<jsp:include page =“footer.jsp”/><jsp:include page =“footer.jsp”/>

Issuing SQL StatementsIssuing SQL Statements

To issue SQL commands to a To issue SQL commands to a database, you need a connection database, you need a connection object.object.

Using Java Naming and Using Java Naming and Directory Interface (JNDI)Directory Interface (JNDI)

String myUri = “java:cmp/env/jdbc/mydb”;String myUri = “java:cmp/env/jdbc/mydb”;Context ctx = new InitialContext();Context ctx = new InitialContext();DataSource source (DataSource) DataSource source (DataSource)

ctx.lookup(myUri);ctx.lookup(myUri);Connection conn = source.getConnection();Connection conn = source.getConnection();

API Documentation API Documentation http://java.sun.com/j2ee/javaserverfaces/1.1_01/docs/api/

index.html

JSF GoalsJSF Goals

The core promise of JSF is support The core promise of JSF is support for UI components—reusable units for UI components—reusable units of code. of code.

JSF has a specific goal: to make web JSF has a specific goal: to make web applications with less effort.applications with less effort.

Top Ten Reasons to Prefer Top Ten Reasons to Prefer JSF to Struts JSF to Struts (David Geary’s (David Geary’s

Blog)Blog)1.1. Components Components 2.2. Render Kits Render Kits 3.3. Renderers Renderers 4.4. Value Binding Expressions Value Binding Expressions 5.5. Event Model Event Model 6.6. Extensibility Extensibility 7.7. Managed Beans (Dependency Injection) Managed Beans (Dependency Injection) 8.8. POJO Action Methods POJO Action Methods 9.9. JSF is the standard Java-based web app JSF is the standard Java-based web app

frameworkframework10.10. There's only one StrutsThere's only one Struts

References (cont’d)References (cont’d)

The J2EE 1.4 TutorialThe J2EE 1.4 Tutorialhttp://java.sun.com/j2ee/1.4/docs/tutorial/doc/http://java.sun.com/j2ee/1.4/docs/tutorial/doc/

Code Samples and AppsCode Samples and Appshttp://java.sun.com/j2ee/javaserverfaces/referenchttp://java.sun.com/j2ee/javaserverfaces/reference/codesamples/index.htmle/codesamples/index.html

Core Java ServerFacesCore Java ServerFacesDavid Geary, Cay Horstmann,David Geary, Cay Horstmann,Sun Microsystems Press Java SeriesSun Microsystems Press Java Series

http://www.jroller.com/comments/http://www.jroller.com/comments/dgeary/Weblog/dgeary/Weblog/