630 likes | 850 Views
Web Tier Frameworks. Java Server Faces. Tapestry. Spring. Struts. Java Server Faces. WebWork. WebObjects. Echo. WingS. Maverick. Frameworks, frameworks, frameworks. JavaServer Faces is a “framework” for developing web-based UIs in Java.
E N D
Web Tier Frameworks Java Server Faces
Tapestry Spring Struts Java ServerFaces WebWork WebObjects Echo WingS Maverick
Frameworks, frameworks, frameworks • JavaServer Faces is a “framework” for developing web-based UIs in Java. • Frameworks are extremely common these days, and for a good reason: • they help make web development easier. • Like most Java web frameworks, JSF enforces a clean separation of presentation and business logic. • It focuses more on the UI side of things and can be integrated with other frameworks, like Struts.
JSF Technology • “Java Server Faces technology is a server-side user interface component framework for Java technology-based web applications” • The main components of JavaServer Faces technology are as follows: • An API for representing UI components and managing their state • Two JavaServer Pages (JSP) custom tag libraries for expressing UI components
JSF Benefits • The JSF specification lists the following ways that JSF helps web application developers to create user interfaces (UIs): • Makes it easy to construct a UI from a set of reusable UI components • Simplifies migration of application data to and from the UI • Helps manage UI state across server requests • Provides a simple model for wiring client-generated events to server-side application code • Allows wiring client-generated events to server-side application code
JSF • The primary design pattern of JSF is the Model-View-Controller (MVC) pattern. • JSP was designed to make the view component of a web application easy to create and manage. • JSF brings a component-based model to web application development • Similar to the model used in stand-alone GUI applications
JSF Applications • JavaServer Faces applications are similar to any other Java web application. • They run in a servlet container, and they typically contain the following: • JavaBeans components containing application-specific functionality and data • Event listeners • Pages, such as JSP pages • Server-side helper classes, such as database access beans
JSF Environment • Requirements • standard web container • implementation of the framework • jsf-api.jar, jsf-impl.jar, jstl.jar, standard.jar • commons-collections.jar, commons-digester.jar, commons-logging.jar, commons-beanutils.jar
JSF Environment - Configuration <web-app> ... <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class> javax.faces.webapp.FacesServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> ... </web-app>
JSF – The key pieces of the pie • Custom Tag Libraries • UI component (a control or simply a component) • Renderer • Validator • Backing beans • Converter • Events and listeners • Messages • Navigation
Two Custom Tag Libraries • The component tag library eliminates the need to hardcode UI components in HTML or another markup language, resulting in completely reusable UI components. • The core tag library makes it easy to register events, validators, and other actions on the components.
User Interface Components • User interface (UI) components focus on interacting with an end user • Like Swing controls, they’re built on top of JavaBeans • They have properties, methods, and events • Packaging UI elements as a component (like a toolbar or a calendar) makes development easier because the core functions are encapsulated within a reusable piece of code • UI component is a stateful object, maintained on the server, and provides specific functionality for interacting with an end user • Example: HtmlInputText
Renderer • Responsible for displaying a UI component and translating a user’s input into the component's value • Renderers can be designed to work with one or more UI components, and a UI component can be associated with many different renderers • <h:inputText id="inputText" size="20" maxlength="30"/> • <input id="myForm:inputText" type="text" name="myForm:inputText“ maxlength="30" size="20" />
Validators • Responsible for ensuring that the value entered by a user is acceptable • One or more validators can be associated with a single UI component • Validation is handled on the server, because all clients do not support scripting • Validators provide a powerful framework to help simplify this task • JSF ships with a set of standard validators for such things as the length or range of the input, but you can write your own, and so will third parties
Backing beans • Specialized JavaBeans that collect values from UI components and implement event listener methods • JSF allows you to declaratively associate backing beans with UI components. • with markup instead of code • You associate a component with a backing bean via the JSF expression language • Similar to the JSTL EL
Backing Beans • <h:outputText id="helloBeanOutput“ value="#{helloBean.numControls}"/> • hooks up an HtmlOutputText component’s value directly to the numControls property of an object called helloBean.
Managed Beans • JSF provides a declarative mechanism called the Managed Bean Creation facility to allow the creation of backing beans <managed-bean> <managed-bean-name>helloBean</managed-bean-name> <managed-bean-class>com.virtua.jsf.sample.hello.HelloBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> • This tells JSF to create an instance of the HelloBean class called helloBean, and store it in the user’s session. • This little snippet is all that’s required to make an object available for integration with UI components. • Any objects that use this facility are called managed beans.
Converter • Converts a component’s value to and from a string for display • A UI component can be associated with a converter • JSF ships with converters for common types like dates and numbers • Converters also handle formatting and localization. <h:outputText value="#{user.dateOfBirth}"> <f:convert_datetime type="both" dateStyle="full"/> </h:outputText>
Events and listeners • JSF uses the JavaBeans event/listener model (also used by Swing). • UI components generate events, and listeners can be registered to handle those events. • In a JSF application, Integrating application logic is a matter of assigning the appropriate listeners to components that generate events that the listeners understand.
Events and listeners • There are four standard events: • Value-change events • Action events • Data model events • Fired when a data-aware component selects a row for processing • Phase events • Execute while JSF processes an HTTP request
Value-Change Events • Value-change events are generated by input controls when the user enters a new value into an input component. • Value-change listeners handle Value-change events • <h:inputText valueChangeListener= "#{myForm.processValueChanged}"/> • When a user changes the text in the control and submits the form, JSF will generate a value-change event public void processValueChanged(ValueChangeEvent event){ HtmlInputText sender = (HtmlInputText)event.getComponent(); sender.setReadonly(true); }
Action events • Generated when a user activates a command component • Components that generate action events, also called action sources, include controls such as buttons or hyperlinks • Action events are handled by action listeners • Action Listeners may or may not affect navigation
Action Listeners • Action listeners that affect navigation typically perform some processing and then return a logical outcome that is used by JSF’s navigation system to select the next page • Listeners that don’t affect navigation usually manipulate components in the current view, or perform some processing that changes model object, but doesn’t alter the current page the user is accessing. • the page is usually redisplayed after the listener finishes executing.
Action Listeners • Technically, all navigation is handled by a single action listener. • This listener automatically handles any action events fired by a component, so it doesn’t need to be registered manually. • By default, this action listener delegates all of its work to action methods in your backing beans, so you can have different action methods handle different parts of your application.
Action Methods • <h:commandButton type="submit" value="Login“ action="#{loginForm.login}"/> • When a user clicks on this button, an action event is fired, and a method login in the loginForm bean is executed public class LoginForm { ... public String login(){ if (...) {// login is successful return "success"; } else{ return "failure"; }} ... } • The control would be forwarded based on the return string
Action Listener Methods • When you need to execute application logic that is not associated with navigation, you can associate an action listener method with a component <h:commandButton id="redisplayCommand" type="submit" value="Redisplay“ actionListener="#{myForm.doIt}"/> • Unlike action methods, action listener methods have access to the component that fired the event as well.
Action Listener Methods public void doIt(ActionEvent event){ HtmlCommandButton button = (HtmlCommandButton)event.getComponent(); button.setValue("It's done!"); }
Data model events • Data model events are triggered when a data-aware component processes a row. • The most common way to trigger this event is through a component that displays a selectable list of items, such as HtmlDataTable, which is the quintessential “data grid” component. • Unlike value-change or action event listeners, data model event listeners must implement a Java interface
Data Model Event Listener FacesContext facesContext = FacesContext.getCurrentInstance(); dataTable = (HtmlDataTable)facesContext.getApplication().createComponent( HtmlDataTable.COMPONENT_TYPE); DataModel myDataModel = new ResultSetDataModel(myResultSet); myDataModel.addDataModelListener(new DataModelListener() { public void rowSelected(DataModelEvent e){ FacesContext.getCurrentInstance().getExternalContext().log("row selected:" + e.getRowIndex()); }}); dataTable.setValue(myDataModel);
Phase Events • Whenever a JSF application receives a request, it goes through a six-step process called the Request Processing Lifecycle.
Messages • Information that’s displayed back to the user. • Just about any part of the application (backing beans, validators, converters, and so on) can generate information or error messages that can be displayed back to the user • <h:message id="errors" for="helloInput" style="color: red"/> • This tag displays all errors that were generated for the helloInput input component
Navigation • The ability to move from one page to the next. • JSF has a powerful navigation system that is integrated with specialized event listeners. • The navigation handler is responsible for deciding what page to load based on the logical outcome of an action method
Navigation – Rule & Case • For any given page, a navigation rule defines what outcomes are understood, and what pages to load based on those outcomes. • A navigation rule specifies which pages can be selected from a specific page or set of pages. • Each specific mapping between an outcome and a page is called a navigation case. • The rules are defined in a JSF configuration file.
Navigation Configuration • Here is a navigation rule with the two cases for the page login.jsp—the "success" and "failure" outcomes: <navigation-rule> <from-view-id>/login.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/mainmenu.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>failure</from-outcome> <to-view-id>/login.jsp</to-view-id> </navigation-case> </navigation-rule>
JSF Standard UI Components • The most central feature of JSF is its support for UI components—this is what sets it apart from many other web development frameworks • JSF ships with a standard set of components that are intended to provide support for typical HTML UIs.
JSF HTML Components • HtmlCommandButton • A form button that is an action source and can execute an action method. • HtmlCommandLink • A hyperlink that is an action source and can execute an action method. • HtmlDataTable • A data-aware table with customizable headers, footers, and other properties. • Can connect to multiple types of data sources.
JSF HTML Components • HtmlForm • An input form; must enclose all input components • HtmlGraphicImage • Displays an image based on its URL • HtmlInputHidden • An input field of type “hidden”. • HtmlInputSecret • An input field of type “password”. • HtmlInputText • An input field of type “text”. • HtmlInputTextarea • A text area (multi-line input field).
JSF HTML Components • HtmlMessage • Displays messages for a specific component. • HtmlMessages • Displays all messages (component-related and/or application-related). • HtmlOutputFormat • Outputs parameterized text. • HtmlOutputLabel • A text label for an input field. • HtmlOutputText • Plain text, with optional CSS formatting.
JSF HTML Components • UIParameter • An invisible component used to configure other components. • HtmlPanelGrid • A table with customizable headers, footers, and other properties. • HtmlPanelGroup • Groups components together for use inside of other components, and to apply common styles or hide/display a group of components. • HtmlSelectBooleanCheckbox • A single checkbox.
JSF HTML Components • UISelectItem • Represents a single item or item group for use in SelectMany and SelectOne components. • UISelectItems • Represents a collection of items or item groups for use in SelectMany and SelectOne components. • HtmlSelectManyCheckbox • A table with a list of checkboxes, grouped together. • HtmlSelectManyListbox • A listbox that allows you to select multiple items. • HtmlSelectManyMenu • A multi-select listbox that shows one available option at a time.
JSF HTML Components • HtmlSelectOneRadio • A table of radio buttons, grouped together • HtmlSelectOneListbox • A listbox that allows you to select a single item • HtmlSelectOneMenu • A drop-down listbox that allows you to select a single item • UIViewRoot • Represents entire view; contains all components on the page
A Simple JSF Application • Flight reservation system
Implementing a JavaBean • We’ll start this example by showing the JavaBean class that represents the business layer of the web application. • This bean will be connected to the presentation layer by the JSF system. • It represents the information necessary to search for a flight in the system. • The FlightSearch class, is used to store the search parameters entered by the user. • For this example, we have chosen to include the following search criteria • origination airport, destination airport, departure date and time, and arrival date and time.