66
Introduction To Java Server Faces 2.0 Jay Balunas JBoss, a Division of Red Hat http://in.relation.to/Bloggers/Jay [email protected] 1

71636

Embed Size (px)

Citation preview

Page 1: 71636

Introduction To Java Server Faces 2.0

Jay BalunasJBoss, a Division of Red Hat

http://in.relation.to/Bloggers/[email protected]

1

Page 2: 71636

Who Is This Guy?

Core Developer atJBoss, Division of Red Hat

RichFaces project leadSeam developer

JBoss Tattletale developer

2

Page 3: 71636

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.

3

Page 4: 71636

What Are We Doing Tonight?

Java Sever Faces(JSF), a brief historyJSF 2.0 key features

Annotations instead of XMLFacelets becomes a standardBuilt in resource handlingIntegrated AJAX supportetc...

The future for JSFWrap up

4

Page 5: 71636

JSF, A Brief History

Introduced in 2004

Developed using Java Community Process

JSF 1.0 (JSR 127) & JSF 1.2 (JSR-252)

Included in EE5 platform

Excellent ecosystem

JSF RI (Mojarra), Myfaces

RichFaces, IceFaces, Trinidad, etc...

5

Page 6: 71636

JSF 1.2 ProsStandards basedWell defined request lifecycleDesigned with tooling in mindComponent based UI frameworkCustom UI widgetsMany extension points

component librariesPhase listenersview handlersrenderersetc...

6

Page 7: 71636

JSF 1.2 ConsRelies on JSP for view layer

Facelets solved many of the issuesVery verbose XMLComplicated backing bean configurationNo built in AJAX supportSmall # of standard componentCustom components complex to createNot easy to bookmark URLs

7

Page 8: 71636

JSF 2.0 MissionThe 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. In fact, many of these great ideas are built on top of the Java Server Faces Specification but, are not, themselves, standards. It is time to harvest these ideas and bring them to a wider audience in manner consistent with the rest of the Java Platform.

- JSR-314

8

Page 9: 71636

JSF 2.0 FeaturesAnnotations instead of XMLFacelets integrationComponent creation & templatingView parametersBuilt in resource handlingProject stages

Integrated AJAX supportException handlingNew event systemsBean validationNavigation updatesBehaviors frameworkEL access to component valuesetc...

9

Page 10: 71636

Annotations Not XMLXML is disconnected from the codeAre you an XML developer?

Quickly grows out of controlRefactoring is a nightmareHard to read

10

Page 11: 71636

JSF 1.2 Managed Bean

<managed-bean> <description>JSF 1.2 backing bean config</description> <managed-bean-name>fooBean</managed-bean-name> <managed-bean-class>com.foo.fooBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>

11

Page 12: 71636

JSF 2.0 Managed Beanpackage com.foo;import javax.faces.model.ManagedBean;import javax.faces.model.SessionScoped;

