a peek at the future: going beyond javaserver faces 2.0 with richfaces 4

61
1

Upload: balunasj

Post on 22-May-2015

5.647 views

Category:

Technology


1 download

DESCRIPTION

Jay Balunas and Alexander Smirnov give an overview of JSF2, and preview of the future for JSF through the RichFaces project. This presentation was given at the 2010 JavaOne conference.

TRANSCRIPT

1

Jay Balunas RichFaces Project LeadJBoss, by Red Hat Inc.

JSF 2 And Beyond With RichFaces

JavaOne September, 2010

Alex SmirnovRichFaces ArchitectExadel Inc.

2

Who We Are:

• Jay Balunaso RichFaces Project Leado JBoss Core Developero http://in.relation.to/Bloggers/Jayo http://twitter.com/tech4jo [email protected]

Co-author of the RichFaces

Dzone RefCard

3

• Alexander Smirnovo RichFaces Project Architecto Ajax4Jsf Project Creatoro JSR-314 ( JSF 2.0 ) Expert Group Membero http://alexsmirnov.wordpress.com/o [email protected]

4

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

5

RichFaces Lighting Review• Ajax enabled component library

o 100+ components

• Two tag libraries o a4j: Page level ajax support & utility

componentso rich: Self contained rich components

• More than just components:o Skinning & themeso Dynamic resourceso Component development kit (CDK)

6

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

7

JSF 2.0 Built in Ajax

<h:inputText id="name_input" value="#{userBean.name}" /> <f:ajax event="keyup" execute=”@this” render="name_out" /></h:inputText>

<h:outputText id="name_out" value="#{userBean.name}" />

8

event="keyup"• DOM event to trigger Ajax request

• Default valueso ActionSource == "action"

Typically "onclick"

o Editable ValueHolders == "valueChange" Depends on type ex. "onblur" for inputText

Ajax Attributes

9

execute=”@this”• Components to process on server

o validation, model updates, listeners, etc...• Default == "@this"

render="name_out"• Components to update on request return• Default == "@none"

Ajax AttributesBoth accept component IDs, or the new keywords

10

Define a set of component identifiers

• No need to explicitly state component IDs

@none@this@form@all

JSF 2.0 Ajax Keywords

Smallest to largest scope

11

RichFaces makes it better with...

• a4j:region• a4j:outputPanel• a4j:queue• Partial updates for complex

components

12

Ajax Region & Output Panel

a4j:regionSet areas of the page to be processed on the Server!

a4j:outputPanelSet area's of the page to be rendered for any Ajax request!

No need to set "execute=x,y,z"

No need to set "render=x,y,z"

13

RichFaces Ajax Region<!-- Verify Address as part of a large form --><a4j:region> <h:inputText id="addr_01" ... /> <h:inputText id="city" ... /> <h:inputText id="state" ... /> <h:inputText id="zip" ... /> ... <h:commandLink action="#{registerBean.verifyAddress}" > <a4j:ajax/> <!--<f:ajax execute="addr_01 city state zip"/>--> </h:commandLink></a4j:region>

14

<!-- Will always be updated with any ajax request --><a4j:outputPanel ajaxRendered="true"> <h:outputText value="Score : #{gameBean.score}" /></a4j:outputPanel>

RichFaces Output Panel

No need to set "render" attribute

15

JSF 2.0 Request Queue

• Specification added Ajax requests• Requests need to be queued to

preserve state• Good, but limitedoVery few optionsoNo client side api

• Can lead to traffic jams...

16

RichFaces Request Queues• Adds a logical queue

o Usability & customizations

• Optionso requestDelay & request groupingo IgnoreDupResponses (in development)

• Client side APIo <queueObj>.getSize()o <queueObj>.isEmpty()o <queueObj>.set/getQueueOptions()o etc...

17

RichFaces Request Queues<h:form id="form"> <!-- Queue applied to whole form --> <a4j:queue requestDelay="500"/>

<h:inputText id="team1" value="#{gameBean.team1}" /> <a4j:ajax event="keyup" .../> </h:inputText> <h:inputText id="team2" value="#{gameBean.team2}" /> <a4j:ajax event="keyup" .../> </h:inputText> ...</h:form>

