Introduction To Java Server Faces 2.

Jay Balunas JBoss, a Division of Red Hat http:/ /


Who Is This Guy?
Core Developer at JBoss, Division of Red Hat RichFaces project lead Seam developer JBoss Tattletale developer


Questions, Questions, Questions
Questions are welcome at anytime!*

* As long as: “I’m not sure, but can find out” “Let’s talk at the break” “I can point you in the right direction but...” are acceptable answers.


. a brief history JSF 2.0 key features Annotations instead of XML Facelets becomes a standard Built in resource handling Integrated AJAX support etc..What Are We Doing Tonight? Java Sever Faces(JSF). The future for JSF Wrap up 4 .

Trinidad.JSF.2 (JSR-252) Included in EE5 platform Excellent ecosystem JSF RI (Mojarra). 5 .0 (JSR 127) & JSF 1. etc.. Myfaces RichFaces. IceFaces. A Brief History Introduced in 2004 Developed using Java Community Process JSF 1..

JSF 1. 6 ..2 Pros Standards based Well defined request lifecycle Designed with tooling in mind Component based UI framework Custom UI widgets Many extension points component libraries Phase listeners view handlers renderers etc..

2 Cons Relies on JSP for view layer Facelets solved many of the issues Very verbose XML Complicated backing bean configuration No built in AJAX support Small # of standard component Custom components complex to create Not easy to bookmark URLs 7 .JSF 1.

In fact.JSR-314 8 .0 Mission The Java community finds itself in a similar situation to that in which the first version of the Java Server Faces specification was initiated: Many great ideas but no standard specification that delivers them to developers and the marketplace. It is time to harvest these ideas and bring them to a wider audience in manner consistent with the rest of the Java Platform. . standards.JSF 2. many of these great ideas are built on top of the Java Server Faces Specification but. are not. themselves.

JSF 2. 9 ..0 Features Annotations instead of XML Facelets integration Component creation & templating View parameters Built in resource handling Project stages Integrated AJAX support Exception handling New event systems Bean validation Navigation updates Behaviors framework EL access to component values etc..

Annotations Not XML XML is disconnected from the code Are you an XML developer? Quickly grows out of control Refactoring is a nightmare Hard to read 10 .

JSF 1.fooBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> 11 .foo.2 backing bean config</description> <managed-bean-name>fooBean</managed-bean-name> <managed-bean-class>com.2 Managed Bean <managed-bean> <description>JSF 1.

