<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Benny's Blog &#187; JSF</title>
	<atom:link href="http://blog.projectnibble.org/tag/jsf/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.projectnibble.org</link>
	<description>House Of Code</description>
	<lastBuildDate>Fri, 13 Aug 2010 15:06:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Java generic paged lazy List with JSF/JPA example implementation</title>
		<link>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/</link>
		<comments>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 12:58:53 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[lazy loading]]></category>
		<category><![CDATA[paging]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[richfaces]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=310</guid>
		<description><![CDATA[Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc. download PagedList Lazy loading with the PagedList Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a list implementation I came up with to enable true paged data fetching completely transparent to any user. It works independent of persistence layers, such as JPA implementations etc.</p>
<ul>
<li><a href="http://projectnibble.org/dump/blog/pagedlist/PagedList.rar">download PagedList</a></li>
</ul>
<p><span id="more-310"></span></p>
<h3>Lazy loading with the PagedList</h3>
<p>Originally I made the PagedList because I needed paged data fetching using JMS queues for a JSF Rich datatable and datascroller; a common problem in JSF but less commonly solved, even less documented and less still solved in an elegant way. Most people are able to solve this problem by using an <a href="https://www.hibernate.org/43.html">OpenSessionInView</a> antipattern (keeping Hibernate-oid session open until the view requests the lazy loaded data) but since I&#8217;m using JMS queue, this was not an option. I decided to circumvent the entire JSF to JMS queue integration by providing my data in a paging lazy list. It works beautifully.</p>
<pre  name="code" class="java">
public class PagedList&lt;Dto, QueryParameters&gt; extends AbstractList&lt;Dto&gt; {

    private final QueryParameters queryParameters;

    private final PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider;

    private final Map&lt;Integer, List&lt;Dto&gt;&gt; fetchedPages;

    private final int dataSize;

    private final int pageSize;

    public PagedList(PagedDataProvider&lt;Dto, QueryParameters&gt; pagedDataProvider, QueryParameters queryParameters) {
        this.pagedDataProvider = pagedDataProvider;
        this.queryParameters = queryParameters;
        fetchedPages = new HashMap&lt;Integer, List&lt;Dto&gt;&gt;();
        dataSize = pagedDataProvider.getDataSize();
        pageSize = pagedDataProvider.getPageSize();
    }

    public Dto get(int index) {
        int pageNr = (int) Math.floor(index / pageSize);
        if (fetchedPages.get(pageNr) == null) {
            fetchedPages.put(pageNr, pagedDataProvider.provide(pageNr, queryParameters));
        }
        return fetchedPages.get(pageNr).get(index % pageSize);
    }

    public int size() {
        return dataSize;
    }
}
</pre>
<p>It is different from <a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/list/LazyList.html">Apache&#8217;s LazyList</a> (and many other implementations) in that it relies on an external dataprovider to provide the dataset&#8217;s total size, pagesize and data provision itself. For example, using my lazy list version the <i>size()</i> method actually returns the total size of data potentially available, not just physically available in the list at the present. This way the list works completely transparent to its users. Also, there is no simple factory being passed in that creates dummy objects or something: actual remote data is being fecthed in pages by a data provider. Pages being fetched are independent of each other; when requesting page 5, page 1 through 4 are not need or fetched.</p>
<p>The PagedList works in combo with a <em>PagedDataProvider</em> interface that external dataproviders (some dao for example) could implement. So it has no dependencies whatsoever on some specific implementation. The paged data provider provides the total size of the dataset, the page size and pages of the dataset itself when needed.</p>
<h3>Example implementation for JSF and JPA dao</h3>
<p>Here&#8217;s an example implementation which ties a JSF Richfaces datatable to a JPA dao using a PagedList. I cut out the service layer, view handlers/controllers and whatnot for sake of simplicity.</p>
<pre  name="code" class="xhtml">
&lt;rich:dataTable id="searchResults" value="#{appleService.apples}" var="apple"&gt;
...
&lt;/rich:dataTable&gt;
</pre>
<pre  name="code" class="java">
/**
 * JPA dao which acts as paged data provider for the paged list.
 *
 * Relies on two JPA named queries specified on the Entity being fetched.
 *
 * @author Benny Bottema
 * @see PagedDataProvider
 */
public class AppleJPADao implements AppleDao, PagedDataProvider&lt;AppleDto, AppleQueryParameters&gt; {

    // entitymanager stuff omitted for example (real world: injected by Spring)

    private static final int PAGESIZE = 50;

    /**
     * @see AppleDao#getAllApples(String, String)
     */
    public List&lt;AppleDto&gt; getAllApples(String type, String quality) {
        // optional query parameters: can be null
        AppleQueryParameters params = new AppleQueryParameters();
        params.setAppleType(type);
        params.setAppleQuality(quality);
        return new PagedList&lt;AppleDto, AppleQueryParameters&gt;(this, params);
    }

    /**
     * @see PagedDataProvider#provide(int, Object)
     */
    public List&lt;AppleDto&gt; provide(int page, AppleQueryParameters queryCriteria) {
        Query query = entityManager.createNamedQuery("Apple.findAll");
        query.setParameter("appleType", queryCriteria.getAppleType());
        query.setParameter("appleQuality", queryCriteria.getAppleQuality());
        // JPA's paging mechanism
        query.setFirstResult(PAGESIZE * page);
        query.setMaxResults(PAGESIZE);
        return (List&lt;AppleDto>) query.getResultList();
    }

    /**
     * @see PagedDataProvider#getDataSize()
     */
    public int getDataSize() {
        Query countQuery = entityManager.createNamedQuery("Apple.count");
        return ((Long) countQuery.getSingleResult()).intValue();
    }

    /**
     * @see PagedDataProvider#provide()
     */
    public int getPageSize() {
        return PAGESIZE;
    }
}
</pre>
<h3>Known issues</h3>
<p>So far there is only one known issue, which is more of a problem with lazy loading in general: synchronizing the lazy loading list with the remote dataset to avoid becoming stale when changes happen to the dataset. Example: when the dataset changes, the size of the list is not being updated and the <i>get()</i> method may try to fetch wrong or even unavailable data throwing an exception. Since I&#8217;m using the paged list in a limited way, I&#8217;ve not yet encountered this problem. </p>
<p>One way would be to solve this problem for the Rich datable and datascroller specifically is to have a a4j poll component that listens for dataset changes on the server and refreshes the entire datatable as necessary. Just thinking out loud here&#8230;</p>
<p><a href="http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/07/22/java-generic-paged-lazy-list-with-jsfjpa-example-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSF is a diamond in the rough, you just need to make it shine</title>
		<link>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/</link>
		<comments>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/#comments</comments>
		<pubDate>Sun, 24 May 2009 13:30:53 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[PrettyFaces]]></category>
		<category><![CDATA[a4j]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[richfaces]]></category>
		<category><![CDATA[seam]]></category>
		<category><![CDATA[tomahawk]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=108</guid>
		<description><![CDATA[[RE: JSF – Still pretty much a steaming pile of donkey turd] &#8211; I was replying to Wille Faler’s post about why JSF sucks, when the comment was getting too large, so I made it into a post on my own blog. JSF is hard to learn yes, but in my opinion it doesn&#8217;t suck [...]]]></description>
			<content:encoded><![CDATA[<div style="color:#999999">
<p>[RE: JSF – Still pretty much a steaming pile of donkey turd] &#8211; I was replying to <a href="http://faler.wordpress.com/2007/03/13/jsf-still-pretty-much-a-steaming-pile-of-donkey-turd/">Wille Faler’s post about why JSF sucks</a>, when the comment was getting too large, so I made it into a post on my own blog.</p>
</div>
<hr />
<p><b>JSF is hard to learn yes, but in my opinion it doesn&#8217;t suck as bad as Wille says. All the points Wille mentions can be solved by certain libraries or write-once reusable solutions (I&#8217;ve included my &#8216;magical&#8217; combination of frameworks on the bottom). JSF is a diamond in the rough, you just need to make it shine.</b></p>
<p><span id="more-108"></span></p>
<h3>The devil is in the details</h3>
<p>There are a couple of pitfalls you need to know about with JSF. It&#8217;s all really a matter of having read a good book about JSF that points them out, or having learned them the hard way. Luckily I&#8217;ve had some guidance by experienced colleagues of mine; I&#8217;m guessing that&#8217;s the missing factor in Wille&#8217;s situation.</p>
<p>Referring to the pitfalls you need to know about, I&#8217;m talking about the common beginner&#8217;s problems like using JSTL c:tags that cause havoc when combined with those of jsf and facelets. I&#8217;m talking about the Ajax4Jsf details as Wille mentioned: once you know what to use it&#8217;s easy. Those 48 attributes? most of them are inherited and never used and you can forget about them, and that&#8217;s the learning curve. Once you know the right ones, it&#8217;s using exactly those, over and over again. And things like how you can incorporate Spring security and stuff like that. Another pitfall that comes to mind is how action=&#8221;" work quirky with navigation rules when using the array notation (action=&#8221;controller['action']&#8220;). And ofcourse there&#8217;s the issue of <a href="http://blog.projectnibble.org/2008/07/26/parameterized-jsf-facelets-validators/">parameterized JSF validators</a>, which needs some understanding. All pitfalls that can baffle a beginner or intermediate.</p>
<p>The thing with JSF is there are a number of little things that are hard to solve, but once you&#8217;re past that it <i>does</i> make you much more productive. You just have to have a solid base to start from each project. The pitfalls learning curve is definitely a downside of JSF, but <a href="http://blogs.jsfcentral.com/jsf2group/entry/jsf_2_primer">JSF 2.0</a> is in the making to solve all these issues.</p>
<h3>Bad performance or beginner&#8217;s mistake?</h3>
<p>Then there is this performance issue Wille mentions, where I think he missed the target: JSF does not have to be slow at all. It really depends on how you treat your backing beans. JSF has the weird tendency to call setters/getters multiple times, which seems utterly pointless (it&#8217;s related to resolving valuebindings in nested components). I&#8217;ve made the mistake before to directly retrieve values from a controller/service in my views instead of a static model (backing bean): this is what makes things slow. JSF in itself isn&#8217;t that slow for a webapp: yes there are many redundant calls but we&#8217;re not dealing with a realtime simulation application, webapps do just fine. On a sidenote, it also depends on the implementation&#8230; JSF is a reference specification, while there are various implementations of the framework (IBM&#8217;s, Sun&#8217;s etc.)</p>
<h3>SEO friendly JSF?</h3>
<p>Ahh, but for the <a href="http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/">JSF Search Engine Friendliness</a>. That&#8217;s solved too, somewhat. There&#8217;s is a framework called <a href="http://ocpsoft.com/prettyfaces/">PrettyFaces</a> which allows you to dynamically generate/interpret pretty GET urls with bean values. It&#8217;s a great framework that solves a common problem, but there still exists the problem that existing jsf/facelets/richfaces components are not generating SEO HTML code. That&#8217;s really the fault of the component makers, not JSF, though JSF definitely isn&#8217;t innocent with its POST obsession: PrettyFaces fixes at least that.</p>
<h3>Common sense: use frameworks to avoid most pitfalls</h3>
<p>Once you&#8217;ve got those kind of things down and use a good framework combo, JSF is straightforward. You won&#8217;t really need to know about the various phases and you can be very productive if you&#8217;ve set up the jsf/facelets components right. I&#8217;ve worked with JSF intensively for about a year now in various projects with various implementations and I hardly ever need to use phaselisteners and that sort of stuff. The rare cases where you do need them, you can define these things ones and reuse them in other projects. With this approach I&#8217;ve created a template project with some standard libraries, phaselisteners, security set up, facelets components etc. and I&#8217;m up and running in no time.</p>
<p>I haven&#8217;t sanitized or otherwise cleaned up the template project so I won&#8217;t put that up for the time being, but at least I can tell you what frameworks are in it by default. </p>
<ul>The magical combination that works for me and my colleagues: </p>
<li>JSF (MVC)</li>
<li>Facelets (Templating, use of XHTML)</li>
<li><a href="http://livedemo.exadel.com/richfaces-demo/richfaces/inputNumberSlider.jsf?c=inputNumberSlider&#038;tab=usage">Richfaces</a> (component suite)</li>
<li><a href="http://livedemo.exadel.com/richfaces-demo/richfaces/commandButton.jsf?c=commandButton&#038;tab=usage">Richfaces A4J</a> (Ajax support)</li>
<li><a href="http://myfaces.apache.org/tomahawk/index.html">Tomahawk</a> (only for <a href="http://myfaces.apache.org/tomahawk/extensionsFilter.html">file uploads with the Extensions Filter</a>)</li>
<li>PrettyFaces (for indexable GET urls)</li>
</ul>
<p>Now that I&#8217;ve mentioned these, you should check out <a href="http://www.jboss.com/products/seam/">JBoss Seam</a> as well, which basically is supposed to do everything the above libraries do combined, plus a couple of things more like solving the <a href="http://matthiaswessendorf.wordpress.com/2008/11/19/conversation-scope-and-jsf-or-your-favorite-web-framework/">conversational scope</a> issue. I haven&#8217;t worked with this framework myself though so I can&#8217;t speak from experience.</p>
<h3>Final note</h3>
<p>Although I agree JSF has some annoying pitfalls, shortcomings and a high learning curve, it&#8217;s been out there for enough time to pass for supplement frameworks to pop up from under the ground to solve most of these problems.</p>
<p>With the right combination, most classic counter arguments have become obsolete. Maybe it&#8217;s time for critics to take JSF as is: incomplete but ultimately making you more productive if combined with the right frameworks.</p>
<p><a href="http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/trackback/">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/05/24/jsf-is-a-diamond-in-the-rough-you-just-need-to-make-it-shine/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Bookmarkable and SEO Friendly JSF with PrettyFaces</title>
		<link>http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/</link>
		<comments>http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 08:00:29 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[advanced jsf]]></category>
		<category><![CDATA[bookmarkable]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[GET links]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[PrettyFaces]]></category>
		<category><![CDATA[SEO]]></category>

		<guid isPermaLink="false">http://blog.projectnibble.org/?p=20</guid>
		<description><![CDATA[Yes, it is possible. Yes, it requires hacking JSF with filters and/or phaselisteners and/or custom servlets for encoding/decoding serializing/deserializing GET parameters and force redirects upon JSF view resolvers. The good news however: it&#8217;s all been done before and you can just hang back and use a small framework that does all this stuff for you. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Yes, it is possible. Yes, it requires hacking JSF with filters and/or phaselisteners and/or custom servlets for encoding/decoding serializing/deserializing GET parameters and force redirects upon JSF view resolvers. The good news however: it&#8217;s all been done before and you can just hang back and use a small framework that does all this stuff for you. Enter <a href="http://ocpsoft.com/prettyfaces/">PrettyFaces</a>.</strong></p>
<p>But before we come to that, I would like to show you how PrettyFaces sums up what you need. This involves solving two problems: <strong>The JSF POST compulsion</strong> and <strong>the JSF Redirect problem</strong>. You can in fact solve all of these problems seperately, but PrettyFaces just encapsulates all these annoying things for you in a convenient little jar.</p>
<p><span id="more-20"></span></p>
<h2>1. GET urls? The POST-back problem with JSF</h2>
<p>In one sentence: JSF uses POST requests for *everything*, so there is are no nice copy-pastable GET urls. For example, if you use your generic h:commandLink, a POST submit is being done on the surrounding form to get everything into JSF. JSF needs this because the form contains a lot of extra (meta) data for the input to be processed by the JSF framework. You could for example indicate that the state information should be stored on the view instead of the server, which is then simply added to the HTML form behind the scene. Now this kind of stuff, you don&#8217;t want in GET urls. It would cause every action you perform on the website to result in a hideous string of code in the browser bar, which isn&#8217;t even copy/pastable to begin with since it contains encoded directions for the server based on specific state (ie. getEmailadresFromCurrentClient, which won&#8217;t work if there is no current client available).</p>
<p>There are instances where you would want GET urls, which work in a stateless fasion. For example <code>.../faces/newsarticle?article=2334</code>. However, the developers at JSF appearantly thought &#8220;If we don&#8217;t need it, you don&#8217;t need it&#8221;, since there is no way in JSF to configure URL mapping using GET parameters. And this is the heart of the problem. This is where all the hacks come in.</p>
<h3>The POST-back solution</h3>
<p>There are a couple of methods to approach this problem. Or rather, the concept is the same, but applied in different ways. The concept is that you intercept a HTTP request, manually extract the parameters from the request URL and apply them to your model (a JSF managed bean for example). The POST problem can be split up into two subproblems: GET url interpretation and GET url generation.</p>
<h3>Solving the GET url interpretation</h3>
<p>You can interpet GET urls in JSF by defining a custom Servlet and have these urls go through it rather than through the faces servlet. In the custom servlet, process the parameters and then redirect the browser to a faces url without these parameters. You need a redirect, since a server-forward won&#8217;t trigger another servlet to act on the mapping. If you still want to forward on the server, you need to <a href="http://wiki.apache.org/myfaces/InvokingJsfPagesWithStandardUrls#head-6c1aaf488d48f938896da962aaa4361ec3ffaf70">create a FacesContext, fix the viewroot and handle the view navigation yourself</a> and so imitate what the faces servlet would&#8217;ve done. There are libraries out there that contain this solution ready to go.</p>
<p>You cannot do it with a filter for the Faces Servlet, because GET parameters will have been removed already. An alternative to GET parameters is to work the parameters into the url itself (something like <code>http://www.peanutbutter.com/faces/newsitems/params/id-22234.xhtml</code>), but this won&#8217;t work either since a filter has no influence on the url passed on to the servlet for further processing. So you can&#8217;t remove the url-based-parameters from the URL and let JSF deal with the rest; it will simply fail to understand our custom parameter format.</p>
<p>Another way that does work is to create a custom JSF PhaseListener. You&#8217;ll still have lost the GET parameters, but at least you can do something about the url based parameters mentioned in the paragraph before (that and you already have a FacesContext you can use). In this case, you extract the parameters before the RESTORE_VIEW phase and use the resting url to manually set the view root for JSF to work with. Jason put an example of this <a href="http://blogs.steeplesoft.com/jsf-phaselisteners-and-get-requests/">manual url based parameter PhaseListener mechanism</a> on his blog. Before PrettyFaces I based my own solution on this concept like Jason&#8217;s, but Jason incorrectly comments [in his code] that you cannot infer the original view url in this case. I solved this by adding a keyword <code>/params/</code> in between the url and parameters. Lucas from Amis has a <a href="http://technology.amis.nl/blog/2967/url-based-navigation-into-a-jsf-application-on-phaselistener-and-viewhandler">variation on the manual url based parameter PhaseListener mechanism</a> which interprets the parameters and then directly renders the views.</p>
<p>My own <a href="http://projectnibble.org/dump/blog/friendlybookmarkablejsf/URLBasedGETParameterToBeanMapperPhaseListener.java">manual url based parameter PhaseListener</a> maps the parameters to bean properties in an automated fashion (although the bean names, parameters and properties are hardcoded in a static list at the top, which could&#8217;ve come from an xml file or something making this version completely generic -which incidently is exactly what PrettyFaces does-).</p>
<h3>Solving the GET url generation</h3>
<p>You can&#8217;t have GET urls for every state in the application, that would require massive GET urls filled with everything JSF needs to restore its state. What you need are specific cases where you want your users to be able to use a GET url, such as viewing a specific news item, company information, always things based on some identification. For these kind of GET urls, you can write a custom ViewHandler in JSF, which intercepts the view resolution and manually appends the GET parameters. For this to work, you first need to solve JSF&#8217;s Redirect problem, discussed in the next section (<i>The Redirect problem with JSF</i>).</p>
<p>Before I turned to PrettyFaces, I wrote my own ViewHandler (for Facelets), which also worked with value bindings in the view mappings in the faces config file. Dominik wrote a nice article on <a href="http://typo.ars-subtilior.com/articles/2007/01/24/how-to-make-jsf-navigation-rules-more-dynamic">dynamic JSF navigation</a>, which I adapted for this approach. In the faces-config.xml I defined the target urls with the parameters added and the values then being value bindings. A navigation case would look something like the following:</p>
<pre  name="code" class="xml">
    &lt;navigation-rule&gt;
    	&lt;from-view-id&gt;/pages/newsitems.xhtml&lt;/from-view-id&gt;
    	&lt;navigation-case&gt;
    		&lt;from-action&gt;#{newsitemController.doSelectNewsitem}&lt;/from-action&gt;
    		&lt;from-outcome&gt;ok&lt;/from-outcome&gt;
    		&lt;to-view-id&gt;/pages/newsitems.xhtml?newsitem=${newsitemController.currentNewsitem.id}&lt;/to-view-id&gt;
    		&lt;redirect /&gt;
    	&lt;/navigation-case&gt;
    &lt;/navigation-rule&gt;
</pre>
<p>The viewhandler I wrote then detected the question mark &#8216;?&#8217; in there and resolved all parameter values. I made sure the GET parameters were worked into the resulting url itself, which my PhaseListener from the previous section would be able to decipher. The result would look something like &#8216;/pages/newsitems/newsitem/4.xhtml&#8217;. This format then wouldn&#8217;t be lost when going through the servlet and its filters and the PhaseListener solution presented in the previous section would understand this format, extract the parameters and fix the url for further processing by JSF, as it originally would have.</p>
<ul>
<li><a href="http://projectnibble.org/dump/blog/friendlybookmarkablejsf/DynamicGETurlGeneratingViewHandler.java">Custom GET url generating Facelets ViewHandler with embedded parameters</a></li>
</ul>
<h2>2. The Redirect problem with JSF</h2>
<p>By default JSF runs one URL behind in the browser&#8217;s adresbar. Everytime you perform an action the JSF browser gets the URL from the <emphasize>previous view</emphasize>. This is because how JSF works with form submits: </p>
<ol>
<li>You click on a button which navigates to a different page</li>
<li>JSF submits a request to itself, the same page you were on</li>
<li>JSF handles the various phases and ultimately resolves to a view id, a new page URL</li>
<li>Since JSF submitted to the same page, for the browser it will return to the same URL, while JSF renders the HTML for the next URL. This is where JSF starts to run 1 URL behind</li>
<li>The new form in the page will submit to the for JSF-current URL, which is 1 URL ahead for the browser adresbar</li>
<li>When you now click on a button, JSF submits to the JSF-current URL, at which time the browser finally catches up. JSF however simply jumps ahead again and the whole thing repeats indefinately</li>
</ol>
<h3>The Redirect solution</h3>
<p>To get the browser to always reflect the current JSF-viewid-resolved-URL, the servlet needs to make the browser redirect to it. If you don&#8217;t, JSF will simply continue under the same URL the browser is in until the HTML form within the page submits to the next URL.</p>
<p>JSF actually contains something useful for this particular problem: redirects. You can add a <code><redirect /></code> entry in your navigation case to make the browser redirect to the resolved view URL. This pattern is known as the <emphasized>POST-REDIRECT-GET</emphasized> pattern. The small problem with this pattern however is that you&#8217;ll need to add it to each and every navigation case. The big problem is that you lose your request-scoped data between the POST submit and the GET browser redirect.</p>
<p>The solution to both is to register a JSF PhaseListener which intercepts any <emphasize>response-render action</emphasize>, invokes a browser GET redirect instead, but saves any state information to the session so it will still be there when the browsers gets back with the GET request on the new URL. One such implementation is the <a href="http://web.archive.org/web/20070514012122/http://learnjsf.com/wp/2006/08/06/a-prg-phase-listener-for-jsf/">PRG Phase Listener</a> (Here is another <a href="http://balusc.blogspot.com/2007/03/post-redirect-get-pattern.html">PRG implementation by BalusC</a>). As you can read in the comments though, there still is a shortcoming: it currently only stores the JSF messages data. Adding other data will require an arbitrary selection process since it is unclear what data will be in there to begin with (JSF internal state information stuff) and even less so what data should or shouldn&#8217;t be overwritten in the session. This selection process can be cumbersome; for example, what data will you need for a richfaces datatable to still work? Will that still work when it&#8217;s updated? I think you get the idea.</p>
<h2>How PrettyFaces solves everything at once</h2>
<p>So what PrettyFaces does is basically the culmination of the solutions I demonstrated (the GET url generation with dynamic navigation part), but polished as opposed to my own rough proof of concept. Indeed with an extra xml file making the approach generic and with a couple of other nifty features added. Telling you in one sentence what PrettyFaces does is like giving a summary of this entire post: </p>
<dl>
<dt><b>PrettyFaces</b></dt>
<dd><i>A framework for dealing with GET url in the POST based framework JSF. By returning a viewid like &#8220;pretty:home&#8221;, PrettyFaces will come into action and look up how the url should be formed using the &#8216;pretty config&#8217; xml file. It will solve any valuebindings and generate a GET url with a pattern it understand and when entering the url back into the browser, it will return the bean values from the url (sort of reverse valuebinding). So all the problems and their solutions we just discussed are solved by this small library (16k jar as of PF-1.0.0). It will redirect properly and only for the kind of queries we need GET urls for we define a pretty navigation case and return a &#8216;pretty:viewid&#8217; string to get PrettyFaces to use it.</i></dd>
</dl>
<p>In addition it offers some tags that, given a pretty maping-id, will generate the GET url for your hyperlinks. Furthermore, since version 1.2 pretty faces contains a mechanism to parse GET parameters using the traditional <i>?p1=v1&#038;p2=v2</i> format.</p>
<p>For completeness, here&#8217;s an overview of PrettyFaces&#8217; key classes:</p>
<dl>
<dt><b>PrettyContext</b></dt>
<dd><i>Loads your PrettyFaces context file and contains its settings and mappings.</i></dd>
<dt><b>PrettyFilter</b></dt>
<dd><i>Monitors incoming requests and checks if a requested URL as mapped in the PRettyFaces context. If so, it will request the context, resolve any parameter bindings (inject values into the beans), store any FacesMessage and forward the request to the configured viewid.</i></dd>
<dt><b>PrettyNavigationHandler</b></dt>
<dd><i>Handles navigation after JSF has processed a request. If a pretty-viewid was returned by the JSF action, the PrettyNavigationHandler will pick up on this, find the associated mapping from the pretty context, generate a GET url and redirect to it. In effect it determines which view to render and what appears in the brows addressbar.</i></dd>
<dt><b>PrettyViewHandler</b></dt>
<dd><i>Generates the requested action url from a request url and removes any trailing PrettyFaces directives from the url.</i></dd>
<dt><b>PrettyConfig</b></dt>
<dd><i>Holds the mapping and is returned inside a PrettyContext instance.</i></dd>
<dt><b>PrettyPhaseListener</b></dt>
<dd><i>Restores any FaceMessages stored between redirects, executes any actions defined in the mapping configuration for specific phases. This is after the beans have been injected with values from the GET url as per pretty-mapping. Finally leaves the request handling up to the PrettyNavigationHandler.</i></dd>
</dl>
<p><a href="http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/trackback/">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2009/03/20/bookmarkable-and-seo-friendly-jsf/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Parameterized JSF Facelets Validators</title>
		<link>http://blog.projectnibble.org/2008/07/26/parameterized-jsf-facelets-validators/</link>
		<comments>http://blog.projectnibble.org/2008/07/26/parameterized-jsf-facelets-validators/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 15:41:10 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[facelets validators]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[validators]]></category>

		<guid isPermaLink="false">http://blogs.quintor.nl/bbottema/2008/07/26/parameterized-jsf-facelets-validators/</guid>
		<description><![CDATA[You&#8217;d be surprised how hard it is to find good information about how you&#8217;re supposed to setup validators that you can parameterize with attributes in your tags; most about validators is very basic and very JSF-only. Or you won&#8217;t be surprised at all, because you searched until loss of sanity like me and found this [...]]]></description>
			<content:encoded><![CDATA[<p>You&#8217;d be surprised how hard it is to find good information about how you&#8217;re supposed to setup validators that you can parameterize with attributes in your tags; most about validators is very basic and very JSF-only. Or you won&#8217;t be surprised at all, because you searched until loss of sanity like me and found this blog. Whatever, here you can read what I found out.</p>
<p>So at first I made the error in not realizing validators under Facelets should be defined in their own facelets tag library. I hadn&#8217;t really worked myself into the the theory behind Facelets; I just picked it up as I went&#8230; as I do with most things, but there you have it. Turns out Facelets actually makes things very easy concerning validators, were it not for one sneaky little detail:</p>
<p>&#8220;<strong>parameterizable validators are stateful validators</strong>&#8221;</p>
<p>We&#8217;ll come back to it, but validators generally lose state after the page has been built by Facelets and you have to manually restore that state (including the previously set parameters), by implementing the <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/StateHolder.html">StateHolder</a> interface.</p>
<p>Oracle has a good article on <a href="http://www.oracle.com/webapps/online-help/jdeveloper/10.1.3?topic=sf_avc_customvalidators_html">StateHolder Validators</a>, though I only found it after I learned what to look for.</p>
<p>I resorted to a rather crude catch&#8217;em all solution, that tucks away the boilerplate code involved.</p>
<p><span id="more-11"></span></p>
<h2>Creating a parameterizable validator</h2>
<p>Having validators with configurable properties involves the following basic steps:</p>
<ul>
<li><em>1. create a JSF validator with the properties you wish to set in your tags</em></li>
<li><em>2. register the validator with your faces-config as you normally would in JSF</em></li>
<li><em>3. create a Facelets taglibrary file and register it with your application</em></li>
<li><em>4. add an entry to this tablib file that defines a validator and points to the faces-config one</em></li>
<li><em>5. that&#8217;s it, no properties need to be explicitly defined, Facelets will take care of that</em></li>
</ul>
<p>We&#8217;ll add one more step to it to make the validators actually work:</p>
<ul>
<li><em>1.5. modify the validator with a StateHolder solution</em></li>
</ul>
<h2>1. Create a JSF Validator</h2>
<p>So for this example I&#8217;m going to take a simplified version of the age validator I made earlier in <a href="http://blog.projectnibble.org/2008/07/13/streamline-your-jsf-validation-framework/">Streamline your JSF validation framework</a>.</p>
<p><a href="http://projectnibble.org/dump/blog/parameterizedvalidators/java/nl/quintor/commons/validator/AgeValidator.java">AgeValidator.java</a></p>
<p>So this validator already has some properties for min and max age we can use. In the previously post article they didn&#8217;t work properly though, we&#8217;ll fix that today.</p>
<h2>2. Register the validator with JSF in faces-config</h2>
<p>So before we can use the validator in Facelets, JSF needs to recognize it. Here&#8217;s the piece of xml that does that in faces-config.xml:</p>
<pre><code class="prettyprint">&lt;validator&gt;
	&lt;validator-id&gt;quintor.validator.AgeValidator&lt;/validator-id&gt;
	&lt;validator-class&gt;nl.quintor.commons.validator.AgeValidator&lt;/validator-class&gt;
&lt;/validator&gt;
</code></pre>
<p>So you may have noticed I didn&#8217;t really use a normal validator id. That&#8217;s because I don&#8217;t want to confuse them with normal validators for use in JSF only and to illustrate their significance in wiring them to Facelets. Instead I&#8217;m using a sort of grouping id by using a shortened version of their full package (for converters it would be <i>quintor.converter.SomeConverter</i>).</p>
<h2>3. Create a Facelets tag library file and register it with the application</h2>
<p>To be able to use the validators in Facelets, and thereby making use of Facelets parameterizing capabilities, we need to use yet another xml file that Facelets needs.</p>
<p>Create a file in the META-INF webapp folder; I&#8217;ll call mine &#8216;quintor-validators.taglib.xml&#8217;. I picked that up from another project that used this convention. Next the taglib file needs to be registered with the web.xml:</p>
<pre><code class="prettyprint">&lt;context-param&gt;
 	&lt;param-name&gt;facelets.LIBRARIES&lt;/param-name&gt;
	&lt;param-value&gt;
		/WEB-INF/quintor-validators.taglib.xml
	&lt;/param-value&gt;
&lt;/context-param&gt;
</code></pre>
<h2>4. Add entry that uses the faces-config validator</h2>
<p>Here&#8217;s the validator definition inside quintor-validators.taglib.xml:</p>
<pre><code class="prettyprint">&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "facelet-taglib_1_0.dtd"&gt;
&lt;facelet-taglib&gt;
	&lt;namespace&gt;http://www.quintor.nl/jsf/validator&lt;/namespace&gt;
	&lt;tag&gt;
		&lt;tag-name&gt;validateAge&lt;/tag-name&gt;
		&lt;validator&gt;
			&lt;validator-id&gt;quintor.validator.AgeValidator&lt;/validator-id&gt;
		&lt;/validator&gt;
	&lt;/tag&gt;
&lt;/facelet-taglib&gt;
</code></pre>
<h2>1.5. Finally let&#8217;s focus on the &#8216;state problem&#8217;</h2>
<p>Currently, the age validator is ready to go, if it weren&#8217;t for the fact it forgets any value set in the tag. For instance, take the following tag example:</p>
<pre><code class="prettyprint">&lt;html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:qnt-validator="http://www.quintor.nl/jsf/validator"&gt;

&lt;ui:composition&gt;
	&lt;ui:define name="body"&gt;

	&lt;h:inputText&gt;
		&lt;qnt-validator:validateAge min="18"/&gt;
		&lt;ui:insert/&gt;
	&lt;/h:inputText&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
&lt;/html&gt;
</code></pre>
<p>Here the minimum age of 18 is set for validation. If we were to debug the validator, we&#8217;d notice the setter is being called when the page is being build up. If we then submit the form, the validator is recreated, but the setter is not being called again thus the validator reverts to its default values!</p>
<p>How then, can we keep the values set by the attributes? The answer lies in the StateHolder interface that comes with JSF, or rather why you <em>need</em> StateHolder. The problem lies in the fact that JSF keeps everything page scoped by default and stores all components in the Response object (which would explain why the setter is being called during page-build). Through the use of the StateHolder interface, JSF is able to carry a component&#8217;s state across requests and responses.</p>
<p>An alternative to StateHolder would be to make the validator <em>serializable</em>, as the MyFaces wiki reveals on <a href="http://wiki.apache.org/myfaces/How_JSF_State_Management_Works">JSF State Management</a>, but that&#8217;s a rather implicit solution. I&#8217;d prefer the explicit version by implementing StateHolder. Instead of having each and every validator implement StateHolder, I chose for a more &#8216;catch all&#8217; solution. This solution involves an abstract base class that stores the complete state of a given component (validator or converter) and restores this.</p>
<p>Here&#8217;s the class and GenericUtils which harbors some boilerplate code:</p>
<p><a href="http://projectnibble.org/dump/blog/parameterizedvalidators/java/nl/quintor/commons/util/AbstractStateholder.java">AbstractStateholder.java</a><br />
<a href="http://projectnibble.org/dump/blog/parameterizedvalidators/java/nl/quintor/commons/util/GenericUtils.java">GenericUtils.java</a></p>
<p>So what happens is that we just ignore transient and let JSF deal with that. But when saving/restoring state we just crudely take Apache&#8217;s BeanUtils and create a clone of the current validator instance and take over all of its properties, which will now need <em>getter</em> methods as well. The copied state is limited by what properties on the validator has getters/setters defined for them. When JSF is asking the validator to restore its previously stored state, we just slam the cloned validator&#8217;s properties on the current one.</p>
<p>Here&#8217;s the modified AgeValidator now: <a href="http://projectnibble.org/dump/blog/parameterizedvalidators/java/nl/quintor/commons/validator/AgeValidator2.java">AgeValidator.java modified</a></p>
<p>The new version only has some getter methods added so that the abstract stateholder class can retrieve the values for state-saving. Now, the validators are being parameterized by Facelets (common conversions done automagically) and the attributes on the tags are being remembered on the validator to the point of actual validation.</p>
<p>Nice, huh.</p>
<p><a href="http://blog.projectnibble.org/bbottema/2008/07/26/parameterized-jsf-facelets-validators/trackback/">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2008/07/26/parameterized-jsf-facelets-validators/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Streamline your JSF validation framework</title>
		<link>http://blog.projectnibble.org/2008/07/13/streamline-your-jsf-validation-framework/</link>
		<comments>http://blog.projectnibble.org/2008/07/13/streamline-your-jsf-validation-framework/#comments</comments>
		<pubDate>Sun, 13 Jul 2008 17:40:43 +0000</pubDate>
		<dc:creator>Benny Bottema</dc:creator>
				<category><![CDATA[JSF/Facelets]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[faces-config]]></category>
		<category><![CDATA[input validation]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://blogs.quintor.nl/bbottema/2008/07/13/streamline-your-jsf-validation-framework/</guid>
		<description><![CDATA[I was working a JSF project which, as all JSF projects do, needed a bunch of validators. It was getting a little bit messy having a lot of boilerplate code and validation algorithms that couldn&#8217;t be reused. So I decided to streamline the code and usage of validators in JSF in general, in combination with [...]]]></description>
			<content:encoded><![CDATA[<p>I was working a JSF project which, as all JSF projects do, needed a bunch of validators. It was getting a little bit messy having a lot of boilerplate code and validation algorithms that couldn&#8217;t be reused. So I decided to streamline the code and usage of validators in JSF in general, in combination with dealing with validation messages optionally using resource bundles.</p>
<p>The solution I&#8217;m suggesting isn&#8217;t rocket science, but it serves its purpose in keeping everything maintainable, understandable and easy to work with.</p>
<p>Let me know what you think.</p>
<p>[ <a href="http://projectnibble.org/dump/blog/validationframework/validation-framework.zip">Download all sources</a> ]</p>
<p><span id="more-10"></span></p>
<h2>The general idea</h2>
<p>So here&#8217;s the general layout of what I had in mind:</p>
<ol>
<li>Group all validation logic in methods in an independent utility class</li>
<li>Have an abstract validation class, which takes care of some logging and validation errors.</li>
<li>Add subclasses of this abstract validation class that merely invokes the validation logic on a separate utility class</li>
</ol>
<p>The methods should be kept in a separate utility class, so that these validations can be used anywhere in the application and furthermore: outside JSF applications. Also, since all validations are now organized in one central location, we can deal with validation messages uniformly across all validation methods, within the utility class. We&#8217;ll see about that later.</p>
<h2>Setting up the Validation utility class</h2>
<p>What I&#8217;m going to do is define constants with error codes, that should be able to be mapped directly to message id&#8217;s in message resourcebundles. Realizing not all projects nescesarily use these bundles, we&#8217;re going to create default messages as well. These default messages are there to be used by the various validators, but don&#8217;t <em>have</em> to be used at all.</p>
<pre><code class="prettyprint">public static final String VALIDATIONERROR_BIRTHDATE_TOOYOUNG = "validationerror.birthdate.tooyoung";
static final Map defaultMessages;
static {
	// set default error messages
	defaultMessages = new HashMap();
	defaultMessages.put(VALIDATIONERROR_BIRTHDATE_TOOYOUNG, "Minimum %s years of age allowed");
}
</code></pre>
<p>I split up the validator utils into two classes. A ValidatorMessages class which contains all the constants with the error codes and default messages. And then ofcourse ValidatorUtils, which contains all validation algorithms, because I wanted to avoid having a validation <a href="http://c2.com/cgi/wiki?GodClass">God Class</a>. I&#8217;ve thought of making the ValidatorMessages an interface, but I couldn&#8217;t semantically justify that.</p>
<p><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/ValidatorMessages.java">ValidatorMessages.java</a><br />
<a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/ValidatorUtils.java">ValidatorUtils.java</a></p>
<p>These classes use some utility functions from GenericUtils (such as the regexp helper method).</p>
<p><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/GenericUtils.java">GenericUtils.java</a></p>
<h2>Setting up the abstract validator class</h2>
<p>The abstract validator class is really the engine behind the new validation framework. It should do some logging, some more logging in case of invalidation, getting the correct message from either the list of default messages or the message resourcebundle (if available) and then it should throw a JSF validation exception.</p>
<p><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/validator/AbstractValidator.java">AbstractValidator.java</a></p>
<p>The abstract validator uses a method from yet another utility class, specific to JSF applications: JSFUtils</em>. What it does is try to return a message from the default application resource bundle, and if unavailable (either the bundle or the specific message) it will return the given backup message.</p>
<p><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/JSFUtils.java">JSFUtils.java</a></p>
<p>So the first thing you&#8217;ll notice is that the abstract validator needs to be instantiated with a default field name. This is so that if you omit the corresponding attribute in the validator tag in your JSF page, there will be a default name in the error message to the end-user.</p>
<p>Furthermore, the abstract validator uses a utility method to get a message from the default application resource bundle, but returns a backup message if the resource bundle or message within is unavailable. Since the way the resource bundle is being fetched depends on a <em>FacesContext</em>, the utility is called JSFUtils and is specific to JSF applications, just as the JSF Validator shells are.</p>
<h2>Setting up the validators</h2>
<p>The actual validators being registered with JSF are now very easy to set up. In fact, they now function merely as glue between the AbstractValidator and the ValidatorUtils, while providing entry points for the JSF validation framework.</p>
<p>Here are two example validator classes:</p>
<p><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/validator/PostalcodeValidator.java">PostalcodeValidator.java</a><br />
<a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/validator/AgeValidator.java">AgeValidator.java</a></p>
<p>As you can see the subclasses are extremely lightweight and only contain some boilerplate code to optionally customize the error messages specific to that validator class and even then the error messages themselves are kept in message bundles or ValidatorMessages and handled by the AbstractValidator class.</p>
<p>To configure JSF with the concrete validators:</p>
<pre><code class="prettyprint">&lt;faces-config&gt;

	...

	&lt;validator&gt;
		&lt;validator-id&gt;validatePostalcode&lt;/validator-id&gt;
		&lt;validator-class&gt;nl.quintor.commons.validator.PostalcodeValidator&lt;/validator-class&gt;
		&lt;property&gt;
			&lt;property-name&gt;fieldName&lt;/property-name&gt;
			&lt;property-class&gt;java.lang.String&lt;/property-class&gt;
		&lt;/property&gt;
	&lt;/validator&gt;
	&lt;validator&gt;
		&lt;validator-id&gt;validateAge&lt;/validator-id&gt;
		&lt;validator-class&gt;nl.quintor.commons.validator.AgeValidator&lt;/validator-class&gt;
		&lt;property&gt;
			&lt;property-name&gt;fieldName&lt;/property-name&gt;
			&lt;property-class&gt;java.lang.String&lt;/property-class&gt;
		&lt;/property&gt;
		&lt;property&gt;
			&lt;property-name&gt;min&lt;/property-name&gt;
			&lt;property-class&gt;java.lang.Integer&lt;/property-class&gt;
		&lt;/property&gt;
		&lt;property&gt;
			&lt;property-name&gt;max&lt;/property-name&gt;
			&lt;property-class&gt;java.lang.Integer&lt;/property-class&gt;
		&lt;/property&gt;
	&lt;/validator&gt;
&lt;/faces-config&gt;
</code></pre>
<p>And to actually use the validator in some page:</p>
<pre><code class="prettyprint">&lt;!-- Put an age validator on the birthdate input field
fieldname 'age' will be used in the error messages too old/young --&gt;
&lt;h:inputText id="birthdate" required="true" maxlength="10" value="#{personBean.birthdate}"&gt;
	&lt;f:converter converterId="CalendarConverter" /&gt;
	&lt;f:validator validatorId="validateAge" fieldName="Age" /&gt;
&lt;/h:inputText&gt;
</code></pre>
<h2>Roundup</h2>
<p>In retrospect, here&#8217;s a short impression of the packages now in use:</p>
<p><img src="http://projectnibble.org/dump/blog/validationframework/validator1.png" alt="the packages so far" /></p>
<p>Let&#8217;s summarize how the logic is spread out among the classes:</p>
<ul>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/GenericUtils.java">GenericUtils</a></strong>: contains some generic functionality neutral to all applications, such as regexp methods</li>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/JSFUtils.java">JSFUtils</a></strong>: contains generic functionality specific to JSF applications, such as getting messages from a FacesContext resourcebundle</li>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/ValidatorUtils.java">ValidatorUtils</a></strong>: contains the validation methods, neutral to all applications, such as validateAge</li>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/util/ValidatorMessages.java">ValidatorMessages</a></strong>: encapsulates the error codes and their default messages that can be returned by validation methods in ValidatorUtils</li>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/validator/AbstractValidator.java">AbstractValidator</a></strong>: contains logic used for all validators, such as logging, determining validation message, throwing JSF validation exceptions</li>
<li><strong><a href="http://projectnibble.org/dump/blog/validationframework/java/nl/quintor/commons/validator/AgeValidator.java">ConcreteValidator.java</a></strong>: contains the default field name for end-user feedback purposes and calls the correct validation method in ValidatorUtils and returns its result to the AbstractValidator validation method (and optionally customizes the message)</li>
<li><strong>faces-config.xml</strong>: contains registration for concrete validators including properties that can be set (ie. limits for the age validator)</li>
<li><strong>some-page.jsp/xhtml</strong>: contains the input fields and nested validator tags, optionally with attributes to customize it</li>
</ul>
<p><img src="http://projectnibble.org/dump/blog/validationframework/validator2.png" alt="the packages so far" /></p>
<p>So to actually add a new validator, you can follow the next steps:</p>
<ol>
<li>Add the validation codes and default messages you&#8217;ll need to ValidatorMessages</li>
<li>Add a method to the ValidatorUtils that performs the validation and returns one of these messages</li>
<li>Create a subclass of AbstractValidator, call the super constructor with a default fieldname and implement the validation method, calling the corresponding validation method in ValidatorUtils</li>
<li>Register the validator with your faces config file</li>
</ol>
<h2>Benefits of this approach</h2>
<p>The benefit is ofcourse that everything is being managed separately and can be reused; you can reuse the validation method anywhere across your projects and what&#8217;s more: you can use the same validation methods in non-JSF applications. Also with this approach you can easily junit test the validation methods. When adding new validators, you add very little code but highly concise and cohesive code.</p>
<p>In this approach the Validator class acts as a shell around the actual validation logic and can therefor be very lightweight. Now you can add validators with the least amount of code possible while maintaining maximum flexibility.</p>
<h2>Conclusion</h2>
<p>So, coming to the conclusion, I hope you can use this stuff. I know it works beautiful for me, but If you have suggestions, as I have no doubt someone can do this all even better, let me know!</p>
<p><img src="http://images.slashdot.org/favicon.ico" alt="Slashdot" border="0" height="16" width="16" /> <a href="http://slashdot.org/slashdot-it.pl?op=basic&amp;url=http://blogs.quintor.nl/bbottema/2008/07/13/streamline-your-jsf-validation-framework/">Slashdot It!</a>   /   <a href="http://blogs.quintor.nl/bbottema/2008/07/13/streamline-your-jsf-validation-framework/trackback/">trackback</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.projectnibble.org/2008/07/13/streamline-your-jsf-validation-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