18

RichFaces Request Queues

<!-- Player lookups are more costly, send less often --><a4j:queue name="player_queue" requestDelay="1000"/>...<h:inputText id="player" value="#{gameBean.cur_player}" /> <a4j:ajax event="keyup" ...> <!-- Requests from here will use player_queue --> <a4j:attachQueue name="player_queue"/> </a4j:ajax></h:inputText>

19

Partial Updates for Complex Components

• RichFaces adds updates within complex componentso Table supports: @body, @header,

@footer, @row & @cello Collections of rows

Track updates, and render as group

o Others, like tree & tabPanel in the futureex. @node, @tab, etc...

20

Partial Updates for Iteration Components

<!-- Will render only the body of the table --><a4j:ajax render="table_id@body"/>

<!-- Will render only the current row --><rich:column> <a4j:commandButton render="@row"/></rich:column>

21

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

22

JSF 2.0 Loading Images <!-- Loads from <web-root>/resources --><h:graphicImage name="banner.jpeg />

<!-- Loads from /META-INF/resources/site --><h:graphicImage name="banner.jpeg" library="site"/>

<!-- EL notation --><h:graphicImage value="#{resource['site:banner.jpeg]}" />

23

JSF 2.0 Loading JavaScript & CSSTwo new resource components

<!-- Loads where you put it --><h:outputScript name=”project.js”/>

<!-- Loads in the <h:head> --><h:outputScript name=”project.js” target=”head”/>

<!-- CSS always loads in <h:head> --><h:outputStylesheet name=”frontpage.css” library=”site”/>

24

What if you need to manipulate resources...

25

Dynamic Resources in RichFaces

• Extends JSF 2.0 resource handler• Used by RichFaces internally

o Skinningo CSS with embedded ELo Java2D

• Make your own!!o Custom icons with state infoo Dynamic CSS & JS

26

@DynamicResourcepublic class GameAiResource implements UserResource{ private boolean easyGame;

public InputStream getInputStream() throws IOException { byte[] data; if (easyGame) { data = easyScript; } else{ data = hardScript; } return new ByteArrayInputStream(data);}....

27

Now Go Get It...Define mapping in resource property file:

#Maps dynamic resource end-point aiScript=foo.bar.GameAiResource

<!-- Retrieved like any other resource --><h:outputScript name="aiScript"/>

28

Sending in the Parameters...@ResourceParameterprotected boolean easyGame;

<!-- Always returns the easyScript resource --><h:outputScript name="easyScript"/>

#Create resource mapping easyScript= foo.bar.GameAiResource?easyGame=true

29

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

30

JSF 2.0 Component Development

JSF 2.0 simplifies component development:• New annotations

o @FacesComponent, @FacesRenderero Helper methods, StateHelper

• Still necessary to :o Extend UIComponentBase classo Create Renderer

Implement the decode/encode*() methodso Create tag handlers and tag lib fileso Component functionality classeso Maintain it all...

31

JSF 2 Component DevelopmentResponseWriter writer = context.getResponseWriter();assert(writer != null);String formClientId = RenderKitUtils.getFormClientId(command, context);if (formClientId == null) {return;}

//make link act as if it's a button using javascript writer.startElement("a", command);writeIdAttributeIfNecessary(context, writer, command);writer.writeAttribute("href", "#", "href");RenderKitUtils.renderPassThruAttributes(context,writer,command, ATTRIBUTES, getNonOnClickBehaviors(command));

RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, command);

String target = (String) command.getAttributes().get("target");if (target != null) { target = target.trim();} else { target = "";}

Collection<ClientBehaviorContext.Parameter> params = getBehaviorParameters(command);RenderKitUtils.renderOnclick(context, command, params, target, true);

writeCommonLinkAttributes(writer, command);

// render the current value as link text.writeValue(command, writer);

