What's new and exciting with JSF 2.0


Published on

This presentation (best viewed with the notes view in ppt, individually) is an overview of new features of JSF 2.0.

Published in: Lifestyle, Technology
  • 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
  • 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 also needed additional enhancements. For example, JSF was still heavily tied to JSP, which led to a misalignment of life cycles which caused odd rendering issues periodically, and also led to inefficiency in general processing. And yet it was good enough when it came out so that not many complained about these things…because they knew better days were coming. So JSF developers produced applications with JSF 1.x, and dealt with and worked around these various inefficiencies and nuisances.
  • Java, Java EE, and JSF professionals worldwide contributed to the JSF specification and in building the reference implementation. This group and the expectant world of JSF developers were super-charged by the improvements and enhancements promised by JSF 2.0. The expectation was that not only would JSF 2.0 atone for past work-arounds and inefficiencies, but that it would also be incorporating best of breed technological practices from a variety of popular frameworks, and providing solutions to problems that had not even occurred yet, thereby creating a better development environment in which JSF developers could create their future applications.
  • 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 again through an awkward method of hijacking requests. Navigation had to be explicitly defined, making it very difficult for beginners to do very simple navigations. Events were present but they were not very fine grained or specific, so the events that existed became a means to enact all kinds of logic, which made it difficult to find or sort through logic and business rules that existed in an application. Templating was developing 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 for improvement.
  • The effort put forth by the Java/Java EE communities has indeed borne fruit. Many of the deficiencies which tripped up and plagued JSF component developers, JSF web application developers, and JSF application users have been solved. What is resulting is the dawning of an era of higher-performing applications, higher standards, and increased positive results and outcomes for JSF application end-users. Broad-sweeping changes together with a myriad tiny improvements have transformed JSF back to its former position of leadership in the race for web development supremacy.
  • At this time there are many JSF component development organizations which have taken initial steps toward creating new components which are compatible with JSF 2.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 of which is Oracle, which has mapped out a plan to guide their development efforts which incorporates more and more features provided by JSF 2.0. Other organizations are developing similar game plans. The only thing is: we must all do 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.0 light comes on, we all will and are benefitting from the glow of improved application health which results from these improvements and trends.
  • Three of the wide and various changes and improvements which come with JSF 2.0 are 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 the JSF framework to deliver standard AJAX usage and functionality. With these three sweeping changes alone, JSF is infused with vitality and cured of several ailments which have plagued it for quite a while: lack of templating, difficulty of implementation, and lack of standard support of Ajax calls, which are ever-more becoming commonplace.
  • When Jacob Hookom authored Facelets, it was as a supplemental functionality to standard JSF. The default view description technology was JSP, but by using the Facelets ViewHandler and libraries, the JSF 1.x developer was given access to a wonderful world of first class templating, and a variety of other positive features which made JSF faster and cleaner-running. In fact much of the improvements that come with JSF 2.0 are not only available as a result of the adoption of facelets, they are also not available if you choose to keep going with JSP as a view description technology with JSF 2.0.
  • Templating is a process by which you can give your web applications a consistent look and feel and to allow similar GUI page sub-sections to be included at will with your pages without reinventing the wheel. With JSP as the view description technology in JSF 1.x applications, templating options were still wide and varied, including third-party tools and frameworks like Tiles, Oracle ADF Regions, JSP includes, and (yes) Facelets. Now that Facelets is the default view description technology for JSF 2.0, it is very easy to use Facelets without including any external java or tag libraries. Using Facelets tags such as ui:composiion, ui:define, ui:decorate, and ui:insert, you can create templates for your JSF application very easily. Not only do these Facelet tags behave well, but they also accept parameters. These parameters, unlike using JSP includes, will allow you to include multiple versions of the same JSF page fragments, varied with different parameter values, into whatever pages you need that template for.
  • I did a presentation at Oracle Open World in 2009 on JSF Custom Components. To help 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 components creation the process of creating a custom composite component is very complex. For example when you instantiate the different sub-components which make up the composite component you must call special methods for each one to make sure state is 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 as creating a template (the way it should be). You simply manufacture the page the way you would want to see it if it were a normal JSF page. Further there is apparently no loss in functionality for these new composite components between pages and these components. For example, if one of your components 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 that validator from the caller of the composite component, and apply this reference to that particular sub-component within your composite component. (see this picture)
  • Up until now, if you use JSP’s you certainly had the option of keeping MVC intact by not using scriptlets. But in a pinch, it is possible that some one on your team could slip in a scriptlet now and then, causing a breakdown in your adherence to MVC precepts. Now we take one step further away from allowing scriptlets by making xhtml the standard. In this document type scriptlets are no longer allowed, and will be counted as syntactical errors.
  • When I think of Ajax, I think of fantastic GUI components which respond brilliantly to your every thought. But let’s keep it simple to start with: what if you just wanted to press a button and do an Ajax submit, instead of full post request of the form? What would be involved if you did this in JSF 1.x? Some other language? Well it depends on the language, and there are many frameworks that make it pretty simple. But I believe in many ways that JSF 2.0 has got them beat.
  • Consider the scenario I just described. This, because Ajax is built into the JSF 2.0 framework, is as simple as nesting the components which would have been nested in a h:form component now in an h:ajax component. That is it…you have now accomplished what I just described. In all the other Ajax frameworks I have seen this simple move toward Ajaxian functionality would always be more complex. Part of what makes this possible is that each component has a default Ajax action associated based on whether it is an Action component (like a link or button) or a editable value holder component (like a field or drop-down list). However if you want to key in on some other client side event you still have access to it in JSF 2.0 very easily.
  • Ajax is all about JavaScript, of course: JavaScript is the “J” in the acronym AJAX. But too often getting the results you want with an Ajax framework results in you having to write JavaScript…perhaps lots of it. JSF 2.0 does its best to eliminate most if not all JavaScript…at least for the common Ajax needs. For example if you want to do an Ajax submit on change of a field value, you just embed an Ajax tag inside the input field on which you want to key your submit. Then the f:ajax tag just needs an attribute set to tell it what to render when the partial submit goes through. By default the client event that is keyed off of for an input field is onchange/onblur. If you set the f:ajax tag to an event=“keyup” then any key stroke in this field will give you a submit. If, for example, however, you wanted your page to do some client side checking every keystroke, but only wanted to do a submit if they had not typed for 3 consecutive seconds, the you would need to do a bit of JavaScript. In that case, however, JSF 2.0 offers the direct call possibility into the jsf.ajax.request function, so you could define a function on your onkeyup for your h:inputText and still get away with the minimum amount of JavaScript coding.
  • You can be as specific or a general as you want…down to customizing the code that does the Ajax request and callback functions, if needed. The JSF 2.0 standard requires that implementations provide a JavaScript resource with a library named javax.faces and resource name jsf.js. In this JavaScript file there is a global object called jsf, which must have exactly two properties called ajax and util. These details are not so important, but what *is* important is that you can completely replace this implementation or pieces of it if needed…it is just that most people don’t need to. If you need to just override part of it, it is still fairly convenient. Let’s say that you wanted to make a client event go and get some data to use on your main page. To do this you could use the f:ajax tag’s listener attribute to specify a method which would generate the XML data file on the response stream . Then you could use the onevent attribute to specify the javascript callback function to call, and you could process the XML response when it was completed. Additionally with the execute attribute you can include other components in the partial submit.
  • Navigation is much friendlier with JSF 2.0. Of primary importance to beginners and also to probably most common use-cases, implicit navigation is a new feature which give everybody a break. Now a lot of the hassle has been removed from the process of 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 has repaired quite a bit of reasons HTML purists had for disliking JSF’s POST method of requesting pages. Now with JSF 2.0 it is far easier to abide by purist HTML method precepts 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 you then how about the new flash feature? With the flash “scope” (we are taking software here…not hardware) we can save state when going even across applications! Flash is extremely convenient, not only in JSF 2.0 but also Ruby on Rails. Now how much would you pay? ;-)
  • In JSF 2.0 they now have something called implicit navigation. It used to be that whenever you wanted a button to navigate from one page to the next that you had to add a navigation rule entry to the faces-config.xml file. This was not really that complicated, and there are a lot of visual IDE navigation editors which made it really simple anyway. But for rapid prototyping it still seems a bit awkward. So now with JSF 2.0 implicit navigation allows you use a tag attribute like the following to signify that you with a particular 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.
  • 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 the state of the world…read-only if you will. POST was for pages which would affect the state of the world. So purists have objected to using POST for all requests in JSF going from page to page. With JSF 2.0, if you like the current navigation using POST you can still use h:commandButton or h:commandLink. If you want GET you can conveniently use new tags called h:button/h:link. These tags are usually used if bookmarkability is at issue, since that is another effect of using POST: with POST, the pages are not bookmarkable, really. (Question: will h:link/h:button be used with view-parameters? Do they get the same substitute features for the lifecycle for the parameters? Review this section again, or create an example, maybe.) View-parameters are closely related to this topic but will be covered later in this presentation.
  • 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 on Rails) 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 an annotation which can be discovered in your Java code. You must either use EL in your page, 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 as well…perhaps any place you might use request scope.
  • <touch base with purpose of this presentation>
  • The addition of some new system events, of composite components, and of central exception handling have brought new life to JSF. There are many new system events which allow the JSF developer to place logic with fine granularity and pinpoint accuracy. Before now similar logic had to be added to larger phase catch buckets, or by other means. Composite Components, brought to you once again by the incorporation of Facelets into JSF 2.0, make things easier for component developer or developers of templates and applications of JSF. What was once very difficult is now very easy, not only at the markup level but also at the resource specification level. Composite component development is now accessible. Exception handlers are a welcome addition as well, giving a precise, central location for uniform error and exception handling. This leads to friendlier applications with a more uniform look and feel, which leads to greater end-user confidence.
  • In JSF 1.x it is possible to use events given by PhaseListeners for all manner of purposes. 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 a complex 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 for someone that is not familiar with the application. Furthermore, the code that is adjacent to your placed code is closely related by virtue of the specificity of the event in which it is placed. These new system events actually allow logic to be placed at times during the request lifecycle which heretofore were not possible, or only at the phase level, which led to kluges.
  • The creation and destruction of an application are now in JSF 2.0 made accessible via two system events called PostConstructApplicationEvent and PreDestroyApplicationEvent. In order to create listeners for these events, you need to create <system-event-listener> elements within faces-config.xml, and in this element, two sub-elements which specify the name of your listener class and the name 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 @ListenerFor annotation for System Events, even though this is documented in Schalk and Burns as being a valid statement to make). (Please note that even if one listener class handles multiple event types, you must create multiple system-event-listener entries for them in faces-config.xml.) Once you have this wired up properly you have a guarantee from JSF 2.0 that your PostConstructApplicationEvent listener will be called exactly once when the Application is created. So, for example, you do not need to worry about concurrency in your code for this listener. In this you can initialize databases, create monitoring processes, 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 for the ExceptionHandler. The event is called ExceptionQueuedEvent. In an example I saw, the custom ExceptionHandler was used to redirect to the login page if the exception was caused by the session timing out. So if, for example, you did not need a redirect, but instead needed just to trigger some sort of logic, then this would be your event of choice.
  • Component events differ from system events in that they are associated with particular components on the page instead of global events. How hard would it have been with JSF 1.x to invoke AJAX and then detect and implement logic only under the circumstances that a particular component was used in an Ajaxian manner? I shudder to think about it  All kidding aside, now with the AjaxBehaviorEvent you now have an entry point to put logic which will fire every time a 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 associate logic with a PreValidateEvent or a PostValidateEvent which fires before/after the Process Validations Phase of the request lifecycle. These events fire once for each component that is about to be/has just been validated. And regarding state restoration: there is now an component-level event called PostRestoreState, 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 not sure if it fires once per component or once per component and row of the table/tree/whatever. I think the former.
  • Removal of a component (?) from a view and adding or removing an entry from a custom scope extend the event possibilities in JSF. Now in JSF 2.0, when the remove() method is called (in any phase) against the list returned by calling getChildren() on that component, a new event called PostAddToEvent/PreRemoveFromViewEvent comes into play. This event is also used in the Renderer implementations for h:outputScript and h:outputStylesheet, cc:insertChildren, and others when these components are moving said components to 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 and destruction, there are new events giving access to the following events as well: PostConstructCustomScopeEvent and PreDestroyCustomScopeEvent. Interestingly since 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 is used in conjunction with the @PostCreate and @PreDestroy annotations, which mark the methods used for these functions.
  • With composite components JSF 2.0 has put life back into JSF custom component development. At a trip to Oracle Open World in 2009, I heard one of the leaders of the JSF development community say that he felt sorry for anybody who had experienced the process of creating custom components in JSF 1.x. He was saying this 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.0 methods are very, very easy by and large. I estimate that the new functionality in JSF 2.0 related to developing custom components will take care of 80% of the people’s needs that would decide that custom component development is what they need for their applications and use-cases. For the remaining 20%, it is still possible to do the old method of custom components development; so nothing has been lost. Much as been gained with this move. This advancement is once again brought to you by Facelets. The people who are mainly helped by this advancement are the people who want to package a set of components into a single component. An impressive aspect of this is that not only are 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 of the aggregate component to the encapsulated sub-components.
  • If the goal of a JSF 2.0 developer is to simply to put a page fragment into a composite component page it can often be done with the simple use of a type of Facelets tag library called a JSF Composite Component Library. It is this facility that gives beginners a fighting chance to create some custom components in JSF. So some of the variables are removed from the equation to simplify setup for creating a composite component. The xhtml file that is using the composite component must add a namespace declaration of “xmlns:<library reference>=http://java.sun.com/jsf/composite</optional library name> The defining page must have a file name that matches the tag name to be referenced in the document page which uses the composite component in question. Also this page must be put in the “resources</optional library name>” directory. The defining page itself has an optional interface element, and a mandatory implementation element. In general the implementation is where you would put the markup that you want to be included in your composite component. The interface is where you tie the interface of the composite component tag in the using page to the code in the implementation section of the defining page. So if your interface is not complex, then you can create a usable composite component very quickly.
  • If you take the basic building blocks available to the beginner in JSF, it is possible to add on to that, a number of details that can wield quite a lot of power. The interface element can include a number of sub-elements that link the using page to the composite component’s implementation section. The cc:attribute element has a name attribute which allows the calling tag with an attribute with the same name to pass a value to the composite component. This value can be accessed with the #{cc.attrs.<name>} EL expression in the implementation section. Cc:editableValueHolder is another element in the interface section. Its purpose is to allow the tag in the using page to attach a converter or validator to a particular editable value holder within the composite component. As such, the name attribute of the cc:editableValueHolder can be referenced by an id attribute of an element within the implementation section of the composite component definition. Similarly it is possible to attach action listeners using the cc:actionSource interface element. Facets are transferred via the cc:facet element, and implemented via the cc:renderFacet element. Children of an element can be placed in the implementation using the cc:insertChildren element.
  • Part of using composite components -- the Facelets Tag Handlers, UIComponent subclass and the facelet-taglib.xml -- is done for you. The Renderer sub-class can be defined manually along with the validators, converters and listeners you might specify. If Composite Components do not offer enough flexibility or features, however, for the purposes of the component author, then there is always the standard UI Component definition 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 rather than JSP?) Using this facility involves defining a UIComponent Java class and a facelets tag library. 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 later slide.
  • When I first started working with JSF 1.x, I encountered a lot of situations where my application 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 totally unfriendly stack trace for the end-user, or the application would just start working very strangely and behaving un-predictably. Adding messages to the FacesContext is a start, but with a Java EE application, you could have errors coming from several different locations, each with a different look to the error and with different solutions and work-arounds. MVC code is by design separated, but the end-user really does not give a darn which part of your application your exceptions originated from, unless you need their help to get some production problem fixed. Mostly they just want to do their work. So as I worked more with JSF and read blogs and other documentation, I became aware of a need for a single place to handle exceptions that would bubble up from the JSF application from …whereever. So if you can handle an exception locally to the immediate code, fine; but if it needs to bubble up and get handled, then an exception handler facility is in order. JSF 2.0 has made this part of its framework now.
  • In the PhaseListener the JSF 1.x spec says that errors shall be suppressed. I am not sure what the reasons are, but if you have code that you are counting on to fulfill part of your end-user’s specifications, and an unexpected and unhandled exception is thrown, what will happen is ugly: parts of your end-users’ expectation for your software 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 “nothing is working!!” And you will have trouble finding the error because no error message is displayed. This is just an example of how unhandled errors can disrupt an application and erode an 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 up unexpectedly, where at least you can catch and redisplay the error with a request to please contact the development liaison with some sort of error message.
  • As your applications generate these errors, you can handle them in one place with perhaps a referral to the FacesMessage facility of the FacesContext. This will allow you to easily access the messages again at render time and display them using f: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 and display them differently with different CSS settings. It is also possible to detect certain errors that are unrecoverable and redirect to a standard error page, which might indicate – for example – that the system is currently under maintenance. Ed Burns and Chris Schalk in their JSF 2.0 book gave an example of such a page; their code only consisted of the faces-config.xml entry redefining the ExceptionHandlerFactory entry, and the Java code for the exception handler and the ExceptionHandlerFactory. The job of the ExceptionHandler code is to deal with the expired page error, and redirect to the login page with a message talking about adding enhanced security. Compare this to not handling this error at all and having, as I have seen, buttons simply stop working on their page, under similar circumstances. The difference is amazing.
  • It is fairly easy to implement a custom ExceptionHandler. The way to do this in JSF 2.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 qualified class name of the ExceptionHandlerFactory. This class (which I think uses the decorator pattern) is very easy to override. In it you need to override the getExceptionHandler() method that simply creates a new instance of another class you 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 not be centrally located, here you only have to go as far as the custom ExceptionHandlerFactory to find out where your exception handler code is location in your application.
  • <touch base again with the purpose of this presentation>
  • Some additional features of JSF 2.0 which are big improvements are Partial State Saving, 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 main themes here are to not save state unnecessarily, and to secondarily make it more convenient to save state when it is necessary. From the component users perspective, JSF is more efficient; so it uses less space wherever you have configured to save space, and it takes less time to save and restore state at the ends of the request lifecycle.
  • Overall JSF’s approach to state saving has improved with age. You may have noticed that 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 into the field when the screen re-renders. This consistency between requests illustrates the effects of State Saving. In JSF this can be carried out on either the client or server side. But the techniques and API’s used in JSF 1.x were not very efficient or overly easy to use. 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 were changed instead of everything on the page. For a big form this is a huge difference and saved a lot of time and space. The second issue dealt with the method by which the JSF component developers went about the business of saving component state. This method was clunky and error prone. This problem too was summarily fixed. There were a number of interesting details related to these two changes which I will try to share with you today.
  • Why do we care about the size of saved state? If you are a JSF application developer then you are aware in JSF 1.x that state can either be saved on the client side or server side in between requests. Client side saving actually stores the state of the page 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 everything about every component on the page in one of these places. This actually slows your application and wastes resources. In JSF 2.0 its implementers made a change which also made by Adam Weiner three years earlier for Apache Trinidad, which was to restore state instead by recreating the page (starting with the markup), then apply whatever changes were different from the markup. They called this “partial” state saving. There are lots of details to consider when implementing this kind of optimized state saving regime. But JSF 2.0 has most of it figured out and implemented in a very nice way. The reference page of this presentation has further reading by Jacob Hookom. I believe there is a connection between using Facelets as the view description technology now, and this state saving debacle.
  • Part and parcel to this issue of partial state saving is the new help that has come into play with JSF 2.0 for component developers, which now makes it easier to save the state of your component in between requests. Whereas in JSF 1.x you had to store your state into huge hierarchical arrays, now in JSF 2.0 it seems that you store just the elements which are changing from the default execution of the page (like attributes) in a Map stored in an object called a StateHelper, which is accessible from components. It used to be you had to override saveState() and restoreState() methods after creating a local variable of the type you wanted to save, along with a getter and setter for this. In order to use this simpler syntax you create a property key in an enum in your component, and in your getter and setter you retrieve StateHelper instance 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. Much simpler.
  • PartialStateHolder is an interface defined in JSF 2.0, which contains a markInitialState() method. It is implemented by any component that needs to save its state between requests. When developing a custom component in JSF, one requirement is that if state must be saved, you as the component developer must tell the JSF framework when in the request lifecycle the state should be saved. The way to tell the framework to do this is to use the markInitialState method. This indicates to the JSF 2.0 framework that starting at that time in the request cycle, the framework needs to note what the initial state of the component looks like for later alteration by the saved state.
  • Similar to JBoss Seam’s page parameters, View Parameters are a great addition to JSF in its 2.0 version. For the people who have argued that JSF should not have been using POST method for non-update functions, the view parameters offer a declarative way of spelling out these parameters, instead of hand-crafting the URL. Now during POST-REDIRECT-GET we can have parameters indicated to carry state forward in a way which keeps our URL’s bookmarkable and also keeps our request methods pure and on the straight and narrow. But it is even better than all that. With this view parameter implementation we not only get a declarative means of setting up our URL for a GET later, but we also have built into this facility all the aspects of the JSF request lifecycle, which would normally be lost on a POST-REDIRECT-GET, simply because the redirect stomps on said lifecycle. So lets look at the various parts of the lifecycle and see how View Parameters are enabled by new features of JSF 2.0 relating to them.
  • Typically in navigation between pages in JSF, there is a page you start from and a page you are going to. Let’s call the page you navigating from the Source page, and the page you are going to the Target page. The target page, then is where you would define 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 have zero or more f:viewParam elements. Essentially you can specify attributes for each of these 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 the navigation handler like h:commandButton or h:commandLink. In this tag you will see an action attribute, the value of which would include text like “someoutcome?faces-redirect=true&includeViewParams=true”. When JSF sees this request it goes to the target page to look a the metadata section to see what parameters it should create. Then it refers to the source page’s component having a clientId equal to the name of the parameters defined in the target page, and gets their values to put on the command line.
  • It is notable that the f:viewParam definitions in the target page can contain EL as their value. So this means the JSF framework in version 2.0 gives you a way to resurrect the action of writing values to the model, just like in the JSF request lifecycle phase Update Model. So the REDIRECT removed the lifecycle, but JSF 2.0 give equivalent functionality back to you with EL in the parameter value to define an assignment target for the parameter. In a similar style to the functionality replaced with allowing EL in the values of the view parameters, we can also include validators and converters in the view parameters. This is because request parameteters come in as text and need to be converted 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 view parameters are validated and written to the model. This is done with a new event defined in JSF 2.0 called the PreRenderViewEvent. This event fires before a page renders but after the view parameters have finished validation and writing to the model. So you can actually create code that acts upon the parameter values in some manner.
  • Of late the topic of bookmarkability has become more popular. Perhaps it is because of discussions concerning REST-based web services, or perhaps it is related to JSF’s use of post, or maybe it is just a trend. Whatever the reason it is important to be able to bookmark a page for later access. For example on a confirmation page to a transaction you may want to allow an end user to bookmark a receipt for a transaction for later printing. It is possible to create a bookmarkable link using these view parameters. If you use the h:link or h:button you can configure a page to turn your link into a fully bookmarkable URL. If you have a page like this receipt page I gave an example, and if it had view parameters defined for it, you could add the same “whateverthecurrentpageis?faces-redirect=true&includeViewParams=true” in the outcome attribute value. The h:link and h:button actually produce GET methods which means that the URL’s they produce would call up the current page, and since your outcome references the same page, it pulls the view parameters and the page values for these parameters into the constructed URL. So you can either right-click the link to add it as a bookmark, or actually click the button and then the URL will be bookmarkable.
  • Resources are a great asset to the JSF 2.0 offering and spec. If you have ever done any custom component development in JSF 1.x, you know this is true. As I was working through Schalk and Burns’s complete reference for JSF 1.x, after all the conveniences built into JSF, I was floored to discover the gigantic chink in the armor of JSF. If you are building a component in JSF 1.x and you wanted a resource…say a CSS file or a JS file…which I dare say EVERY component developer would want to have, the way to do that was to use a PhaseListener or a ServletFilter and commandeer the request when you detected that the request was for a resource you needed; 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 would have to bounce the application or server to refresh the resource, which is not nice for anybody currently working on the application, and is taboo and inconvenient in some production environments. JSF 2.0 has more than atoned for all these idiosyncrasies.
  • So in JSF 2.0 there is no longer any need to use PhaseListeners or servlet Filters to trap resource file requests in order to package your custom components and not include the resource in your actual page. If anybody here has ever done this, they know it is a page of code which you have to configure just right, and it is several files and entries into those files in addition to the standard 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 the head element of your page when it is rendered. The resource file in question, in this case would reside in the docroot directory of your application in a directory called resources, or a directory called resources on your classpath. So the latter could be in a 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 using NetBeans 6.9 and glassfish 3.0. One annotation…yes, I would say that is a vast improvement.
  • 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 is possible that from time to time we may want to install a new version of the resource file. JSF 2.0 has built into its workings an ability to detect a new version of a resource simply by the name we give it and what directory it is in. And it should do it without requiring the application or the web server instance to be bounced. These are great features. The manner in which you implement this versioning feature, I hear, is quite strange however: Inserting a new version of the library would require you to add the version as a directory 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_0 Note in the second example that 1_1_0.css is the name of the new resource file, and that mycss.css is the name of a directory (mycss.css is the directory name not mycss/css).
  • Due to the JSF 2.0 standards, the maintenance application developer will have a standard place to look now for resource files. As a maintainer of a newly built JSF 2.0 system, you would look for directories on the docroot or classpath that begin with the directory name of resources, either inside or outside of META-INF directories. That should help reduce the amount of time it takes to find a resource file in an application. Of course I guess you could always search the whole app for anything ending in .css, but this is much cleaner.
  • Well?
  • While, in their day, JSF 1.1 and JSF 1.2 have served the user community, the app developer and the component developer well, we also are ready to admit that perhaps there is room for improvement. We have experienced – some of us first hand (!) – how certain aspects of JSF 1.x caused hardships and difficulties in getting different tasks completed. We have also seen how the JSF communities from around the world came together to prioritize, debate and decide what to do about it.
  • Now as we have ended the first year of life with JSF 2.0 being available to the developer community, we see the adoption of this standard by quite a few companies to be used in creating applications for various end-user communities. We also see an increasing number of development platforms, and component developers taking JSF 2.0 in hand and creating products which utilize some of the great new features and improvements we have talked about today. For example Oracle is finalizing plans for the next major revision of their Jdeveloper IDE and ADF Faces Rich Client to be JSF 2.0 compatible. This is just the beginning of the adoption of this standard for Oracle, and to some degree they are being conservative 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 of about 50 different component suites, platforms and IDE’s that were already JSF 2.0 compatible. 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.0 applications and others generating new products and services.
  • This group of people represents a larger community that is deciding every day, what they are going to recommend – at their next meeting, getting coffee at work, at the company barbeque, even at this meeting. We either are the movers and the shakers or we contribute to where the movers and shakers are taking us, by what jobs we choose, by what new technologies we experiment with, and by how well these different technologies fit what we think we need to do with our professional lives. It is time to check out this JSF 2.0 offering. By being here you have already taken the first step. What will you do with this information?
  • I would now like to open the table for questions…
  • These resources are just the surface. There are tons of resources out there, in books and in minutes and write-ups from development processes which are going on all the time.
  • This is the image the audience will walk away from the presentation in their minds.
  • What's new and exciting with JSF 2.0

    1. 1. Increasing JSF’s vitality with version 2.0 enhancements By Michael Fons ADF Developer SquareTwo Financial
    2. 2. Act I
    3. 3. Many JSF developers were not thriving with JSF 1.x.
    4. 4. Java professionals worldwide invigorated the JSF 2.0 redo.
    5. 5. JSF 1.x turned out to be weak, and needed to become more fit.
    6. 6. JSF 2.0 has infused JSF with life and given JSF back its edge.
    7. 7. The Java EE community builds its health by adopting JSF 2.0!
    8. 8. Act II, Scene 1
    9. 9. Features like Facelets, Navigational changes, and Ajax strengthen JSF.
    10. 10. Facelets creates many strong capabilities.
    11. 11. Facelets makes templating straightforward. <ul><li>ui:composition, </li></ul><ul><li>ui:define, </li></ul><ul><li>ui:decorate, and </li></ul><ul><li>ui:insert </li></ul>
    12. 12. Developers can easily create composite components now. <ul><li>Caller page: </li></ul><ul><li><xyz:myComp …> </li></ul><ul><li><f:validateLength for=“myClientId” …/> </li></ul><ul><li></xyz:myComp> </li></ul><ul><li>Composite component Interface section: </li></ul><ul><li><cc:editableValueHolder name=“myClientId”…/> </li></ul><ul><li>Composite component Implementation: </li></ul><ul><li><h:inputText … id=“myClientId”/> </li></ul>
    13. 13. Using XHTML now eliminates scriptlets. <ul><li>Not allowed <% …java code … %> </li></ul><ul><li>Only XHTML allowed. </li></ul>
    14. 14. JSF 2.0 implements Ajax in a natural way.
    15. 15. Tiny syntactical changes tap into lots of Ajax capability. <ul><li>Using AJAX </li></ul><ul><li><f:ajax …> </li></ul><ul><li><h:inputText …/> </li></ul><ul><li></f:ajax> </li></ul><ul><li>OR </li></ul><ul><li><h:form> </li></ul><ul><li><h:inputText …> </li></ul><ul><li><f:ajax render=“@form”/> </li></ul><ul><li></h:inputText> </li></ul><ul><li></h:form> </li></ul>Non-AJAX <h:form> <h:inputText …/> <h:commandButton …/> </h:form>
    16. 16. Developers do not need any JavaScript in many cases. <ul><li><h:form id=&quot;form&quot;> </li></ul><ul><li><!-- ******M E T H O D 1********** --> </li></ul><ul><li><h:outputText id=&quot;output&quot; </li></ul><ul><li>value=&quot;You entered </li></ul><ul><li>#{requestScope['input']}. &quot;/> </li></ul><ul><li><h:inputText id=&quot;input“ </li></ul><ul><li>value=&quot;#{requestScope.input}” > </li></ul><ul><li><f:ajax render=&quot;form:output“ </li></ul><ul><li>event=&quot;keyup&quot; /> </li></ul><ul><li></h:inputText> </li></ul><ul><li></h:form> </li></ul>
    17. 17. A developer can still implement any custom Ajax solution. <ul><li><h:form id=&quot;form&quot; > </li></ul><ul><li><!-- *******M E T H O D 2******** --> </li></ul><ul><li><h:outputText id=&quot;output2&quot; value=&quot;You entered #{requestScope['input2']}. &quot;/> </li></ul><ul><li><h:inputText id=&quot;input2&quot; </li></ul><ul><li>value=&quot;#{requestScope.input2}&quot; </li></ul><ul><li>onkeyup =&quot;var lArgs = {}; lArgs['render'] = 'form:output2'; l Args['javax.faces.behavior.event'] = 'keyup' ; jsf.ajax.request(this,event,lArgs);”> </li></ul><ul><li><!-- If I did not want to change from the default event for the inputText, </li></ul><ul><li>the call would be jsf.ajax.request(this, event, {render:’form:output2’}); </li></ul><ul><li>but I want to change the event, and they have named that property with </li></ul><ul><li>periods in it. in jsf.js line 1659 I am getting an error because </li></ul><ul><li>there is a syntax problem when I set javax.faces.behaviour.event property to keyup </li></ul><ul><li>because the periods in the property name throw the js interpreter off--> </li></ul><ul><li></h:inputText> </li></ul><ul><li></h:form> </li></ul>
    18. 18. The navigation makes JSF 2.0 friendlier.
    19. 19. Implicit navigation makes navigation easier. <ul><li>… To go to page xyz.xhtml, </li></ul><ul><li>you can use… </li></ul><ul><li><h:comandButton action=“xyz” … /> </li></ul>
    20. 20. Post-redirect-get and bookmarkability strengthen JSF. <ul><li>POST method: </li></ul><ul><li><h:commandButton/> OR </li></ul><ul><li><h:commandLink/> </li></ul><ul><li>GET method: </li></ul><ul><li><h:button/> OR </li></ul><ul><li><h:link/> </li></ul>
    21. 21. Flash supplements JSF navigation. <ul><li>Using EL: </li></ul><ul><li>#{flash.someVariable} </li></ul><ul><li>… to keep what is already stored there for another request… </li></ul><ul><li>#{flash.keep.someVariable} </li></ul><ul><li>Using Java: </li></ul><ul><li>Flash lFlash = </li></ul><ul><li>FacesContext.getCurrentInstance(). </li></ul><ul><li>getExternalContext().getFlash(); </li></ul><ul><li>lFlash.get(“someVariable”); </li></ul>
    22. 22. Act II, Scene 2
    23. 23. JSF 1.1/1.2 have lost favor due to their unhealthiness.
    24. 24. Events, Components, and Exception Handling invigorate JSF.
    25. 25. Expanded System Events allows precision placement of logic.
    26. 26. Application create/destroy and exceptions now all create events. <ul><li><application> </li></ul><ul><li><system-event-listener> </li></ul><ul><li><system-event-listener-class> </li></ul><ul><li>mfons.experiments.jsf20.TestPostConstructApplicationEventListener </li></ul><ul><li></system-event-listener-class> </li></ul><ul><li><system-event-class> </li></ul><ul><li>javax.faces.event.PostConstructApplicationEvent </li></ul><ul><li></system-event-class> </li></ul><ul><li></system-event-listener> </li></ul><ul><li><system-event-listener> </li></ul><ul><li><system-event-listener-class> </li></ul><ul><li>mfons.experiments.jsf20.TestPostConstructApplicationEventListener </li></ul><ul><li></system-event-listener-class> </li></ul><ul><li><system-event-class> </li></ul><ul><li>javax.faces.event.PreDestroyApplicationEvent </li></ul><ul><li></system-event-class> </li></ul><ul><li></system-event-listener> </li></ul><ul><li></application> </li></ul>
    27. 27. Component events now include AJAX, validation, and state. <ul><li>… this statement… </li></ul><ul><li><f:ajax … listener=&quot;#{myBean.checkAjaxBehavior}&quot;/> </li></ul><ul><li>… creates this event for each Ajax event for the components to which this f:ajax tag applies… </li></ul><ul><li>public void checkAjaxBehavior(AjaxBehaviorEvent pEvent){ </li></ul><ul><li>System.out.println(&quot;This inputText has Ajax behavior and it is right now undergoing a decode method call in the request values phase of the JSF request lifecycle&quot;); </li></ul><ul><li>} </li></ul>
    28. 28. Removal from view and scope changes increase events. <ul><li>Good reference to know when PostAddToViewEvent and PreRemoveFromViewEvent are fired: </li></ul><ul><li>https://issues.apache.org/jira/browse/MYF ACES-2638 </li></ul>
    29. 29. JSF 2.0 heals custom components development.
    30. 30. Beginners can quickly combine components to make their own. <ul><li>A using page references… </li></ul><ul><li>xmlns:<library reference>=http://java.sun.com/jsf/composite</optional library name> </li></ul><ul><li>… and will reference… </li></ul><ul><li><lr:xyz …/> </li></ul><ul><li>… if the library reference is “lr” and the name of the definition file is “resources</optional library name>/xyz.xhtml” </li></ul>
    31. 31. Intermediates can add much complexity simply in most cases. <ul><li><cc:interface> </li></ul><ul><li><cc:attribute name=“ someattr ”/> </li></ul><ul><li><cc:editableValueHolder … /> </li></ul><ul><li><cc:actionSource … /> </li></ul><ul><li></cc:interface> </li></ul><ul><li><cc:implementation> </li></ul><ul><li><h:outputText value=“#{cc.attrs. someattr }”/> </li></ul><ul><li></cc:implementation> </li></ul>
    32. 32. JSF 2.0 still has its old custom component options for experts. <ul><li>Non-composite component authors define… </li></ul><ul><li>… UIComponent Java class </li></ul><ul><li>… Facelets tag library </li></ul><ul><li>… Renderers </li></ul><ul><li>… tag handlers </li></ul><ul><li>Easier state management, now… </li></ul>
    33. 33. Exception handling increases JSF’s IQ.
    34. 34. Unhandled errors are disruptive to an application. <ul><li>Nobody wants to hear… </li></ul><ul><li>NOTHING IS WORKING!!!! </li></ul>
    35. 35. Having a consistent error handling interface is calming. <ul><li>...in faces-config.xml… </li></ul><ul><li>You can redefine </li></ul><ul><li>ExceptionHandlerFactory </li></ul>
    36. 36. Now global error-handling schemes can be found. <ul><li>The custom </li></ul><ul><li>ExceptionHandlerFactory </li></ul><ul><li>Can provide… </li></ul><ul><li>A custom ExceptionHandler </li></ul>
    37. 37. Act II, Scene 3
    38. 38. JSF 1.1/1.2 have lost favor due to their unhealthiness.
    39. 39. State Saving, View Parameters, and Resources revitalize JSF.
    40. 40. Toned State Saving improves JSF.
    41. 41. The partial state feature minimizes the state saved. <ul><li>Thanks, </li></ul><ul><li>Adam </li></ul><ul><li>Weiner! </li></ul>
    42. 42. Component developers enjoy the simpler syntax. <ul><li>StateHelper has </li></ul><ul><li>Eliminated </li></ul><ul><li>The need for… </li></ul><ul><li>saveState() and </li></ul><ul><li>restoreState() </li></ul><ul><li>@Overrides! </li></ul>
    43. 43. Developers now say when a component has its initial state. <ul><li>PartialStateHolder.markInitialState() </li></ul><ul><li>is needed for component developers. </li></ul>
    44. 44. View Parameters increase JSF developers’ options.
    45. 45. Developers can declaratively define GET parameters. <ul><li>In caller page link/button outcome… </li></ul><ul><li>someoutcome?faces-redirect=true&amp;includeViewParams=true </li></ul><ul><li>In target page… </li></ul><ul><li><f:metadata> </li></ul><ul><li><f:viewParam …/> </li></ul><ul><li></f:metadata> </li></ul>
    46. 46. The parameters implement EditableValueHolder. <ul><li>… can write to model… </li></ul><ul><li><f:viewParam name=“something” </li></ul><ul><li>value=“#{some.valueExpression}” /> </li></ul><ul><li>… can invoke application logic… </li></ul><ul><li><f:event type=“preRenderView” </li></ul><ul><li>listener=“#{some.preRenderViewEventListenerMethod}”/> </li></ul>
    47. 47. You can create bookmarkable links with these parameters. <ul><li>… supports bookmarkability… </li></ul><ul><li><h:link …/>/<h:button …/> </li></ul><ul><li>… example: </li></ul><ul><li><h:link outcome=“currentPageName?faces-redirect=true&amp;includeViewParams=true” value=“bookmarkable link to this page”/> </li></ul>
    48. 48. JSF 2.0 power-lifts resource access for custom components.
    49. 49. JSF 2.0 easily serves resources to custom components. <ul><li>@FacesRenderer(rendererType = “…&quot;, componentFamily = “…&quot;) @ResourceDependencies({         @ResourceDependency(name = “mycss.css&quot;, library = “mystyle&quot;, target = &quot;head&quot;), …}) public class MyRenderer extends Renderer { … </li></ul>
    50. 50. Developers can install new resource versions instantly. <ul><li>In resources directory… </li></ul><ul><li>[localePrefix/][libraryName/][ libraryVersion /]resourceName[/ resourceVersion ] </li></ul><ul><li>… where [ ] indicate optionality </li></ul>
    51. 51. Resource files will now reside in predictable locations. <ul><li>… either in docroot: </li></ul><ul><li>/resources/… </li></ul><ul><li>… or in </li></ul><ul><li>META-INF/resources/… </li></ul><ul><li>… somewhere on the classpath. </li></ul>
    52. 52. Has the JSF 2.0 team detoxified JSF 1.x?
    53. 53. Act III
    54. 54. JSF 1.1/1.2 have lost favor due to their unhealthiness.
    55. 55. The Java EE community builds its health by adopting JSF 2.0!
    56. 56. Increasing JSF’s vitality with version 2.0 enhancements…
    57. 57. JSF 2.0 is out, and it’s better than ever!
    58. 58. Resources <ul><li>http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature for help on resources. </li></ul><ul><li>JavaServer Faces 2.0: the complete reference , by Ed Burns, Chris Schalk, McGraw-Hill, 2010. </li></ul><ul><li>http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/ </li></ul><ul><li>http://javaserverfaces.java.net/nonav/docs/2.0/javadocs/javax/faces/component/PartialStateHolder.html </li></ul><ul><li>http://blogs.sun.com/jasondlee/entry/jsf_2_gets_declarative_event </li></ul><ul><li>http://myfaces.apache.org/core20/myfaces-api/apidocs/javax/faces/event/ComponentSystemEvent.html </li></ul><ul><li>http://weblogs.java.net/blog/edburns/archive/2009/09/02/jsf2-composite-component-metadata </li></ul><ul><li>http://weblogs.java.net/blog/jhook/archive/2006/01/experiment_goin_1.html </li></ul><ul><li>http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-157 </li></ul><ul><li>http://www.slideshare.net/jimdriscoll/jsf-2-and-ajax </li></ul><ul><li>http://code.google.com/p/teknoatolye/source/browse/trunk/sinek/src/main/java/org/mca/sinek/jsf/SinekRenderer.java </li></ul><ul><li>https://issues.apache.org/jira/browse/MYFACES-2638 </li></ul>
    59. 59. Contact Info: [email_address]