package import javax.0 Managed Bean 12 .faces. import javax.faces. @ManagedBean(name = "fooBean") @SessionScoped public class FooBean { JSF 2.model.SessionScoped.

foo.<managed-bean> <managed-bean-name>fooBean</managed-bean-name> <managed-bean-class>com.fooBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>bar</property-name> <property-class></property-class> <value>#{barBean}</value> </managed-property> </managed-bean> JSF 1.2 Managed Properties 13 .

public BarBean getBarBean() public void setBarBean(BarBean barBean) The gets/sets are required! 14 .0 Managed Properties Assumes #{barBean} is defined @ManagedProperty(value=”#{barBean}”) private BarBean barBean.@ManagedBean(name = "fooBean") @SessionScoped public class FooBean { JSF 2.

jar Only jars with /META-INF/faces-config.How Are Annotations Processed Classpath scanning on startup What classes are scanned: WEB-INF/classes WEB-INF/lib/*.xml Can be empty Configuration files override annotations XML still supported 15 .

FacesValidator. FacesRenderer Lifecycle callbacks PostConstruct PreDestroy Scopes NoneScoped RequestScoped ViewScoped SessionScoped ApplicationScoped 16 .Additional Annotations FacesConverter.

Still Not Great Not type safe String based references Won’t know till you are clicking Scoping still limited Only inject larger scoped beans Leads to some interesting bean configurations No conversation scope Limited to view/session scopes for state 17 .

etc. SE) Unified injection & component model with EE6 Directly reference EJBs...JSR 299 Java Context and Dependancy Injection Inspired by Seam. Entities. POJOs Backing bean layer becomes optional 18 . (EE. Servlets. Better dependency injection Conversation scope support Runs in any Java env. Google Guice.

Better DI Injection types Field Constructor Initializer method Typesafe No string based lookups Beans defined and referenced with binding types No scope/context restrictions 19 .

@Named only needed for EL access Can be of any Scope.JCDI Example @Named @SessionScoped public class FooBean { @Current private BarBean barBean. FooBean does not need to care public BarBean getBarBean() public void setBarBean(BarBean barBean) 20 .

barBean=barBean.Constructor Injection @Named @SessionScoped public class FooBean { private BarBean barBean. @Initializer public FooBean(BarBean barBean){ this. not just constructor 21 . } Can be used on any method.

Binding Types @Foo @RequestScoped public class FoobarBean extends BarBean{ @Far @RequestScoped public class FarbarBean extends BarBean{ @Named @SessionScoped public class FooBean { @Named @SessionScoped public class FooBean { private BarBean barBean. @Far @Initializer private BarBean barBean. public FooBean(@Far BarBean barBean) @Foo and @Far are binding types you create. 22 .

Conversation Scope Spans multiple requests Smaller than session Allows multi-window/ multi-tab operation Boundaries defined by the developer not the framework Helps avoid orphaned data in session Can correspond to an optimistic transaction 23 .

Conversation Example
@Named @ConversationScoped public class Booking { @Current Conversation conversation; public void selectHotel(){ converstation.begin(); .... } public void confirmHotel(){{ ... converstation.end(); .... }

Conversation is JCDI Class

Would also be in public void cancelHotel(){}


Facelets in JSF 2.0
JSP is deprecated Several features not supported Resource handling View parameters Some of the AJAX support View Definition Language (VDL) Templating & composite components Backwards compatible *


<html xmlns="http:/ /" xmlns:h="http:/ /" xmlns:f="http:/ /"> <h:head> <title>VDL Page</title> </h:head> <h:body> <h:form> <h:outputText value="I won’t say " /> <h:outputText value="hello world" /> </h:form> </h:body> </html>

View Description Language (VDL)


xhtml"> <ui:param name="title" value="VDL Template Page"/> <ui:define name="content"> <h2>${title}</h2> <h:form> <h:outputText value="I won’t say " /> <h:outputText value="hello world" /> </h:form> </ui:define> </ui:composition> <h:head> <title>${title}</title> </h:head> <body> <div id="container"> <ui:insert name="content"/> </div> </body> Templating What template to use template.xhtml “content” inserted 27 .<ui:composition template="/WEB-INF/template.

Composition Components DRY in the view Construct complex components Built from existing components Reuse where ever needed Define attribute interfaces No Java coding required 28 .

com/jsf/composite" .sun.Composition Components Create a file <web-root>/resources/simpleout/out. <composite:interface> <composite:attribute name="value1" required="true"/> <composite:attribute name="value2" required="true"/> </composite:interface> <composite:implementation> <h:outputText value="#{compositeComponent..attrs.value1}" style="background-color: green"/> <h:outputText value="#{compositeComponent.xml xmlns:composite="http:/ /java.attrs..value2}" style="background-color: red"/> </composite:implementation> 29 .

xhtml"> <ui:param name="title" value="VDL Template Page"/> <ui:define name="content"> <h2>${title}</h2> <h:form> <ez:out value1="I won’t say “ value2=”hello world" /> </h:form> </ui:define> </ui:composition> References the /simpleout directory “ez” is from namespace “out” is from the out.Using The Component xmlns:ez="http:/ /" <ui:composition template="/WEB-INF/template.xhtml file 30 .sun.

.xhtml http:/ /java.sun.Breaking Down the Path <web-root>/resources/simpleout/ Namespace is a trigger for JSF to wire these together <ez:out value="." /> 31 .

validation. etc New Tags <f:metadata> <f:viewParam> <h:link> <h:button> 32 .View Parameters Propagate state across pages using GET requests Bookmarkable URLs Facelets only not JSP Lifecycle execution on non-faces request Conversion.

. <h:link> & <h:button> Render link/button that acts as URL Appends any viewParam. or nested param 33 . validators. etc..Tag Details <f:metadata> Must be right after <f:view> <f:viewParam> Binds GET request values to model Extends UIInput Supports converters.

department}“/> <h:outputText value="Category : #{store.category}”/> <f:viewParam name=”sort” value=”#{store.sortOrder}“/> . </f:view 34 . <h:outputText value="Department : #{store..category}“/> <h:outputText value="Sort Order : #{store..sortOrder}”/> </f:metadata> .department}”/> <f:viewParam name=”category” value=”#{store..xhtml?dept=mens <f:view> <f:metadata> <f:viewParam name=”dept” value=”#{store.Store Example http:/ /localhost:8080/myStore/cloths..

<h:link value=”Pants” includeViewParams=”true” > <f:param name=”category” value=”pants” /> </h:link> <br/> <h:link value=”Shirts” includeViewParams=”true” > <f:param name=”category” value=”shirts” /> </h:link> .sortOrder}”/> </f:metadata> .<f:metadata> <f:viewParam name=”dept” value=”#{store.category}”/> <f:viewParam name=”sort” value=”#{store.. 35 Adding Category Links ...department}”/> <f:viewParam name=”category” value=”#{store..

sortOrder}” /> </h:link> 36 .department}”/> <f:viewParam name=”category” value=”#{store.category}”/> <f:viewParam name=”sort” value=”#{store.sortOrder}”/> </f:metadata> .Nav to New Page <f:metadata> <f:viewParam name=”dept” value=”#{store.. <h:link value=”Electronics” outcome=”buymore” includeViewParams=”false” > <f:param name=”sort” value=” #{store..

/> ! ! </f:metadata> <html xmlns="http:/ /www..sun.xhtml"> ! <ui:define name="metadata"> template.Templates and Metadata <ui:composition template="" ! ! ! xml:lang="en" lang="en"> <body> <f:view> ! ! <ui:insert name="metadata"/> ! ! <div id="container"> ! ! ! ! <ui:insert name="content"/> ! ! </div> </f:view> 37 .xhtml ! ! <f:metadata> ! ! ! <f:viewParam name="id" .com/jsf/facelets" ! ! ! xmlns:f="http:/ /" </ui:define> Metadata gets injected right after <f:view> ! ! ! xmlns:ui="http:/ /java..

locale. version. and library Can be packaged in : Web root under /resources In libraries under /META-INF/resources Only available for Facelets (VDL) pages 38 ..Resource Handler Declarative resource loading JavaScript. images. etc. Resource can be defined by: name. CSS.

gif 39 .gif Would look for: <app-root>/resources/tiger.jar/1.gif/1.Resource Identifier [localePrefix/][libraryName/][libraryVersion/]resourceName[/resourceVersion] tiger.0/tiger.gif/1.gif Would look for: de/tanks.0.gif de/tanks/1.jar/META-INF/resources/tiger.2.2.

LOCALE_PREFIX). 40 ..highest version found Locale : locale = . if (locale has a loaded ResourceBundle) prefix= ResourceHandler..calculateLocale().highest version found Resource . else prefix = null.Hiding The Details Version and locale processing hidden Default behavior Library .viewHandler.

gif”/> <h:graphicImage name=”tiger.gif” library=”tanks”/> <h:graphicImage value=”#{resource[‘tanks:tiger.Image Resources Loads from /resources <h:graphicImage name=”sherman.gif’]}”/> Loads from tanks.jar 41 .

js" target="head"/> !!!! <h:outputText value="Hello"/> !!!! <h:outputStylesheet name="style.!!! <h:head> !!!! <title>Resource Example</title> Will render inside !!! </h:head> !!! <h:body> <h:head> !!!! <h:form id="form"> !!!! <h:outputScript name="script.css"/> !!!! </h:form> !!! </h:body> Stylesheets always </html> Script and CSS Resources the render to the head 42 .

library="ww2". !!!@ResourceDependency(name="menu.library="ww2") public class Tank extends UIComponentBase {} @ResourceDependencies({ !!!@ResourceDependency(name="tank.css".js".library="ww2").Most component libraries will hide resources Page authors don’t need to worry about this @ResourceDependency(name="tank.css".target="head") }) public class TankMenu extends UIComponentBase {} Components Hiding Resources 43 .

AJAX Integration JavaScript API & The <f:ajax> Tag 44 .

JavaScript API for AJax JSF now has JavaScript API for AJAX Registered with Open AJAX Alliance All requests queued on client side Supports Requests Callbacks Error handling 45 .

name}"!/> Call this to trigger a request 46 .Ajax. return false. {render: 'outtext'}). event.Input Text Example Resource loading <h:outputScript name="jsf.faces.faces" target="head"/> <h:inputText!id="myinput"!value="#{userBean.js" library="}" onchange="javax."/> <br/>! <h:outputText!id="outtext"!value="#{userBean.ajaxRequest(this.

return}"/> <h:outputText!id="outtext"!value="#{userBean.request(this." /> 47 .ajax.Button Example <h:outputScript name="jsf.render:'outtext'}). {execute:'myinput'.js" library="javax.faces" target="head"/> <h:inputText!id="myinput"!value="#{userBean.}"!/> <br/> <h:commandbutton id="submit" value="submit" onclick="jsf.

org/a4j"}"> <a4j:support!event="onclick"!reRender="outtext"!/> </h:inputText> !<h:outputText!id="outtext"!value="#{userBean..2 Adding AJAX Behavior !xmlns:a4j="http:/ /richfaces.JSF}"!/> .. !<h:inputText!id="myinput"!value="#{userBean.... 48 .

49}"!/> .. !<h:inputText!id="myinput"!value="#{userBean.sun..JSF" ...0 Adding Ajax Behavior xmlns:f="http:/ /}"/> !!!!<f:ajax!event="keyup"!render="form1:outtext"!/> !</h:inputText> !<h:outputText!id="outtext"!value="#{userBean.

Nested <f:ajax> Nest to apply default ajax behaviors <f:ajax> <h:panelGrid> <h:inputText id=”text1”/> <h:commandButton id=”button1”/> </h:panelGrid> </f:ajax> valueChange action panelGrid has no default event and is ignored 50 .

Extending Nested Events <f:ajax event=”mouseover”> <h:panelGrid id=”grid1”> <h:inputText id=”text1”/> <h:commandButton id=”button1”> <f:ajax event=”click”/> </h:commandButton> </h:panelGrid> CommandButton </f:ajax> inputText and PanelGrid will have an “mouseover” event gets both “click” and “mouseover” 51 .

Ajax Actions “execute” .default for execute @form 52 .list of ids to process in the request “render” .list of ids to rerender in the response Key words @all @none .default for render @this .

53 ....accepted}" !<h:commandButton!id="verify"!value="verify"!.> <f:ajax!execute="@form"!render="form1:accepted"!/> </h:commandButton> .cardNum}"/> !<h:inputText!id="exprDate"!value="#{account....cardExpr}"/> <h:outputText!id="accepted"!value="#{accout.sun...... <h:inputText!id="creditNum"!value="#{account...@Form Example xmlns:f="http:/ /" .

Bean Validation JSR 303 Bean Validation Annotation based constraints Validate from JSF to DB Supports localization of messages Control at view 54 .

@Pattern(regexp="[0-9]*") String number. but usually an entity 55 . In any POJO.303 Bean Validation Example @NotNull String username. @Length(max = 9) @NotNull Number cellPhone.

Wiring To The View <h:inputText id="username" value="#{account.username}"/> <h:message for="username" styleClass="error" /> <br/> <h:inputText id="cellPhone" value="#{account.cellPhone}" > <f:validateBean disable=”true”/> </h:inputText> <h:message for="cellPhone" styleClass="error" /> 56 .

” System or application wide events Component scoped events Extend “ComponentSystemEvent” Trigged from components 57 .New Event System New publish/subscribe event system Much more fine grained events System scoped events Extend “SystemEvent.

Built In Events All in “javax.event“ package System events ExceptionQueuedEvent PostConstructApplicationEvent PreDestroyApplicationEvent Component events AfterAddToParentEvent PreRenderViewEvent PreValidateEvent Custom events can be created 58 .faces.

. Class sourceClass.. with matching public abstract void unsubscribeToEvent(. SystemEventListener listener).) 59 .. SystemEventListener listener) public abstract void subscribeToEvent( Class<? extends SystemEvent> systemEventClass.Application Subscribe public abstract void subscribeToEvent( Class<? extends SystemEvent> systemEventClass.

public void unsubscribeFromEvent(Class<? extends SystemEvent> eventClass. ComponentSystemEventListener componentListener).class) public class MyComponent extends UIOutput {} 60 .beforeTextRender}" /> </h:inputText> Annotations @ListenerFor(systemEventClass=AfterAddToParentEvent. Declarative <h:inputText value="#{myBean. ComponentSystemEventListener componentListener).UIComponent Subscribe Pragmatic public void subscribeToEvent(Class<? extends SystemEvent> eventClass.text}"> <f:event type="beforeRender" listener="#{myBean.

beforeTextRender}" /> </h:inputText> 61 ... } <h:inputText value="#{myBean.text}"> <f:event type="myEvent" listener="#{myBean.Custom Events @NamedEvent(shortName="myEvent”) public class MyEvent extends ComponentSystemEvent { .

Object source) 62 . Class<?> sourceBaseType...Triggering Events The framework will trigger it’s own events All the component and application events or .application.faces. javax. public void publishEvent( Class<? extends SystemEvent> systemEventClass.. SystemEventListenerHolder source).Application public abstract void publishEvent( Class<? extends SystemEvent> systemEventClass.

or other page 63 .Exception Handling It just works! No filter needed (as in JSF 1.2) No more swallowed exception New ExceptionHandler Subclass for custom behavior Subscribe to and publish exception events using event system Redirect to JSF.

Web Beans Conversation scope DI improvements Component libraries will expand & may interoperate RichFaces. IceFaces.. Trinidad.. 64 JSF Futures . JSF 2.1 Cross-field validation View actions Formal collection interface support Default application time zone XSD for Facelets http:/ /seamframework..

betas.. etc.) Optimizations Performance Bandwidth Excellent tools support (JBoss Tools) Fall release Alphas.0 integration Migration of current components Skinning. and CRs 65 .RichFaces 4. and theme support Dynamic resource handling Library interoperability (ICEfaces.0 Full JSF 2..

com/tech4j http:/ / RichFaces http:/ / http:/ /twitter.0 http:/ / JBoss http:/ / https:/ / Me: http:/ / 66 For More .to/Bloggers/Jay http:/ /twitter.

Sign up to vote on this title
UsefulNot useful