97
Java Server Face From the specification 2.0

Java Server Face - Université de Nantespagesperso.lina.univ-nantes.fr/~molli-p/pmwiki/uploads/... · 2010-03-15 · Java Server Face From the ... ... DataModel → ArrayDataModel,

  • Upload
    vudiep

  • View
    213

  • Download
    0

Embed Size (px)

Citation preview

Java Server Face

From the specification 2.0

JSF sources

● JSF specification 2.0● JSF sun tutorials EE6● Core Java server face (http://horstmann.com/corejsf/)● http://jsftutorials.net/● JSF Lectures from Pascal URSO (Mcf Nancy)● JSF Lectures from François Charoy (Mcf Nancy)● Intro à JSF : [email protected]● JSF and ICEFaces (?? anonymous)

My Source ??

Overview and motivations

● JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways:● 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 custom UI components to be easily built and re-used

Solving pratical problems of the web

● Managing UI component state across request

● Supporting encapsulation of the differences in markup across different browsers and clients

● Supporting form processing (multi-page, more than one per page, and so on)

● Providing a strongly typed event model that allows the application to write server-side handlers (independent of HTTP) for client generated events

● Validating request data and providing appropriate error reporting

● Enabling type conversion when migrating markup values (Strings) to and from application data objects (which are often not Strings)

● Handling error and exceptions, and reporting errors in human-readable form back to the application user

● Handling page-to-page navigation in response to UI events and model interactions.

Why JSF (From Sun Deepak Goyal et al)

● JSP and Servlet● No built-in UI component model

● Struts (I am not saying you should not use Struts)● No built-in UI component model● No built-in event model for UI components● No built-in state management for UI components● No built-in support of multiple renderers● Not a standard (despite its popularity)

● Struts and JSF can be used together

Many web frameworks want to do this

JSF

JSF Roles

Pages authors

● A page author is primarily responsible for creating the user interface of a web application.

● He or she must be familiar with the markup and scripting languages (such as HTML and JavaScript) that are understood by the target client devices, as well as the rendering technology (such as JavaServer Pages) used to create dynamic content.

● Page authors are often focused on graphical design and human factors engineering, and are generally not familiar with programming languages such as Java or Visual Basic (although many page authors will have a basic understanding of client side scriptinglanguages such as JavaScript).

Component writer

● Component writers are responsible for creating libraries of reusable user interface objects. Such components support the following functionality:● Convert the internal representation of the component’s properties and attributes

into the appropriate markup language for pages being rendered (encoding).

● Convert the properties of an incoming request—parameters, headers, and cookies—into the corresponding properties and attributes of the component (decoding)

● Utilize request-time events to initiate visual changes in one or more components, followed by redisplay of the current page.

● Support validation checks on the syntax and semantics of the representation of this component on an incoming request, as well as conversion into the internal form that is appropriate for this component.

● Saving and restoring component state across requests

Application developper

Application Developers are responsible for providing the server-side functionality of a web application that is not directly related to the user interface. This encompasses the following general areas of responsibility:

● Define mechanisms for persistent storage of the information required by JSF-based web applications (such as creating schemas in a relational database management system)

● Create a Java object representation of the persistent information, such as Entity Enterprise JavaBeans (Entity EJBs), and call the corresponding beans as necessary to perform persistence of the application’s data.

● Encapsulate the application’s functionality, or business logic, in Java objects that are reusable in web and non-web applications, such as Session EJBs.

● Expose the data representation and functional logic objects for use via JSF, as would be done for any servlet- or JSP-based application.

Tools Providers

● Tool providers, as their name implies, are responsible for creating tools that assist in the development of JSF-based applications, rather than creating such applications directly:● GUI-oriented page development tools that assist page authors in creating the user

interface for a web application

● IDEs that facilitate the creation of components (either for a particular page, or for a reusable component library)

● Page generators that work from a high level description of the desired user interface to create the corresponding page and component objects

● IDEs that support the development of general web applications, adapted to provide specialized support (such as configuration management) for JSF

● Web application frameworks (such as MVC-based and workflow management systems) that facilitate the use of JSF components for user interface design, in conjunction with higher level navigation management and other services

● Application generators that convert high level descriptions of an entire application into the set of pages, UI components, and application modules needed to provide the required application functionality

JSF Implementors

● Finally, JSF implementors will provide runtime environments that implement all of the requirements described in this specification.

● Typically, a JSF implementor will be the provider of a Java 2 Platform, Enterprise Edition (J2EE) application server, although it is also possible to provide a JSF implementation that is portable across J2EE servers.

Partial Conclusion

● JSF is clearly oriented to bootstrap an eco-system where roles are clearly defined.

● Important criteria for choosing a web-application framework...

● I did not say that JSF is the best choice...● I just said that designer of JSF took that into

account.

JSF

JSF General Approach

Archi

JSF

Dev Process

JSF dev process

● Develop backing beans● Make the link between UIComponent and your real business code.

● Is the « controler » of your business code.

● Create views with Facelets (jsf 2.0) :● reference your backing beans with the Unified Expressions language

● Set/get properties, call methods, register listeners, validators, formatters...

● Map the Faces servlet instance (general controler)● The general controler is part of the JSF framework

● Ref to Controller-oriented web architecture style.

● Run

User enter 5 in inputbox and click on submit → 1/ access UserNumberBean (declared in session)2/ set the property UserNumber to 53/ controler calls the « response.xhtml » JSF page (static navigation)

Call getResponse() on UserNumberBean in Session.

JSF

JSF Life cycle and concepts

Restore View

● « At the end of this phase, the viewRoot property of the FacesContext instance for the current request will reflect the saved configuration of the view generated by the previous Faces Response, or a new view returned by ViewHandler.createView() for the view identifier. »

● UI Component tree is created or restored from a previous call...

Apply Request Values

● « The purpose of the Apply Request Values phase of the request processing lifecycle is to give each (UI) component the opportunity to update its current state from the information included in the current request (parameters, headers, cookies, and so on). »

● Update the UI component tree...● Some component fires events (ActionEvent...)

Process Validation

● « As part of the creation of the view for this request, zero or more Validator instances may have been registered for each component. In addition, component classes themselves may implement validation logic in their validate() methods. »

● Ex:

Update Model Values

● « If this phase of the request processing lifecycle is reached, it is assumed that the incoming request is syntactically and semantically valid (according to the validations that were performed), that the local value of every component in the component tree has been updated, and that it is now appropriate to update the application's model data in preparation for performing any application events that have been enqueued. »

Invoke Application

● « If this phase of the request processing lifecycle is reached, it is assumed that all model updates have been completed, and any remaining event broadcast to the application needs to be performed. »

● « The default behavior of this method will be to broadcast any queued events that specify a phase identifier of PhaseId.INVOKE_APPLICATION »

Render Response

● « This phase accomplishes two things:● 1. Causes the response to be rendered to the client● 2. Causes the state of the response to be saved for

processing on subsequent requests. »

● Upon completion of rendering, the completed state of the view must have been saved using the methods of the class StateManager. This state information must be made accessible on a subsequent request, so that the Restore View can access it.

JSF

UI Component model

UI Component Model

● A JSF user interface component is the basic building block for creating a JSF user interface.

● A particular component represents a configurable and reusable element in the user interface, which may range in complexity from simple (such as a button or text field) to compound (such as a tree control or table).● Multiple select in tables... ??

● Components can optionally be associated with corresponding objects in the data model of an application, via value expressions (Binding).● How backed beans knows multiple selection ?

UI Component models

● Several of the standard UIComponent subclasses described in the previous section reference JavaBean components to represent the underlying model data that is rendered by those components.

● DataModel → ArrayDataModel, ListDataModel, ResultDataModel, ScalarDataModel

● SelectItem → a single choice, from among those made available to the user

● SelectItemGroup -> represents a group of subordinate SelectItem instances that can be rendered as a “sub-menu” or “option group”.

UI Component model

● JSF also supports user interface components with several additional helper APIs:● Converters—Pluggable support class to convert the markup

value of a component to and from the corresponding type in the model tier.

● Events and Listeners—An event broadcast and listener registration model based on the design patterns of the JavaBeans Specification, version 1.0.1.

● Validators—Pluggable support classes that can examine the local value of a component (as received in an incoming request) and ensure that it conforms to the business rules enforced by each Validator. Error messages for validation failures can be generated and sent back to the user during rendering.

Standard Converter

● The JavaServerTM Faces implementation provides a set of Converter implementations that you can use to convert component data.● (you can add your own)

● A standard error message associated with each of these converters. If you have registered one of these converters onto a component on your page, and the converter is not able to convert the component’s value, the converter’s error message will display on the page.

Standard converters...

<h:outputText value="#{cashier.shipDate}"> <f:convertDateTime pattern="EEEEEEEE, MMM dd, yyyy" /></h:outputText>

<h:inputText value="#{cashier.shipDate}"> <f:convertDateTime dateStyle="full" locale="Locale.SPAIN" timeStyle="long" type="both" /></h:inputText>

Converters...

● BigDecimalConverter

● BigIntegerConverter

● BooleanConverter

● ByteConverter

● CharacterConverter

● DateTimeConverter

● DoubleConverter

● EnumConverter

● FloatConverter

● IntegerConverter

● LongConverter

● NumberConverter

● ShortConverter

Standard Validators

● avaServer Faces technology provides a set of standard classes and associated tags that page authors and application developers can use to validate a component’s data.

<h:inputText id="quantity" size="4" value="#{item.quantity}" > <f:validateLongRange minimum="1"/></h:inputText><h:message for="quantity"/>

JSF

UI Components and backing bean methods

Referencing Backing bean methods

● In JSF, in a component tag, you can:● Reference a method that performs navigation

(dynamic navigation)● Reference a method that handles an action event● Reference a method that perform validation● Reference a method that handles a value-change

event

Methods for navigation

<h:commandButton value="#{bundle.Submit}" action="#{cashier.submit}" />

public String submit() { ... if(cart().getTotal() > 100.00 && !specialOffer.isRendered()) { specialOfferText.setRendered(true); specialOffer.setRendered(true); return null; } else if (specialOffer.isRendered() && !thankYou.isRendered()){ thankYou.setRendered(true); return null; } else { clear(); return ("receipt"); }}

Go to « receipt.xhtml » (if nothing in face-config.xml

Methods for action event<h:commandLink id="NAmerica" action="bookstore" actionListener="#{localeBean.chooseLocaleFromLink}">

public void chooseLocaleFromLink(ActionEvent event) { String current = event.getComponent().getId(); FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale((Locale) locales.get(current));}

Get access to UI component tree

Methods for validation

public void validateEmail(FacesContext context, UIComponent toValidate, Object value) { String message = ""; String email = (String) value; if (email.contains(’@’)) { ((UIInput)toValidate).setValid(false); message = CoffeeBreakBean.loadErrorMessage(context, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME, "EMailError"); context.addMessage(toValidate.getClientId(context), new FacesMessage(message)); }}

<h:inputText id="email" value="#{checkoutFormBean.email}" size="25" maxlength="125" validator="#{checkoutFormBean.validateEmail}"/>

Display message as validators

Methods for value changed

<h:inputText id="name" size="50" value="#{cashier.name}" required="true"> <f:valueChangeListener type="listeners.NameChanged" /></h:inputText>

public void processValueChange(ValueChangeEvent event) throws AbortProcessingException { if (null != event.getNewValue()) { FacesContext.getCurrentInstance(). getExternalContext().getSessionMap(). put("name", event.getNewValue()); }}

Update ManagedBean « name » stored in session...

Bean Validation

● @Min: The annotated element must be a number whose value must be higher or equal to the specified minimum.

● @Max: The annotated element must be a number whose value must be lower or equal to the specified maximum.

● @Size: The annotated element must be between specified minimum and maximum boundaries.

● @NotNull: The annotated element must not be null.

● @Null: The annotated element must be null.

● @Pattern: The annotated element must match the specified Java regular expression.

Validators

public class Name { @NotNull @Size(min=1, max=16) private String firstname;

@NotNull @Size(min=1, max=16) private String lastname;}

@validEmail public String getEmailAddress() { return emailAddress;}

JSF

Wire Bean instance and UI Component Instance

Wire UIComponent and beans

● The component’s tag binds the component’s value to a backing bean property using its value attribute and binds the component’s instance to a backing bean property using its binding attribute.

● all the converter, listener, and validator tags use their binding attributes to bind their associated implementations to backing bean properties.

● Attach one UIComponent instance to a bean instance : The UIComponent instance persist between requests !

Input !

<h:inputText id="name" size="50" value="#{cashier.name}" </h:inputText>

protected String name = null; public void setName(String name) { this.name = name;}public String getName() { return this.name;}

In the View In the mapped bean (cashier)

Output

<h:outputText value="#{cashier.shipDate}"> <f:convertDateTime dateStyle="full" /></h:outputText>

protected Date shipDate;public Date getShipDate() { return this.shipDate;}public void setShipDate(Date shipDate) { this.shipDate = shipDate;}

The bean property represented by this tag must be of a type of java.util.Date.

DataTable

<h:dataTable id="items" ... value="#{cart.items}" var="item" >

public synchronized List getItems() { List results = new ArrayList(); results.addAll(this.items.values()); return results;}

SelectMany

<h:selectManyCheckbox id="newsletters" layout="pageDirection" value="#{cashier.newsletters}"> <f:selectItems value="#{newsletters}"/></h:selectManyCheckbox>

protected String newsletters[] = new String[0];

public void setNewsletters(String newsletters[]) { this.newsletters = newsletters;}public String[] getNewsletters() { return this.newsletters;}

SelectBoolean

<h:selectBooleanCheckbox title="#{bundle.receiveEmails}" value="#{custFormBean.receiveEmails}" ></h:selectBooleanCheckbox><h:outputText value="#{bundle.receiveEmails}">

protected boolean receiveEmails = false; ... public void setReceiveEmails(boolean receiveEmails) { this.receiveEmails = receiveEmails; } public boolean getReceiveEmails() { return receiveEmails; }

SelectOne

<h:selectOneMenu id="shippingOption" required="true" value="#{cashier.shippingOption}"> <f:selectItem itemValue="2" itemLabel="#{bundle.QuickShip}"/> <f:selectItem itemValue="5" itemLabel="#{bundle.NormalShip}"/> <f:selectItem itemValue="7" itemLabel="#{bundle.SaverShip}"/> </h:selectOneMenu>

protected String shippingOption = "2";

public void setShippingOption(String shippingOption) { this.shippingOption = shippingOption;}public String getShippingOption() { return this.shippingOption;}

Wiring UI and Backed bean example

Writing Properties Bound to Component Instances

● A property bound to a component instance returns and accepts a component instance rather than a component value.

Bindings

h:selectBooleanCheckbox id="fanClub" rendered="false" binding="#{cashier.specialOffer}" /><h:outputLabel for="fanClub" rendered="false" binding="#{cashier.specialOfferText}" > <h:outputText id="fanClubLabel" value="#{bundle.DukeFanClub}" /></h:outputLabel>

UIOutput specialOfferText = null;

public UIOutput getSpecialOfferText() { return this.specialOfferText;}public void setSpecialOfferText(UIOutput specialOfferText) { this.specialOfferText = specialOfferText;}

UISelectBoolean specialOffer = null;

public UISelectBoolean getSpecialOffer() { return this.specialOffer;}public void setSpecialOffer(UISelectBoolean specialOffer) { this.specialOffer = specialOffer;}

Writing Properties Bound to Converters, Listeners, or Validators

<h:inputText value="#{LoginBean.birthDate}"> <f:convertDateTime binding="#{LoginBean.convertDate}" /></h:inputText>

private DateTimeConverter convertDate;public DateTimeConverter getConvertDate() { ... return convertDate;}public void setConvertDate(DateTimeConverter convertDate) { convertDate.setPattern("EEEEEEEE, MMM dd, yyyy"); this.convertDate = convertDate;}

From Pascal Urso

Managed beans and managed beans properties

ManagedBean

● EL with ManagedBeans allows the user to configure an entire complex tree of POJO beans, including how they should be scoped and populated with initial values, and expose them to EL expressions

● A managed bean defined as :● <managed-bean-name>, <managed-bean-class>,

<managed-bean-scope>, <managed-property>

Managed Properties

● Zero or more elements used to initialize the properties of the newly instantiated bean

● Can be another managed bean

Bean injection,The XML way...

Bean injection, the @annotation way

Facelets composition and templating

Facelets and composition

● To be done

JSF conclusions

● JSF is a web-framework with server-side UI component.

● It allows validation, rendering (jsp or ajax), event-management

● It allows RAD and RIA developpement (with ICEFaces et al)

● It competes with other Web-framework such as Wicket, Vaadin, GWT etc...