PDF What's new with JSF 2.0


Published on

This PDF is a presentation with notes which will serve well to bring a technologist up to speed with the latest offerings of JSF 2.0

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

PDF What's new with JSF 2.0

  1. 1. 1
  2. 2. JSF, while a vast improvement over Struts, is nevertheless a maturing framework. So,while JSF 1.x had many advantages over Struts and other similar frameworks, it alsoneeded additional enhancements.For example, JSF was still heavily tied to JSP, which led to a misalignment of life cycleswhich caused odd rendering issues periodically, and also led to inefficiency in generalprocessing. And yet it was good enough when it came out so that not manycomplained about these things…because they knew better days were coming.So JSF developers produced applications with JSF 1.x, and dealt with and workedaround these various inefficiencies and nuisances. 3
  3. 3. Java, Java EE, and JSF professionals worldwide contributed to the JSF specificationand in building the reference implementation. This group and the expectant world ofJSF developers were super-charged by the improvements and enhancementspromised by JSF 2.0.The expectation was that not only would JSF 2.0 atone for past work-arounds andinefficiencies, but that it would also be incorporating best of breed technologicalpractices from a variety of popular frameworks, and providing solutions to problemsthat had not even occurred yet, thereby creating a better development environmentin which JSF developers could create their future applications. 4
  4. 4. The deficiencies of JSF 1.x were many. Ajax functionality and support was present,but through a thousand different means. Resource files were available but againthrough an awkward method of hijacking requests. Navigation had to be explicitlydefined, making it very difficult for beginners to do very simple navigations. Eventswere present but they were not very fine grained or specific, so the events thatexisted became a means to enact all kinds of logic, which made it difficult to find orsort through logic and business rules that existed in an application. Templating wasdeveloping through facelets, but facelets was not well integrated with JSF.The list of deficiencies went on and on in like manner. Clearly there was room forimprovement. 5
  5. 5. The effort put forth by the Java/Java EE communities has indeed borne fruit. Many ofthe deficiencies which tripped up and plagued JSF component developers, JSF webapplication developers, and JSF application users have been solved. What is resultingis the dawning of an era of higher-performing applications, higher standards, andincreased positive results and outcomes for JSF application end-users.Broad-sweeping changes together with a myriad tiny improvements havetransformed JSF back to its former position of leadership in the race for webdevelopment supremacy. 6
  6. 6. At this time there are many JSF component development organizations which havetaken initial steps toward creating new components which are compatible with JSF2.0, so that JSF developers can embark on their journey to produce faster, robuster,easier-to-use web application using the latest features of JSF 2.0 – not the least ofwhich is Oracle, which has mapped out a plan to guide their development effortswhich incorporates more and more features provided by JSF 2.0.Other organizations are developing similar game plans. The only thing is: we must alldo our part now, as JSF developers. We must and are adopting this new technology,and incorporating it into our new upgrades and developments. Slowly as this JSF 2.0light comes on, we all will and are benefitting from the glow of improved applicationhealth which results from these improvements and trends. 7
  7. 7. Three of the wide and various changes and improvements which come with JSF 2.0are as follows: 1) the incorporation of Facelets into JSF as a default view technology,2) the improvements in navigation for JSF, and 3) the incorporation of AJAX into theJSF framework to deliver standard AJAX usage and functionality.With these three sweeping changes alone, JSF is infused with vitality and cured ofseveral ailments which have plagued it for quite a while: lack of templating, difficultyof implementation, and lack of standard support of Ajax calls, which are ever-morebecoming commonplace. 9
  8. 8. When Jacob Hookom authored Facelets, it was as a supplemental functionality tostandard JSF. The default view description technology was JSP, but by using theFacelets ViewHandler and libraries, the JSF 1.x developer was given access to awonderful world of first class templating, and a variety of other positive featureswhich made JSF faster and cleaner-running.In fact much of the improvements that come with JSF 2.0 are not only available as aresult of the adoption of facelets, they are also not available if you choose to keepgoing with JSP as a view description technology with JSF 2.0. 10
  9. 9. Templating is a process by which you can give your web applications a consistent lookand feel and to allow similar GUI page sub-sections to be included at will with yourpages without reinventing the wheel.With JSP as the view description technology in JSF 1.x applications, templatingoptions were still wide and varied, including third-party tools and frameworks likeTiles, Oracle ADF Regions, JSP includes, and (yes) Facelets. Now that Facelets is thedefault view description technology for JSF 2.0, it is very easy to use Facelets withoutincluding any external java or tag libraries.Using Facelets tags such as ui:composiion, ui:define, ui:decorate, and ui:insert, youcan create templates for your JSF application very easily. Not only do these Facelettags behave well, but they also accept parameters. These parameters, unlike usingJSP includes, will allow you to include multiple versions of the same JSF pagefragments, varied with different parameter values, into whatever pages you need thattemplate for. 11
  10. 10. I did a presentation at Oracle Open World in 2009 on JSF Custom Components. Tohelp me prepare for this I did some experiments trying to create custom components.Without Facelets and JSF 2.0’s new facilities to handle composite componentscreation the process of creating a custom composite component is very complex.For example when you instantiate the different sub-components which make up thecomposite component you must call special methods for each one to make sure stateis saved properly for each piece in between requests if a postback is done.With JSF 2.0 composite components creating composite components is as easy ascreating a template (the way it should be). You simply manufacture the page the wayyou would want to see it if it were a normal JSF page.Further there is apparently no loss in functionality for these new compositecomponents between pages and these components. For example, if one of yourcomponents within your composite components should use a particular validator,you can use the simple JSF 2.0 syntax to dynamically apply a nested reference to thatvalidator from the caller of the composite component, and apply this reference tothat particular sub-component within your composite component. (see this picture) 12
  11. 11. Up until now, if you use JSP’s you certainly had the option of keeping MVC intact bynot using scriptlets. But in a pinch, it is possible that some one on your team couldslip in a scriptlet now and then, causing a breakdown in your adherence to MVCprecepts.Now we take one step further away from allowing scriptlets by making xhtml thestandard. In this document type scriptlets are no longer allowed, and will be countedas syntactical errors. 13
  12. 12. When I think of Ajax, I think of fantastic GUI components which respond brilliantly toyour every thought. But let’s keep it simple to start with: what if you just wanted topress a button and do an Ajax submit, instead of full post request of the form? Whatwould be involved if you did this in JSF 1.x? Some other language? Well it dependson the language, and there are many frameworks that make it pretty simple. But Ibelieve in many ways that JSF 2.0 has got them beat. 14
  13. 13. Consider the scenario I just described. This, because Ajax is built into the JSF 2.0framework, is as simple as nesting the components which would have been nested ina h:form component now in an h:ajax component. That is it…you have nowaccomplished what I just described. In all the other Ajax frameworks I have seen thissimple move toward Ajaxian functionality would always be more complex.Part of what makes this possible is that each component has a default Ajax actionassociated based on whether it is an Action component (like a link or button) or aeditable value holder component (like a field or drop-down list). However if you wantto key in on some other client side event you still have access to it in JSF 2.0 veryeasily. 15
  14. 14. Ajax is all about JavaScript, of course: JavaScript is the “J” in the acronym AJAX. Buttoo often getting the results you want with an Ajax framework results in you havingto write JavaScript…perhaps lots of it.JSF 2.0 does its best to eliminate most if not all JavaScript…at least for the commonAjax needs.For example if you want to do an Ajax submit on change of a field value, you justembed an Ajax tag inside the input field on which you want to key your submit. Thenthe f:ajax tag just needs an attribute set to tell it what to render when the partialsubmit goes through. By default the client event that is keyed off of for an input fieldis onchange/onblur. If you set the f:ajax tag to an event=“keyup” then any key strokein this field will give you a submit.If, for example, however, you wanted your page to do some client side checking everykeystroke, but only wanted to do a submit if they had not typed for 3 consecutiveseconds, the you would need to do a bit of JavaScript. In that case, however, JSF 2.0offers the direct call possibility into the jsf.ajax.request function, so you could define afunction on your onkeyup for your h:inputText and still get away with the minimumamount of JavaScript coding. 16
  15. 15. You can be as specific or a general as you want…down to customizing the code thatdoes the Ajax request and callback functions, if needed.The JSF 2.0 standard requires that implementations provide a JavaScript resourcewith a library named javax.faces and resource name jsf.js. In this JavaScript file thereis a global object called jsf, which must have exactly two properties called ajax andutil. These details are not so important, but what *is* important is that you cancompletely replace this implementation or pieces of it if needed…it is just that mostpeople don’t need to.If you need to just override part of it, it is still fairly convenient. Let’s say that youwanted to make a client event go and get some data to use on your main page. To dothis you could use the f:ajax tag’s listener attribute to specify a method which wouldgenerate the XML data file on the response stream . Then you could use the oneventattribute to specify the javascript callback function to call, and you could process theXML response when it was completed.Additionally with the execute attribute you can include other components in thepartial submit. 17
  16. 16. Navigation is much friendlier with JSF 2.0. Of primary importance to beginners andalso to probably most common use-cases, implicit navigation is a new feature whichgive everybody a break. Now a lot of the hassle has been removed from the processof simply navigating from one JSF page to the next within the same JSF application.But that is only on the surface. Even when you dig deeper, you will find that JSF hasrepaired quite a bit of reasons HTML purists had for disliking JSF’s POST method ofrequesting pages. Now with JSF 2.0 it is far easier to abide by purist HTML methodprecepts without having to do a lot of configuration or manual URL crafting.But wait! There is still more…if these features were still not enough to satisfy youthen how about the new flash feature? With the flash “scope” (we are takingsoftware here…not hardware) we can save state when going even acrossapplications! Flash is extremely convenient, not only in JSF 2.0 but also Ruby on Rails.Now how much would you pay? ;-) 18
  17. 17. In JSF 2.0 they now have something called implicit navigation. It used to be thatwhenever you wanted a button to navigate from one page to the next that you had toadd a navigation rule entry to the faces-config.xml file. This was not really thatcomplicated, and there are a lot of visual IDE navigation editors which made it reallysimple anyway.But for rapid prototyping it still seems a bit awkward. So now with JSF 2.0 implicitnavigation allows you use a tag attribute like the following to signify that you with aparticular button/link press to navigate to page xyz.xhtml in your JSF 2.0 application:<h:comandButton action=“xyz” … />As you can see this is much simpler and easier to get up and running, since no faces-config.xml entries are required. 19
  18. 18. In the HTML specification, the actions GET and POST were for different purposes.The GET method was for pages that were idempotent…or which would not affect thestate of the world…read-only if you will. POST was for pages which would affect thestate of the world. So purists have objected to using POST for all requests in JSF goingfrom page to page.With JSF 2.0, if you like the current navigation using POST you can still useh:commandButton or h:commandLink. If you want GET you can conveniently usenew tags called h:button/h:link. These tags are usually used if bookmarkability is atissue, since that is another effect of using POST: with POST, the pages are notbookmarkable, really.(Question: will h:link/h:button be used with view-parameters? Do they get the samesubstitute features for the lifecycle for the parameters? Review this section again, orcreate an example, maybe.)View-parameters are closely related to this topic but will be covered later in thispresentation. 20
  19. 19. Flash is a Map that is available in JSF 2.0 to keep short-term storage across requests.The difference between using flash (named after the same concept from Ruby onRails) and request scope is that flash will work between any two requests – redirects,GET’s, or whatever. This scope is presisted in the web browser in between requests.Flash is not a scope per se that you can specify in faces-config, nor does it have anannotation which can be discovered in your Java code. You must either use EL in yourpage, or get and put against the Flash Map stored in the External context.A chief use of flash is in navigation, but it could be used in other use-cases aswell…perhaps any place you might use request scope. 21
  20. 20. <touch base with purpose of this presentation> 23
  21. 21. The addition of some new system events, of composite components, and of centralexception handling have brought new life to JSF.There are many new system events which allow the JSF developer to place logic withfine granularity and pinpoint accuracy. Before now similar logic had to be added tolarger phase catch buckets, or by other means.Composite Components, brought to you once again by the incorporation of Faceletsinto JSF 2.0, make things easier for component developer or developers of templatesand applications of JSF. What was once very difficult is now very easy, not only at themarkup level but also at the resource specification level. Composite componentdevelopment is now accessible.Exception handlers are a welcome addition as well, giving a precise, central locationfor uniform error and exception handling. This leads to friendlier applications with amore uniform look and feel, which leads to greater end-user confidence. 24
  22. 22. In JSF 1.x it is possible to use events given by PhaseListeners for all manner ofpurposes. However as you begin placing logic in PhaseListeners for various purposes,you begin to realize that the granularity of the PhaseListener is not too rich. And for acomplex application, pretty soon you have a PhaseListener full of disparate logic,which is messy.Having the “right” place to put logic makes the logic easier to find again, even forsomeone that is not familiar with the application. Furthermore, the code that isadjacent to your placed code is closely related by virtue of the specificity of the eventin which it is placed.These new system events actually allow logic to be placed at times during the requestlifecycle which heretofore were not possible, or only at the phase level, which led tokluges. 25
  23. 23. The creation and destruction of an application are now in JSF 2.0 made accessible viatwo system events called PostConstructApplicationEvent andPreDestroyApplicationEvent. In order to create listeners for these events, you needto create <system-event-listener> elements within faces-config.xml, and in thiselement, two sub-elements which specify the name of your listener class and thename of the class of the event with which you want to associate the listener method.(In the current implementations of JSF 2.0, you cannot use the @ListenerForannotation for System Events, even though this is documented in Schalk and Burns asbeing a valid statement to make). (Please note that even if one listener class handlesmultiple event types, you must create multiple system-event-listener entries for themin faces-config.xml.)Once you have this wired up properly you have a guarantee from JSF 2.0 that yourPostConstructApplicationEvent listener will be called exactly once when theApplication is created. So, for example, you do not need to worry about concurrencyin your code for this listener. In this you can initialize databases, create monitoringprocesses, or do anything else that would need to be done once per application.Contrast the new system event which is fired each time an Exception is queued forthe ExceptionHandler. The event is called ExceptionQueuedEvent. In an example Isaw, the custom ExceptionHandler was used to redirect to the login page if theexception was caused by the session timing out. So if, for example, you did not needa redirect, but instead needed just to trigger some sort of logic, then this would beyour event of choice. 26
  24. 24. Component events differ from system events in that they are associated withparticular components on the page instead of global events.How hard would it have been with JSF 1.x to invoke AJAX and then detect andimplement logic only under the circumstances that a particular component was usedin an Ajaxian manner? I shudder to think about it  All kidding aside, now with theAjaxBehaviorEvent you now have an entry point to put logic which will fire every timea particular component fires its “decode” method…that is…on postback.Now also with JSF 2.0, if you have logic for a particular component, you can associatelogic with a PreValidateEvent or a PostValidateEvent which fires before/after theProcess Validations Phase of the request lifecycle. These events fire once for eachcomponent that is about to be/has just been validated.And regarding state restoration: there is now an component-level event calledPostRestoreState, and it fires after a component had its state restored.Note that if the component is in a data table or some iterating component, I am notsure if it fires once per component or once per component and row of thetable/tree/whatever. I think the former. 27
  25. 25. Removal of a component (?) from a view and adding or removing an entry from acustom scope extend the event possibilities in JSF.Now in JSF 2.0, when the remove() method is called (in any phase) against the listreturned by calling getChildren() on that component, a new event calledPostAddToEvent/PreRemoveFromViewEvent comes into play. This event is also usedin the Renderer implementations for h:outputScript and h:outputStylesheet,cc:insertChildren, and others when these components are moving said componentsto either the head or body parts of the view.It appears that these events are invoked as part of the view restore and save process.Custom Scopes are new to JSF 2.0; and related to custom scope creation anddestruction, there are new events giving access to the following events as well:PostConstructCustomScopeEvent and PreDestroyCustomScopeEvent. Interestinglysince implementers of custom scopes are responsible for publishing these events,they must do so with a call to the Application object’s publishEvent() method. This isused in conjunction with the @PostCreate and @PreDestroy annotations, which markthe methods used for these functions. 28
  26. 26. With composite components JSF 2.0 has put life back into JSF custom componentdevelopment. At a trip to Oracle Open World in 2009, I heard one of the leaders ofthe JSF development community say that he felt sorry for anybody who hadexperienced the process of creating custom components in JSF 1.x. He was sayingthis in the context of talking about JSF 2.0’s improvements in this realm.Compared to JSF 1.x and JSP methods of creating custom UI components, JSF 2.0methods are very, very easy by and large. I estimate that the new functionality in JSF2.0 related to developing custom components will take care of 80% of the people’sneeds that would decide that custom component development is what they need fortheir applications and use-cases. For the remaining 20%, it is still possible to do theold method of custom components development; so nothing has been lost. Much asbeen gained with this move.This advancement is once again brought to you by Facelets. The people who aremainly helped by this advancement are the people who want to package a set ofcomponents into a single component. An impressive aspect of this is that not onlyare you able to group components into a single components, but also you have fine-grained access to the internal components, and the ability to relate the interface ofthe aggregate component to the encapsulated sub-components. 29
  27. 27. If the goal of a JSF 2.0 developer is to simply to put a page fragment into a compositecomponent page it can often be done with the simple use of a type of Facelets taglibrary called a JSF Composite Component Library. It is this facility that givesbeginners a fighting chance to create some custom components in JSF.So some of the variables are removed from the equation to simplify setup forcreating a composite component. The xhtml file that is using the compositecomponent must add a namespace declaration of “xmlns:<libraryreference>=http://java.sun.com/jsf/composite</optional library name>The defining page must have a file name that matches the tag name to be referencedin the document page which uses the composite component in question. Also thispage must be put in the “resources</optional library name>” directory.The defining page itself has an optional interface element, and a mandatoryimplementation element. In general the implementation is where you would put themarkup that you want to be included in your composite component. The interface iswhere you tie the interface of the composite component tag in the using page to thecode in the implementation section of the defining page. So if your interface is notcomplex, then you can create a usable composite component very quickly. 30
  28. 28. If you take the basic building blocks available to the beginner in JSF, it is possible toadd on to that, a number of details that can wield quite a lot of power. The interfaceelement can include a number of sub-elements that link the using page to thecomposite component’s implementation section.The cc:attribute element has a name attribute which allows the calling tag with anattribute with the same name to pass a value to the composite component. Thisvalue can be accessed with the #{cc.attrs.<name>} EL expression in theimplementation section.Cc:editableValueHolder is another element in the interface section. Its purpose is toallow the tag in the using page to attach a converter or validator to a particulareditable value holder within the composite component. As such, the name attributeof the cc:editableValueHolder can be referenced by an id attribute of an elementwithin the implementation section of the composite component definition. Similarlyit is possible to attach action listeners using the cc:actionSource interface element.Facets are transferred via the cc:facet element, and implemented via thecc:renderFacet element.Children of an element can be placed in the implementation using thecc:insertChildren element. 31
  29. 29. Part of using composite components -- the Facelets Tag Handlers, UIComponentsubclass and the facelet-taglib.xml -- is done for you. The Renderer sub-class can bedefined manually along with the validators, converters and listeners you mightspecify.If Composite Components do not offer enough flexibility or features, however, for thepurposes of the component author, then there is always the standard UI Componentdefinition methods of JSF 1.x, which also work just fine in JSF 2.0.(Question: how much has this process been tweaked in order to use Facelets ratherthan JSP?)Using this facility involves defining a UIComponent Java class and a facelets taglibrary. Additionally, custom Renderers and tag handlers can be defined as well.There is additional help for state management now in JSF 2.0 for component authors.StateHelpers simplify this effort quite a bit; these will be covered further in a laterslide. 32
  30. 30. When I first started working with JSF 1.x, I encountered a lot of situations where myapplication would be fine as long as an error did not occur. If an error did occur,however, Hell started to break loose. The application would either display a totallyunfriendly stack trace for the end-user, or the application would just start workingvery strangely and behaving un-predictably.Adding messages to the FacesContext is a start, but with a Java EE application, youcould have errors coming from several different locations, each with a different lookto the error and with different solutions and work-arounds. MVC code is by designseparated, but the end-user really does not give a darn which part of your applicationyour exceptions originated from, unless you need their help to get some productionproblem fixed. Mostly they just want to do their work.So as I worked more with JSF and read blogs and other documentation, I becameaware of a need for a single place to handle exceptions that would bubble up fromthe JSF application from …whereever.So if you can handle an exception locally to the immediate code, fine; but if it needsto bubble up and get handled, then an exception handler facility is in order. JSF 2.0has made this part of its framework now. 33
  31. 31. In the PhaseListener the JSF 1.x spec says that errors shall be suppressed. I am notsure what the reasons are, but if you have code that you are counting on to fulfillpart of your end-user’s specifications, and an unexpected and unhandled exception isthrown, what will happen is ugly: parts of your end-users’ expectation for yoursoftware goes unmet; they may see the cascading results of this missed error,thinking it is additional instability, they may come to you with a message of “nothingis working!!” And you will have trouble finding the error because no error messageis displayed.This is just an example of how unhandled errors can disrupt an application and erodean end-users faith in a developer, an organization, or even a development framework.So JSF has added an exception handler that will handle errors that bubble upunexpectedly, where at least you can catch and redisplay the error with a request toplease contact the development liaison with some sort of error message. 34
  32. 32. As your applications generate these errors, you can handle them in one place withperhaps a referral to the FacesMessage facility of the FacesContext. This will allowyou to easily access the messages again at render time and display them usingf:message, f:messages, or any other of a number of message display UI components.Using FacesMessage will allow you to partition your errors into several categories anddisplay them differently with different CSS settings.It is also possible to detect certain errors that are unrecoverable and redirect to astandard error page, which might indicate – for example – that the system is currentlyunder maintenance.Ed Burns and Chris Schalk in their JSF 2.0 book gave an example of such a page; theircode only consisted of the faces-config.xml entry redefining theExceptionHandlerFactory entry, and the Java code for the exception handler and theExceptionHandlerFactory. The job of the ExceptionHandler code is to deal with theexpired page error, and redirect to the login page with a message talking aboutadding enhanced security.Compare this to not handling this error at all and having, as I have seen, buttonssimply stop working on their page, under similar circumstances. The difference isamazing. 35
  33. 33. It is fairly easy to implement a custom ExceptionHandler. The way to do this in JSF2.0 is to edit the faces-config.xml and add an <exception-handler-factory> inside a<factory> element. Inside this factory element you need to put the fully qualifiedclass name of the ExceptionHandlerFactory. This class (which I think uses thedecorator pattern) is very easy to override. In it you need to override thegetExceptionHandler() method that simply creates a new instance of another classyou define which should extend from javax.faces.context.ExceptionHandlerWrapper.This class also uses the decorator pattern. It needs it’s handle() method overwritten.In Schalk and Burns’s JSF 2.0 book, there is a great example of how to do this.It is nice to know that unlike some other ExceptionHandling schemes that might notbe centrally located, here you only have to go as far as the customExceptionHandlerFactory to find out where your exception handler code is location inyour application. 36
  34. 34. <touch base again with the purpose of this presentation> 38
  35. 35. Some additional features of JSF 2.0 which are big improvements are Partial StateSaving, the addition of View Parameters, and the way JSF 2.0 now handles resources.These are all interesting topics.Partial State Saving changes have improved JSF in a number of ways. The mainthemes here are to not save state unnecessarily, and to secondarily make it moreconvenient to save state when it is necessary. From the component usersperspective, JSF is more efficient; so it uses less space wherever you have configuredto save space, and it takes less time to save and restore state at the ends of therequest lifecycle. 39
  36. 36. Overall JSF’s approach to state saving has improved with age. You may have noticedthat on a JSF page if you have a field and a button embedded in a h:form component,and you put a value in it, and press the button you will still see the value you put intothe field when the screen re-renders. This consistency between requests illustratesthe effects of State Saving. In JSF this can be carried out on either the client or serverside.But the techniques and API’s used in JSF 1.x were not very efficient or overly easy touse. So in JSF 2.0 improvements were made to fix these things.The first issue fixed was to make the page only save the state of the items that werechanged instead of everything on the page. For a big form this is a huge differenceand saved a lot of time and space.The second issue dealt with the method by which the JSF component developerswent about the business of saving component state. This method was clunky anderror prone. This problem too was summarily fixed.There were a number of interesting details related to these two changes which I willtry to share with you today. 40
  37. 37. Why do we care about the size of saved state? If you are a JSF application developerthen you are aware in JSF 1.x that state can either be saved on the client side orserver side in between requests. Client side saving actually stores the state of thepage encoded in a field in the page. Server side stores it in precious Session memory.Either way, the larger a page gets, the bigger your commitment to saving everythingabout every component on the page in one of these places. This actually slows yourapplication and wastes resources.In JSF 2.0 its implementers made a change which also made by Adam Weiner threeyears earlier for Apache Trinidad, which was to restore state instead by recreating thepage (starting with the markup), then apply whatever changes were different fromthe markup. They called this “partial” state saving.There are lots of details to consider when implementing this kind of optimized statesaving regime. But JSF 2.0 has most of it figured out and implemented in a very niceway.The reference page of this presentation has further reading by Jacob Hookom. Ibelieve there is a connection between using Facelets as the view descriptiontechnology now, and this state saving debacle. 41
  38. 38. Part and parcel to this issue of partial state saving is the new help that has come intoplay with JSF 2.0 for component developers, which now makes it easier to save thestate of your component in between requests.Whereas in JSF 1.x you had to store your state into huge hierarchical arrays, now inJSF 2.0 it seems that you store just the elements which are changing from the defaultexecution of the page (like attributes) in a Map stored in an object called aStateHelper, which is accessible from components.It used to be you had to override saveState() and restoreState() methods aftercreating a local variable of the type you wanted to save, along with a getter andsetter for this. In order to use this simpler syntax you create a property key in anenum in your component, and in your getter and setter you retrieve StateHelperinstance from your component, and either put or add your value into the StateHelper.Your getter can either call get or eval for an abitrary Object or a boolean. Muchsimpler. 42
  39. 39. PartialStateHolder is an interface defined in JSF 2.0, which contains amarkInitialState() method. It is implemented by any component that needs to saveits state between requests. When developing a custom component in JSF, onerequirement is that if state must be saved, you as the component developer must tellthe JSF framework when in the request lifecycle the state should be saved. The wayto tell the framework to do this is to use the markInitialState method. This indicatesto the JSF 2.0 framework that starting at that time in the request cycle, theframework needs to note what the initial state of the component looks like for lateralteration by the saved state. 43
  40. 40. Similar to JBoss Seam’s page parameters, View Parameters are a great addition to JSFin its 2.0 version. For the people who have argued that JSF should not have beenusing POST method for non-update functions, the view parameters offer a declarativeway of spelling out these parameters, instead of hand-crafting the URL. Now duringPOST-REDIRECT-GET we can have parameters indicated to carry state forward in away which keeps our URL’s bookmarkable and also keeps our request methods pureand on the straight and narrow.But it is even better than all that. With this view parameter implementation we notonly get a declarative means of setting up our URL for a GET later, but we also havebuilt into this facility all the aspects of the JSF request lifecycle, which would normallybe lost on a POST-REDIRECT-GET, simply because the redirect stomps on saidlifecycle.So lets look at the various parts of the lifecycle and see how View Parameters areenabled by new features of JSF 2.0 relating to them. 44
  41. 41. Typically in navigation between pages in JSF, there is a page you start from and a pageyou are going to. Let’s call the page you navigating from the Source page, and thepage you are going to the Target page. The target page, then is where you woulddefine parameters declaratively.These definitions occur in a section of the xhtml page that is new to the JSF 2.0 spec:the <f:metadata> section, which is optional. In f:metadata element, you can havezero or more f:viewParam elements. Essentially you can specify attributes for each ofthese consisting mainly of a name value pair, just as you would expect.In the source page, you will find a component to enable JSF navigation using thenavigation handler like h:commandButton or h:commandLink. In this tag you will seean action attribute, the value of which would include text like “someoutcome?faces-redirect=true&amp;includeViewParams=true”. When JSF sees this request it goes tothe target page to look a the metadata section to see what parameters it shouldcreate. Then it refers to the source page’s component having a clientId equal to thename of the parameters defined in the target page, and gets their values to put onthe command line. 45
  42. 42. It is notable that the f:viewParam definitions in the target page can contain EL as theirvalue. So this means the JSF framework in version 2.0 gives you a way to resurrectthe action of writing values to the model, just like in the JSF request lifecycle phaseUpdate Model. So the REDIRECT removed the lifecycle, but JSF 2.0 give equivalentfunctionality back to you with EL in the parameter value to define an assignmenttarget for the parameter.In a similar style to the functionality replaced with allowing EL in the values of theview parameters, we can also include validators and converters in the viewparameters. This is because request parameteters come in as text and need to beconverted before they get to the model, if there is some non-String datatype.And in case you think they forgot, you can also run application code after the viewparameters are validated and written to the model. This is done with a new eventdefined in JSF 2.0 called the PreRenderViewEvent. This event fires before a pagerenders but after the view parameters have finished validation and writing to themodel. So you can actually create code that acts upon the parameter values in somemanner. 46
  43. 43. Of late the topic of bookmarkability has become more popular. Perhaps it is becauseof discussions concerning REST-based web services, or perhaps it is related to JSF’suse of post, or maybe it is just a trend. Whatever the reason it is important to be ableto bookmark a page for later access. For example on a confirmation page to atransaction you may want to allow an end user to bookmark a receipt for atransaction for later printing.It is possible to create a bookmarkable link using these view parameters. If you usethe h:link or h:button you can configure a page to turn your link into a fullybookmarkable URL. If you have a page like this receipt page I gave an example, andif it had view parameters defined for it, you could add the same“whateverthecurrentpageis?faces-redirect=true&amp;includeViewParams=true” inthe outcome attribute value.The h:link and h:button actually produce GET methods which means that the URL’sthey produce would call up the current page, and since your outcome references thesame page, it pulls the view parameters and the page values for these parametersinto the constructed URL. So you can either right-click the link to add it as abookmark, or actually click the button and then the URL will be bookmarkable. 47
  44. 44. Resources are a great asset to the JSF 2.0 offering and spec. If you have ever doneany custom component development in JSF 1.x, you know this is true. As I wasworking through Schalk and Burns’s complete reference for JSF 1.x, after all theconveniences built into JSF, I was floored to discover the gigantic chink in the armorof JSF. If you are building a component in JSF 1.x and you wanted a resource…say aCSS file or a JS file…which I dare say EVERY component developer would want tohave, the way to do that was to use a PhaseListener or a ServletFilter andcommandeer the request when you detected that the request was for a resource youneeded; then fulfill the resource request yourself. It was awful.So there was no standard for where these resource files were to reside in JSF 1.x.And also to make matters worse, if you had a new version of a resource you wouldhave to bounce the application or server to refresh the resource, which is not nice foranybody currently working on the application, and is taboo and inconvenient in someproduction environments.JSF 2.0 has more than atoned for all these idiosyncrasies. 48
  45. 45. So in JSF 2.0 there is no longer any need to use PhaseListeners or servlet Filters totrap resource file requests in order to package your custom components and notinclude the resource in your actual page.If anybody here has ever done this, they know it is a page of code which you have toconfigure just right, and it is several files and entries into those files in addition to thestandard complexity of custom components…which in JSF 1.x was large.In the above code, to contrast, is the way you tell JSF to include a resource file in thehead element of your page when it is rendered. The resource file in question, in thiscase would reside in the docroot directory of your application in a directory calledresources, or a directory called resources on your classpath. So the latter could be ina JAR file under a META-INF/resources directory, or in classes directory under META-INF/resources directory.With the latter method I have actually gotten a sample program up an running usingNetBeans 6.9 and glassfish 3.0.One annotation…yes, I would say that is a vast improvement. 49
  46. 46. In JSF 2.0 there is built right into the spec a facility for including resource versions.When requesting a resource as we did with the annotations in a previous slide, it ispossible that from time to time we may want to install a new version of the resourcefile.JSF 2.0 has built into its workings an ability to detect a new version of a resourcesimply by the name we give it and what directory it is in. And it should do it withoutrequiring the application or the web server instance to be bounced.These are great features. The manner in which you implement this versioningfeature, I hear, is quite strange however:• Inserting a new version of the library would require you to add the version as adirectory name. So /resources/mylib/mycss.css would become/resources/mylib/1.1/mycss.css•Inserting a new version of the resource gets even stranger:/resources/mylib/mycss.css would have the next version of/resources/mylib/mycss.css/1_1_0Note in the second example that 1_1_0.css is the name of the new resource file, andthat mycss.css is the name of a directory (mycss.css is the directory name notmycss/css). 50
  47. 47. Due to the JSF 2.0 standards, the maintenance application developer will have astandard place to look now for resource files.As a maintainer of a newly built JSF 2.0 system, you would look for directories on thedocroot or classpath that begin with the directory name of resources, either inside oroutside of META-INF directories.That should help reduce the amount of time it takes to find a resource file in anapplication.Of course I guess you could always search the whole app for anything ending in .css,but this is much cleaner. 51
  48. 48. Well? 52
  49. 49. While, in their day, JSF 1.1 and JSF 1.2 have served the user community, the appdeveloper and the component developer well, we also are ready to admit thatperhaps there is room for improvement.We have experienced – some of us first hand (!) – how certain aspects of JSF 1.xcaused hardships and difficulties in getting different tasks completed. We have alsoseen how the JSF communities from around the world came together to prioritize,debate and decide what to do about it. 54
  50. 50. Now as we have ended the first year of life with JSF 2.0 being available to thedeveloper community, we see the adoption of this standard by quite a few companiesto be used in creating applications for various end-user communities.We also see an increasing number of development platforms, and componentdevelopers taking JSF 2.0 in hand and creating products which utilize some of thegreat new features and improvements we have talked about today.For example Oracle is finalizing plans for the next major revision of their JdeveloperIDE and ADF Faces Rich Client to be JSF 2.0 compatible. This is just the beginning ofthe adoption of this standard for Oracle, and to some degree they are beingconservative by waiting so long. There is a book, for example, by Anghel Leonard,called JSF 2.0 Cookbook, which came out right when JSF 2.0 did, and gave example ofabout 50 different component suites, platforms and IDE’s that were already JSF 2.0compatible.But this is just the tip of the iceberg. Compatibility is being closely followed by full-fledged adoption (not the same thing!), both by companies wishing to create JSF 2.0applications and others generating new products and services. 55
  51. 51. This group of people represents a larger community that is deciding every day, whatthey are going to recommend – at their next meeting, getting coffee at work, at thecompany barbeque, even at this meeting.We either are the movers and the shakers or we contribute to where the movers andshakers are taking us, by what jobs we choose, by what new technologies weexperiment with, and by how well these different technologies fit what we think weneed to do with our professional lives.It is time to check out this JSF 2.0 offering. By being here you have already taken thefirst step. What will you do with this information? 56
  52. 52. I would now like to open the table for questions… 57
  53. 53. These resources are just the surface. There are tons of resources out there, in booksand in minutes and write-ups from development processes which are going on all thetime. 58
  54. 54. This is the image the audience will walk away from the presentation in their minds. 59