Just part of CommandLinkRenderer.java(it's 272 lines total )

32

JSF 2.0 Composite Components• Reusable, easy to create• Declarative XML language• Create custom components from existing ones

Limitations:• Available in Facelets VDL only.• Limited place for custom logic.• Limited ability to process JSF events• Does not help to create Behaviors, Converters, Validators,

and EL Functions.

For complex components, you still require Java.

33

JSF 2.0 composite<composite:interface> <composite:attribute name="value" required="false"/></composite:interface>

<composite:implementation>

<h:outputText value="#{cc.attrs.value}" style="background-color: yellow"/> </composite:implementation>

34

RichFaces Component Development Kit

• Does much of the leg work for you!• Coding by convention• In the best case you only need two things:

o Abstract component classo Renderer template in xml/xhtml

• Integrates into your buildo Maven-plugino Java Annotations Processor

• IDE support o Standard xml files & schemao Type safe

35

JSF 2.0 composite<composite:interface> <composite:attribute name="value" required="false"/></composite:interface>

<composite:implementation>

<h:outputText value="#{cc.attrs.value}" style="background-color: yellow"/> </composite:implementation>

36

RichFaces Renderer Template<composite:interface> <!-- <cdk:component-family> org.richfaces.Out </cdk:component-family/> --> <composite:attribute name="value" required="false"/></composite:interface>

<composite:implementation>

<div id="#{clientId}" style="background-color: yellow"> #{component.attributes.value} </div></composite:implementation>

37

RichFaces Component Development

• Abstract component classo Only implement component functionalityo CDK will extend it based on:

Annotations Naming Conventions Template Config options

• CDK will compile template for renderero Including concrete component class

Getters/setters, etc..o Tag handlers, tab lib, and faces-config files

38

RichFaces Component Development

Not limited to JSF components, but also helps to create:

• Converters• Validators• Faces Events/Event Listeners• Behaviors.• Behavior Renderers

• compile JavaScript into renderer.• EL Functions• Unit tests• Documentation

39

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

40

What is Bean Validation

• Bean Validation JSR-303 o Part of Java EE6

• Generic, tier independent constraints• Custom, and composition constraints

possible• Constraint groups, and object graph

validation too• Message localization• Define constraints once, apply everywhere*

* Not all the way to the browser

41

Bean Validation Samplepublic class User {

@NotEmpty @Size(max=100) private String loginname;

@NotEmpty @Pattern(regexp = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+") private String email;

@NotEmpty @ValidTeam private String team;}

42

JSF 2.0 Bean Validation Integration

Login:<h:inputText id="login" value="#{user.login}"/><h:message for="login"/><br/>Email:<h:inputText id="email" value="#{user.email}"/><h:message for="email"/><br/>Team:<h:inputText id="team" value="#{user.team}"> <f:validateBean disabled="true"/> </h:inputText><h:message for="team"/><br/>

43

RichFaces Validation

• Validate entire object• Takes it to the Client, there possible

o Ajax fallback options• Use the same constrains on both sides• JavaScript:

o Validation, Converters, Messages• Can be applied to:

o Inputs, Commands, Views• Develop you own validators

o Client/server JS mapping

44

RichFaces Object Validation

JSF validation protects your Model from invalid values:

• Get client input as String request parameter.• Convert String to target value class using converter. • Mark value as invalid if string doesn't match ( e.g. characters

in the number ).• Verify converted object using Validator.• Model updated only if there are no errors on previous steps.

45

RichFaces Object Validation

JSF validation protects your Model from invalid values, but:

• it's hard to validate multiply fields together.• JSR-303 graph validator can verify updated model only.

46

RichFaces Object Validation <rich:graphValidator value="#{passwordBean}"> <h:inputText value="#{passwordBean.password}" /> <h:inputText value="#{passwordBean.retypePassword}" /></rich:graphValidator> public class PasswordBean implements Cloneable { @Size(min=6) @GoodPassword private String password ; @Size(min=6) private String retypePassword ; @AssertTrue(message="Passwords do not match") public boolean match(){ return password.equals(retypePassword); }

47

RichFaces Object ValidationWhat does <rich:graphValidator > do ?

1. clone Bean object instance.2. If there is no per-field errors, update cloned object with

submitted values at the end of PROCESS_VALIDATORS phase.

3. Perform JSR-303 validation on cloned object. Record errors ( if any ) and discard cloned object.

4. Go back to JSF lifecycle there model updated only if all constraint violations passed.

48

RichFaces Object Validation

Limitations:

• Model class should properly implement Cloneable interface.• Cannot inquire into EL variable references ( "var" dataTable

variable ).

49

RichFaces Client Side Validation

RichFaces 4.0 ( under development ) performs constraint validation on the client side where possible:

• Implemented as JSF 2.0 Behavior• Transparent for application developers • Looks up JavaScript version of JSF Converter and Validator.• If client-side version found, performs validation on client with

the same constraints as server-side. • Update RichFaces message component directly on the

client.• Otherwise, call Java code using AJAX transport.

See https://community.jboss.org/wiki/ClientSideValidation

50

RichFaces Client Validation - InputsLogin:<h:inputText id="login" value="#{user.login}"> <rich:clientValidator event="keyup"/></h:inputText><rich:message for="login"/>

Email:<h:inputText id="email" value="#{user.email}"> <rich:clientValidator event="keyup"/></h:inputText><rich:message for="email"/>

51

RichFaces Client Validation - Forms<h:form id="register">

Login: <h:inputText id="login" value="#{user.login}"/> <rich:message for="login"/>

Email: <h:inputText id="email" value="#{user.email}"/> <rich:message for="email"/>

<!-- This will verify when form submitted --> <h:commandButton id="submit" value="Save"> <rich:clientValidator/> </h:commandButton > ......

52

Beyond JSF 2.0 with RichFaces

• An Introduction• Built in Ajax• Built in Resource Handling• Component Development• Client Side Bean Validation• Project Updates

53

RichFaces 3.3.X

• Stable and mature

• Community Versions:o Moved into maintenance mode

• Enterprise supported versions included with:o Enterprise Application Platform (EAP)o Enterprise Portal Platform (EPP)o Web Framework Kit (WFK)

54

RichFaces 4.0.X

• In Developmento Latest Release: 4.0.0.Milestone2

• Complete JSF 2 integration & more...o Custom Behaviorso Dynamic Resource Extensionso Simplified Component Development Kito Updated skinningo Completely refactoredo Design for long term stability and support

55

Rich Components!

56

RichFaces 4.0.X• Wrapping up milestone project phase:

o 4.0.0.Milestone3 in Early Octobero 4.0.0.Milestone4 in Novembero 4.0.0.Milestone5 in Decembero 4.0.0.CR/Final in January/February

• Each release includes:o New & migrated componentso Stabilization of core/cdko Migration& developer guides

57

How To Get Started• Project Page: http://richfaces.org

• 4.0 Downloadso http://bit.ly/RF_Milestones

• Maven Integrationo http://bit.ly/RF_Maven

• User Wiki/Forumso Great for "how to" questions, and informationo http://bit.ly/RF_User_Space

• RichFaces Bug Trackero http://bit.ly/RF_Jira

58

More Way To Connect• Project Twitter Account

o http://twitter.com/richfaces

• Project Calendaro http://bit.ly/RF_Calendar

• IRC o #richfaces @ irc.freenode.net

• Team Meetings (open to all)o http://bit.ly/RF_Team_Mtgs

• Developer Blogso [Jay] http://in.relation.to/Bloggers/Jayo [Alex] http://alexsmirnov.wordpress.com/o [Ilya] http://www.jroller.com/a4j/

59

How To Get Involved• Developer Wiki/Forum

o Bring up your ideas, or discuss patches!o http://bit.ly/RF_Dev_Space

• Anonymous SVNo http://bit.ly/RF_SVN

• Sandbox SVNo http://bit.ly/RF_SVN_Sandbox

• Directory Structure Explainedo http://bit.ly/RF_Build_Structure

• Build Optionso http://bit.ly/RF_Build_Options

• Hudson CI Servero http://bit.ly/RF_Hudson_CI

60

Wrap up and Q&A

61