@ManagedBean(name = "fooBean")@SessionScopedpublic class FooBean {

12

Page 13: 71636

JSF 1.2 Managed Properties

<managed-bean> <managed-bean-name>fooBean</managed-bean-name> <managed-bean-class>com.foo.fooBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>bar</property-name> <property-class>com.foo.BarBean</property-class> <value>#{barBean}</value> </managed-property> </managed-bean>

13

Page 14: 71636

JSF 2.0 Managed Properties

@ManagedBean(name = "fooBean")@SessionScopedpublic class FooBean {

@ManagedProperty(value=”#{barBean}”) private BarBean barBean;

public BarBean getBarBean() public void setBarBean(BarBean barBean) The gets/sets are

required!

Assumes #{barBean}

is defined

14

Page 15: 71636

How Are Annotations Processed

Classpath scanning on startupWhat classes are scanned:

WEB-INF/classesWEB-INF/lib/*.jar

Only jars with /META-INF/faces-config.xmlCan be empty

Configuration files override annotationsXML still supported

15

Page 16: 71636

Additional AnnotationsFacesConverter, FacesValidator, FacesRendererLifecycle callbacks

PostConstructPreDestroy

ScopesNoneScopedRequestScopedViewScopedSessionScopedApplicationScoped

16

Page 17: 71636

Still Not GreatNot type safe

String based referencesWon’t know till you are clicking

Scoping still limitedOnly inject larger scoped beansLeads to some interesting bean configurations

No conversation scopeLimited to view/session scopes for state

17

Page 18: 71636

JSR 299 Java Context and Dependancy Injection

Inspired by Seam, Google Guice, etc...Better dependency injectionConversation scope supportRuns in any Java env. (EE, Servlets, SE)Unified injection & component model with EE6

Directly reference EJBs, Entities, POJOsBacking bean layer becomes optional

18

Page 19: 71636

Better DIInjection types

FieldConstructorInitializer method

TypesafeNo string based lookupsBeans defined and referenced with binding types

No scope/context restrictions

19

Page 20: 71636

JCDI Example@Named@SessionScopedpublic class FooBean {

@Current private BarBean barBean;

public BarBean getBarBean() public void setBarBean(BarBean barBean)

Can be of any Scope. FooBean does

not need to care

@Named only needed for EL access

20

Page 21: 71636

Constructor Injection@Named@SessionScopedpublic class FooBean {

private BarBean barBean;

@Initializer public FooBean(BarBean barBean){ this.barBean=barBean; }

Can be used on any method, not just

constructor

21

Page 22: 71636

Binding Types@Foo @RequestScopedpublic class FoobarBean extends BarBean{

@Far @RequestScopedpublic class FarbarBean extends BarBean{

@Foo and @Far are binding types you create.

@Named @SessionScopedpublic class FooBean {

@Far private BarBean barBean;

@Named @SessionScopedpublic class FooBean { private BarBean barBean; @Initializer public FooBean(@Far BarBean barBean)

22

Page 23: 71636

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

Page 24: 71636

Conversation Example@Named @ConversationScopedpublic 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(){}

24

Page 25: 71636

Facelets in JSF 2.0JSP is deprecated

Several features not supportedResource handlingView parametersSome of the AJAX support

View Definition Language (VDL)Templating & composite componentsBackwards compatible *

25

Page 26: 71636

View Description Language (VDL)

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <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>

26

Page 27: 71636

Templating<ui:composition template="/WEB-INF/template.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>

template.xhtml

What template to use

“content” inserted

27

Page 28: 71636

Composition ComponentsDRY in the viewConstruct complex components

Built from existing componentsReuse where ever needed

Define attribute interfacesNo Java coding required

28

Page 29: 71636

Composition Components

xmlns:composite="http://java.sun.com/jsf/composite"...<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.attrs.value2}" style="background-color: red"/></composite:implementation>

Create a file <web-root>/resources/simpleout/out.xml

29

Page 30: 71636

Using The Componentxmlns:ez="http://java.sun.com/jsf/composite/simpleout"

<ui:composition template="/WEB-INF/template.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.xhtml file

30

Page 31: 71636

Breaking Down the Path

<web-root>/resources/simpleout/out.xhtml

http://java.sun.com/jsf/composite/simpleout

<ez:out value="..." />Namespace is a trigger for JSF to wire these

together

31

Page 32: 71636

View ParametersPropagate state across pages using GET requestsBookmarkable URLsFacelets only not JSPLifecycle execution on non-faces request

Conversion, validation, etc New Tags

<f:metadata><f:viewParam><h:link><h:button>

32

Page 33: 71636

Tag Details<f:metadata>

Must be right after <f:view><f:viewParam>

Binds GET request values to modelExtends UIInputSupports converters, validators, etc...

<h:link> & <h:button>Render link/button that acts as URLAppends any viewParam, or nested param

33

Page 34: 71636

Store Example

<f:view><f:metadata>

<f:viewParam name=”dept” value=”#{store.department}”/><f:viewParam name=”category” value=”#{store.category}”/><f:viewParam name=”sort” value=”#{store.sortOrder}”/>

</f:metadata> ...<h:outputText value="Department : #{store.department}“/><h:outputText value="Category : #{store.category}“/><h:outputText value="Sort Order : #{store.sortOrder}“/>...

</f:view

http://localhost:8080/myStore/cloths.xhtml?dept=mens

34

Page 35: 71636

Adding Category Links<f:metadata>

<f:viewParam name=”dept” value=”#{store.department}”/><f:viewParam name=”category” value=”#{store.category}”/><f:viewParam name=”sort” value=”#{store.sortOrder}”/>

</f:metadata> ...<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>...

35

Page 36: 71636

Nav to New Page

<f:metadata><f:viewParam name=”dept” value=”#{store.department}”/><f:viewParam name=”category” value=”#{store.category}”/><f:viewParam name=”sort” value=”#{store.sortOrder}”/>

</f:metadata> ...<h:link value=”Electronics” outcome=”buymore” includeViewParams=”false” > <f:param name=”sort” value=” #{store.sortOrder}” /></h:link>

36

Page 37: 71636

Templates and Metadata<ui:composition template="template.xhtml">! <ui:define name="metadata">! ! <f:metadata>! ! ! <f:viewParam name="id" .../>! ! </f:metadata> </ui:define> <html xmlns="http://www.w3.org/1999/xhtml"

! ! ! xmlns:ui="http://java.sun.com/jsf/facelets"! ! ! xmlns:f="http://java.sun.com/jsf/core"! ! ! xml:lang="en" lang="en"><body><f:view>! ! <ui:insert name="metadata"/>! ! <div id="container">! ! ! ! <ui:insert name="content"/>! ! </div></f:view>

template.xhtml

Metadata gets injected right after

<f:view>

37

Page 38: 71636

Resource Handler

Declarative resource loading JavaScript, images, CSS, etc..

Resource can be defined by:name, version, locale, and library

Can be packaged in :Web root under /resourcesIn libraries under /META-INF/resources

Only available for Facelets (VDL) pages

38

Page 39: 71636

Resource Identifier

[localePrefix/][libraryName/][libraryVersion/]resourceName[/resourceVersion]

de/tanks/1.0/tiger.gif/1.2.gifWould look for: de/tanks.jar/1.0.jar/META-INF/resources/tiger.gif/1.2.gif

tiger.gif

Would look for: <app-root>/resources/tiger.gif

39

Page 40: 71636

Hiding The DetailsVersion and locale processing hiddenDefault behavior

Library - highest version foundResource - highest version foundLocale :

locale = ...viewHandler.calculateLocale(); if (locale has a loaded ResourceBundle) prefix= ResourceHandler.LOCALE_PREFIX);else prefix = null;

40

Page 41: 71636

Image Resources

<h:graphicImage name=”sherman.gif”/>

<h:graphicImage name=”tiger.gif” library=”tanks”/>

<h:graphicImage value=”#{resource[‘tanks:tiger.gif’]}”/>

Loads from /resources

Loads from tanks.jar

41

Page 42: 71636

!!! <h:head> !!!! <title>Resource Example</title>!!! </h:head>!!! <h:body> !!!! <h:form id="form"> !!!! <h:outputScript name="script.js"

target="head"/>!!!! <h:outputText value="Hello"/>!!!! <h:outputStylesheet name="style.css"/>!!!! </h:form>!!! </h:body></html>

Stylesheets always render to the head

Will render inside the <h:head>

Script and CSS Resources

42

Page 43: 71636

Components Hiding Resources

Most component libraries will hide resourcesPage authors don’t need to worry about this

@ResourceDependency(name="tank.css",library="ww2")public class Tank extends UIComponentBase {}

@ResourceDependencies({!!!@ResourceDependency(name="tank.css",library="ww2"),!!!@ResourceDependency(name="menu.js",library="ww2",target="head")})public class TankMenu extends UIComponentBase {}

43

Page 44: 71636

AJAX Integration

JavaScript API&

The <f:ajax> Tag

44

Page 45: 71636

JavaScript APIfor AJax

JSF now has JavaScript API for AJAXRegistered with Open AJAX AllianceAll requests queued on client side Supports

RequestsCallbacksError handling

45

Page 46: 71636

Input Text Example

<h:outputScript name="jsf.js" library="javax.faces" target="head"/><h:inputText!id="myinput"!value="#{userBean.name}" onchange="javax.faces.Ajax.ajaxRequest(this, event, {render: 'outtext'}); return false;"/><br/>!<h:outputText!id="outtext"!value="#{userBean.name}"!/>

Resource loading

Call this to trigger a request

46

Page 47: 71636

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

47

Page 48: 71636

JSF 1.2 Adding AJAX Behavior

!xmlns:a4j="http://richfaces.org/a4j" .......!<h:inputText!id="myinput"!value="#{userBean.name}">

<a4j:support!event="onclick"!reRender="outtext"!/> </h:inputText>!<h:outputText!id="outtext"!value="#{userBean.name}"!/> ......

48

Page 49: 71636

JSF 2.0 Adding Ajax Behavior

xmlns:f="http://java.sun.com/jsf/core" .......!<h:inputText!id="myinput"!value="#{userBean.name}"/>

!!!!<f:ajax!event="keyup"!render="form1:outtext"!/>!</h:inputText>!<h:outputText!id="outtext"!value="#{userBean.name}"!/>......

49

Page 50: 71636

Nested <f:ajax>

<f:ajax> <h:panelGrid> <h:inputText id=”text1”/> <h:commandButton id=”button1”/> </h:panelGrid> </f:ajax>

Nest to apply default ajax behaviors

valueChange

action

panelGrid has no default event and is ignored

50

Page 51: 71636

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> </f:ajax>

inputText and PanelGrid will have an

“mouseover” event

CommandButton gets both “click” and “mouseover”

51

Page 52: 71636

Ajax Actions“execute” - list of ids to process in the request“render” - list of ids to rerender in the responseKey words

@all@none - default for render@this - default for execute@form

52

Page 53: 71636

@Form Example

xmlns:f="http://java.sun.com/jsf/core" ....... <h:inputText!id="creditNum"!value="#{account.cardNum}"/>!<h:inputText!id="exprDate"!value="#{account.cardExpr}"/> <h:outputText!id="accepted"!value="#{accout.accepted}"!<h:commandButton!id="verify"!value="verify"!...>

<f:ajax!execute="@form"!render="form1:accepted"!/> </h:commandButton>......

53

Page 54: 71636

Bean Validation

JSR 303 Bean ValidationAnnotation based constraintsValidate from JSF to DBSupports localization of messagesControl at view

54

Page 55: 71636

303 Bean Validation Example

@NotNullString username;

@Length(max = 9)@NotNullNumber cellPhone;

@Pattern(regexp="[0-9]*")String number;

In any POJO, but usually an entity

55

Page 56: 71636

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

Page 57: 71636

New Event System

New publish/subscribe event systemMuch more fine grained eventsSystem scoped events

Extend “SystemEvent.”System or application wide events

Component scoped eventsExtend “ComponentSystemEvent”Trigged from components

57

Page 58: 71636

Built In EventsAll in “javax.faces.event“ packageSystem events

ExceptionQueuedEventPostConstructApplicationEventPreDestroyApplicationEvent

Component eventsAfterAddToParentEventPreRenderViewEventPreValidateEvent

Custom events can be created

58

Page 59: 71636

Application Subscribe

public abstract void subscribeToEvent( Class<? extends SystemEvent> systemEventClass, SystemEventListener listener) public abstract void subscribeToEvent( Class<? extends SystemEvent> systemEventClass, Class sourceClass, SystemEventListener listener);

with matching

public abstract void unsubscribeToEvent(....)

59

Page 60: 71636

UIComponent Subscribe Pragmaticpublic void subscribeToEvent(Class<? extends SystemEvent> eventClass,

ComponentSystemEventListener componentListener); public void unsubscribeFromEvent(Class<? extends SystemEvent> eventClass, ComponentSystemEventListener componentListener);

Declarative<h:inputText value="#{myBean.text}"> <f:event type="beforeRender" listener="#{myBean.beforeTextRender}" /> </h:inputText>

Annotations @ListenerFor(systemEventClass=AfterAddToParentEvent.class) public class MyComponent extends UIOutput {}

60

Page 61: 71636

Custom Events

<h:inputText value="#{myBean.text}"> <f:event type="myEvent" listener="#{myBean.beforeTextRender}" /> </h:inputText>

@NamedEvent(shortName="myEvent”)

public class MyEvent extends ComponentSystemEvent{ ...}

61

Page 62: 71636

Triggering EventsThe framework will trigger it’s own events

All the component and application eventsor ....

javax.faces.application.Applicationpublic abstract void publishEvent(

Class<? extends SystemEvent> systemEventClass, SystemEventListenerHolder source);

public void publishEvent( Class<? extends SystemEvent> systemEventClass, Class<?> sourceBaseType, Object source)

62

Page 63: 71636

Exception Handling

It just works!No filter needed (as in JSF 1.2)No more swallowed exceptionNew ExceptionHandler

Subclass for custom behaviorSubscribe to and publish exception events using event systemRedirect to JSF, or other page

63

Page 64: 71636

JSF FuturesWeb Beans

Conversation scopeDI improvements

Component libraries will expand & may interoperateRichFaces, IceFaces, Trinidad, etc....

JSF 2.1Cross-field validationView actionsFormal collection interface supportDefault application time zoneXSD for Faceletshttp://seamframework.org/Documentation/JSF21

64

Page 65: 71636

RichFaces 4.0Full JSF 2.0 integrationMigration of current componentsSkinning, and theme supportDynamic resource handlingLibrary interoperability (ICEfaces, etc...)Optimizations

PerformanceBandwidth

Excellent tools support (JBoss Tools)Fall release

Alphas, betas, and CRs

65