<?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>Andy Gibson &#187; JSF</title>
	<atom:link href="http://www.andygibson.net/blog/tag/jsf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Thu, 02 Feb 2012 14:33:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language></language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Announcing CDISource</title>
		<link>http://www.andygibson.net/blog/article/announcing-cdisource/</link>
		<comments>http://www.andygibson.net/blog/article/announcing-cdisource/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 13:38:01 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[CDISource]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1787</guid>
		<description><![CDATA[In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is [...]]]></description>
			<content:encoded><![CDATA[<p>In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is for intertwining various historical and literary references in his posts. The result of this is the <a href="https://sites.google.com/site/cdipojo/get-started">CDISource</a> project which aims to advocate and facilitate the use of the JSR 299 &#8211; Java Contexts and Dependency Injection framework across the Java landscape.</p>
<p>If you&#8217;ve seen my posts or my site before, you&#8217;ll no doubt be aware that I have written at great length about Java EE 6, JSF, CDI , EJB and so on. What I haven&#8217;t written about is the many frustrations I&#8217;ve come up against in dealing with these frameworks on their own and especially when combined, or how their usefulness is often constrained to the application server container. </p>
<p>Java EE in some ways is an archipelago of frameworks that lacks the cohesiveness and all in one wide screen vision that software developers need. Java EE is about the enterprise, in reality its about the web, or even more specifically about Java EE containers. There&#8217;s a whole slew of uses for a good type safe and flexible dependency injection and AOP framework and such as CDI outside of Java EE containers but there is very little information and code to make it actually work.  </p>
<p>Our goal is to make CDI useful and usable on its own without Java EE 6, and to give developers the tools and information to do so. To let them write vendor neutral and portable code, and apply agile and best practices. Developers know how to write good software and don&#8217;t want to sacrifice that for the sake of using a framework to make things easier. To that end we aim to provide code and information that will help facilitate those practices. </p>
<p>There will be some learning for ourselves along the way and we will have to change some of our previously held concepts. I know over the last few weeks having been  getting CDI working and useful outside of the web container it has really altered my perspective on how I think about the dependencies and structure in CDI applications. My perspective has changed even more than when I wrote <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>. </p>
<p>As much as I hate to say it, we did come up with a mission statement, although we found it fairly easy and enjoyable to clearly defined the goals and attitudes of the project. </p>
<p>Our mission is to :</p>
<ul>
<li>Promote and facilitate the use of the Java Context and Dependency Injection (CDI) framework in relation to as many aspects of application development as possible.</li>
<li>Enable developers to take advantage of CDI independently of Java EE.</li>
<li>Provide lightweight, lean and agile access to the underlying CDI container as a core principle in our efforts.</li>
<li>Make testing easy without requiring a complex set of tools or complex deployment scenarios.</li>
<li>Enhance both Java EE development as well as the use of CDI in non Java EE application where possible.</li>
<li>Promote and enable the use of CDI in a vendor neutral environment and maximize the portability of application code across CDI implementations.</li>
<li>Not reject the ideas of Java EE but expand the usability of CDI outside the borders of Java EE application servers with frameworks that are not a part of the specification.</li>
<li>Not reject other CDI efforts but to provide another venue to promote those efforts. This is an addition. This is another voice in support of CDI.</li>
</ul>
<p>We are pretty excited that so far we have been able to live up to the intent of our mission statement with everything we&#8217;ve done so far. Over the next few days and weeks you will see articles and tutorials come out of Rick, Rob and I as we write about the CDISource project and we start to showcase some of the code we have written and start giving you an idea of where we are heading.  </p>
<p>Right now we have vendor neutral support for starting up CDI outside of the web container and also for testing CDI beans with minimal configuration and intrusion on your test cases. We also have a few other pieces that are nearly ready, as well as dozens of ideas to get started on.</p>
<p>You can start by looking at Ricks brand new <a href="http://java.dzone.com/articles/cdi-di-p1">introduction of CDI</a> over on JavaLobby.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/announcing-cdisource/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Double the speed of (some of) your JSF pages (and dodge bugs too)</title>
		<link>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/</link>
		<comments>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 12:49:39 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1771</guid>
		<description><![CDATA[There was a thread on the JSF LinkedIn group about JSF performance and a number of people complained about the fact that as part of the restore view phase, JSF reconstructs the component tree including binding data to data tables causing unnecessary fetches of data from the database. This article looks at one way of [...]]]></description>
			<content:encoded><![CDATA[<p>There was a thread on the JSF LinkedIn group about JSF performance and a number of people complained about the fact that as part of the restore view phase, JSF reconstructs the component tree including binding data to data tables causing unnecessary fetches of data from the database. This article looks at one way of avoiding the additional work to fetch the data.<br />
<span id="more-1771"></span><br />
When you first do a postback, the restore view phase rebuilds the tree, including fetching the data to bind it to the data table. Why you ask, well a good question. Typically this wouldn&#8217;t be an issue since we want the server state to match the client view state. However, as the developer, we know that for some cases these results are useless since we don&#8217;t anticipate using them for anything so fetching them is really a waste of time. </p>
<p>Let&#8217;s take a look at this problem in action. You can use the maven archetype to generate the project and code along or download the source from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/fastapp.zip'>fastapp.zip</a>).</p>
<ol>
<li>Create a new maven application using the jee6-servlet-basic knappsack archetype. This gives you an empty Java EE 6 application that can be run using Jetty or Tomcat from the command line.</li>
<li>Add a new class that will be our backing bean that returns a list of paginated numbers but takes a long time (2 seconds) to do it.
<pre class="brush: java;">
@Named
@RequestScoped
public class DataBean {

	//indicates the page we are on
	private int pageNumber = 0;	

	//lazy loaded reference to the results
	private List&lt;Integer&gt; data;

	//returns the list of data by lazy loading it
	public List&lt;Integer&gt; getData() {
		if (data == null) {
			data = generateData();
		}
		return data;
	}

	//generates the list of data, think of this as an expensive DB operation
	private List&lt;Integer&gt; generateData()  {
		System.out.println(&quot;Generating Data starting from &quot;+pageNumber);

		//Sleep for 2 seconds while I access the database and do stuff
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		//now we actually generate the data
		List&lt;Integer&gt; results = new ArrayList&lt;Integer&gt;();
		for (int i = 0;i &lt; 10;i++) {
			results.add(pageNumber+i);
		}
		return results;

	}

	//method to move to the next page in the list
	public void nextPage() {
		pageNumber = pageNumber+10;
		//invalidate the lazy loaded data
		data = null;
	}

	//method to move to the previous page in the list
	public void previousPage() {
		pageNumber = pageNumber-10;
		//invalidate the lazy loaded data
		data = null;
	}

	//getter/setter for page number
	public int getPageNumber() {
		return pageNumber;
	}
	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}
}
</pre>
<p>We lazy load the results so for each request, we start with nothing and then load the results when the restore view phase looks for them. In the render response phase, the same results are used unless the next/previous page methods are called and the data value is set to null and invalidated. In this case when the data is requested in the render response phase, we see it is null and so it will be loaded fresh for the new page number.
</li>
<li>Now we modify the existing home.xhtml page to show a table and add two buttons to move to the previous and next pages.
<pre class="brush: xml;">
&lt;ui:define name=&quot;content&quot;&gt;

	&lt;h:dataTable value=&quot;#{dataBean.data}&quot; var=&quot;v_value&quot;&gt;
		&lt;h:column&gt;
			&lt;f:facet name=&quot;header&quot;&gt;Value&lt;/f:facet&gt;
			#{v_value}
		&lt;/h:column&gt;
	&lt;/h:dataTable&gt;
	&lt;h:form&gt;
		&lt;h:commandButton action=&quot;#{dataBean.previousPage}&quot; value=&quot;Previous&quot; /&gt;
		Page #{dataBean.pageNumber}
		&lt;h:commandButton action=&quot;#{dataBean.nextPage}&quot; value=&quot;Next&quot; /&gt;
		&lt;h:inputHidden value=&quot;#{dataBean.pageNumber}&quot; /&gt;
	&lt;/h:form&gt;
&lt;/ui:define&gt;
</pre>
<p>Fairly straightforward, we just show the list of numbers and have buttons for navigating. We store the page number in a hidden field and post it back to our backing bean so we have a stateless setup. I also added a phase listener that I&#8217;ve used before to log the timing of the JSF requests that is documented in this post (<a href="http://www.andygibson.net/blog/tutorial/timing-jsf-requests-using-a-phase-listener/">Timing JSF Requests using a Phase Listener</a>). Since this was for Seam originally I modified it by removing the logger code and just pushing the log text to <code>System.out</code>. You can turn it on and off by removing it from the <code>faces-config.xml</code> file in the <code>lifecycle</code> section.
</li>
<li>In a command console enter <code>mvn clean jetty:run</code> to start the server and go to the home page at <a href="http://localhost:8080/fastapp/home.jsf">http://localhost:8080/fastapp/home.jsf</a>.
</li>
</ol>
<p>When you first go to the page, you trigger a GET request which will cause the data to be loaded one time and displayed. In our output log we see :</p>
<pre class="brush: plain;">
Generating Data starting from 0
</pre>
<p>Fantastic. At this point, we know the page took 2 seconds to render. If we click the next or previous buttons, we cause a postback which will restore the view (including rebuilding the data) and then change the page number which will invalidate the data before again rebuilding the data for the new page. We see this in the log as  :</p>
<pre class="brush: plain;">
Generating Data starting from 0
Generating Data starting from 10
</pre>
<p>If you are using the phase listener to time it, you will see the two requests as :</p>
<pre class="brush: plain;">
//first request initiated
Executed Phase RESTORE_VIEW 1
Generating Data starting from 0
Execution Time = 2228ms
Executed Phase RENDER_RESPONSE 6

//click next page to trigger the postback and response
Generating Data starting from 0
Executed Phase RESTORE_VIEW 1
Executed Phase APPLY_REQUEST_VALUES 2
Executed Phase PROCESS_VALIDATIONS 3
Executed Phase UPDATE_MODEL_VALUES 4
Executed Phase INVOKE_APPLICATION 5
Generating Data starting from 10
Execution Time = 4116ms
Executed Phase RENDER_RESPONSE 6
</pre>
<p>You can see the first request took 2 seconds while the second request took over 4 seconds. The problem here is that the data is being fetched twice, once for the restore view and again for the rendering of the response with the new data as you can see in the phase listener log entries.</p>
<h1>Solution</h1>
<p>The solution to the problem is to skip fetching the data the first time altogether. It isn&#8217;t needed, it isn&#8217;t even used and it isn&#8217;t even the correct data (don&#8217;t worry, I&#8217;ll explain that later). In the <code>FacesContext</code> object there is a method called <code>getRenderResponse()</code> which returns true if the render response method has been called and we are in the rendering phase. Until we are rendering the page, we don&#8217;t really need our data so we only load it if this method returns true.</p>
<pre class="brush: java;">
	//generates the list of data, think of this as an expensive DB operation
	private List&lt;Integer&gt; generateData()  {
		if (!FacesContext.getCurrentInstance().getRenderResponse()) {
			return null;
		}
		System.out.println(&quot;Generating Data starting from &quot;+pageNumber);
		...
		...
		...
	}
</pre>
<p>It&#8217;s that simple, now redeploy the application load the page and click next, this time, we only get one data fetch per page request even on postbacks because we don&#8217;t bother loading the data until we really need it in the render response and if you look at the timing, our pages are loading twice as fast since we only fetch half the data.</p>
<pre class="brush: plain;">
//initial request
Executed Phase RESTORE_VIEW 1
Generating Data starting from 0
Execution Time = 2278ms
Executed Phase RENDER_RESPONSE 6

//click the next button to trigger a postback - look, no data loaded until the response is rendered
Executed Phase RESTORE_VIEW 1
Executed Phase APPLY_REQUEST_VALUES 2
Executed Phase PROCESS_VALIDATIONS 3
Executed Phase UPDATE_MODEL_VALUES 4
Executed Phase INVOKE_APPLICATION 5
Generating Data starting from 10
Execution Time = 2302ms
Executed Phase RENDER_RESPONSE 6
</pre>
<p>So there you go, you can increase the speed of your JSF pages by only loading data when you really need it, I guess kind of lazy lazy loading data.</p>
<h1>What about that bug we are dodging?</h1>
<p>Ah yes, that thing, not sure if it can be called a bug but to see the problem, remove the code to check for the render response so we do the double data request on postbacks. Now load up the application and click the next button twice, and you should see the following log :</p>
<pre class="brush: plain;">
//initial GET request, we only load the data once
Generating Data starting from 0

//Click next, trigger a postback with two data fetches
Generating Data starting from 0
Generating Data starting from 10

//Click next again, trigger a postback with two more fetches.
Generating Data starting from 0 --err, this isn't right it should be 10
Generating Data starting from 20
</pre>
<p>When we do the second postback, the first set of data fetched is starting from position 0. We are loading our data using the default <code>pageNumber</code> value of 0. So not only are we loading data we don&#8217;t need, we are loading the wrong data. This could have consequences if say you are in a search page and the postback triggers an unconstrained search which may take longer than one with search parameters set.</p>
<p>The reason for this is that the restore view process takes place before the request values are applied so the <code>pageNumber</code> is set to the default value of zero which makes the fetching of the data even more useless. I&#8217;m not sure it can be called a bug since the value hasn&#8217;t been set at the restore view phase The question is whether it is correct for the restore view phase to fetch data based on values that haven&#8217;t yet been initialized and if so, what&#8217;s the point?</p>
<h2>A Feature?</h2>
<p>You know, thinking about it, this might really be a feature, not a bug. It&#8217;s feasible to utilize the state of the <code>pageNumber</code> value to determine whether we can return the results if we change its type to <code>Integer</code>. We know that we don&#8217;t need to fetch the data if the page number is <code>null</code> because we haven&#8217;t hit the read request values stage so we must still be in the restore view stage and therefore don&#8217;t need any data.<br />
The only problem comes with the initial setting of the value when you first enter the page, what sets it from null to zero initially. You&#8217;d have to fudge around with the getters and settings, plus it would be hard to display that initial page of results since it would always be empty.</p>
<p>The source code for this project is available from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/fastapp.zip'>fastapp.zip</a>). To run, simply unzip, and in the console, type <code>mvn clean jetty:run</code> or <code>mvn clean tomcat:run</code> and go to <a href="http://localhost:8080/fastapp/home.jsf">http://localhost:8080/fastapp/home.jsf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A Little Less Conversation&#8230;</title>
		<link>http://www.andygibson.net/blog/article/a-little-less-conversation/</link>
		<comments>http://www.andygibson.net/blog/article/a-little-less-conversation/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 13:11:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1718</guid>
		<description><![CDATA[One thing that I wrote that I haven&#8217;t really gotten around to examining and verifying in closer detail and validating my position on is the production of the conversational entity manager in the Knappsack archetypes. This article looks at this and re-evaluates my thinking on the use of conversational contexts in CDI. Defaulting to Request [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that I wrote that I haven&#8217;t really gotten around to examining and verifying in closer detail and validating my position on is the production of the conversational entity manager in the Knappsack archetypes.  This article looks at this and re-evaluates my thinking on the use of conversational contexts in CDI.<br />
<span id="more-1718"></span><br />
<H1>Defaulting to Request Scoped</h1>
<p>It&#8217;s one of those things that you write and it works, but something feels wrong with it, and I haven&#8217;t had time to go back and look at it. The entity manager is scoped to the conversation so that it will work with as both conversational and request scoped. When an object is scoped to the conversation and there is no long running conversation then the conversation itself is limited to the request so your data, although conversation scoped becomes request scoped. This was a handy way to default data that was mostly request scoped to a request scope while giving it the ability to partake in active conversations.  In Seam, this was fairly standard practice since it allowed your model to live in a conversational entity manager without having to worry about detachment issues. However, CDI conversations are different from Seam conversations and their use needs to be a little more focused.</p>
<p>The problem is that CDI is supported in a number of environments within Java EE 6  while the conversation scope is not. To name a few, servlets and web services don&#8217;t have default support for conversations and Arquillian tests doesn&#8217;t handle conversations well. While we may be able to work around non-conversational servlets, web services and arquillian tests, the problem really goes deeper.</p>
<p>Logically we are thinking about using these beans as request scoped beans because there is no long running conversation. However, the conversational context still needs to be initialized and available to hold these beans. CDI doesn&#8217;t magically know to put the conversational beans in the request scope context when there&#8217;s no long running conversation, it always puts it in the conversational context.</p>
<p>So, the answer you say is to use request scoped beans and relegate a conversational scope to those cases where you really do need a conversational scope, and not use it everywhere you want request scoped but might need a conversation scoped bean. While this is true, our request scoped beans depend on business logic beans that in turn use the data layer beans that uses our entity manager to access the database. The problem is that the entity manager is conversation scoped so all our beans that depend on it are broken. </p>
<p>The end result is that using some of the tools and API&#8217;s with CDI has been rather frustrating since nearly every bean depends on the entity manager at the end of the day and without conversation support it typically breaks with an obscure error message.</p>
<p>The solution is to treat our entity manager like our beans, we only use conversations where absolutely necessary. The question you may be asking yourselves is how to deal with code that is both request and conversation scoped. For example, you load an entity at the start of a wizard into a conversation scoped bean using a conversation scoped entity manager because you want to keep this bean attached for the duration of the conversation. At the end of the conversation, you might want to use the standard request scoped entity Dao to save the entity. Will the request scoped Dao will use a different entity manager from the conversation scoped bean or not? The good news is that we can re-use the same entity manager sourced from the same place and offered up as a request scoped entity manager to get around this so they will use the same entity manager.</p>
<p>Additionally, the introduction of some of the new JSF 2.0 scopes helps out since we can use the flash or view scopes to pass objects from one page to the next or to maintain state between requests. The only problem here is that these scopes are in JSF and not compatible with CDI, or implemented in CDI by default. The Seam 3 faces module provides CDI compatible alternatives and I would put good money on those scopes making it into the next version of CDI.</p>
<h1>Lesson Learned</h1>
<p>One take away from this is to always make sure everything will play nice together before committing to a particular strategy or design. It would have been a shame to implement our data access layer and find out that we couldn&#8217;t use it in our web services or testing. </p>
<p>I&#8217;ll be trying to spend a little time working all this out and seeing what the best strategies are, but hopefully this will remove some of the barriers to demonstrating and adding third party integrations into the Knappsack archetypes. This will probably get changed for the next version of the Knappsack archetypes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/a-little-less-conversation/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Need a Java developer in Pittsburgh?</title>
		<link>http://www.andygibson.net/blog/personal/need-a-java-developer-in-pittsburgh-pa/</link>
		<comments>http://www.andygibson.net/blog/personal/need-a-java-developer-in-pittsburgh-pa/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 13:50:45 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1715</guid>
		<description><![CDATA[If anyone is looking for a good experienced Java, JSF developer in Pittsburgh PA, get in touch. I can be reached through my contact form which goes straight to my email.]]></description>
			<content:encoded><![CDATA[<p>If anyone is looking for a good experienced Java, JSF developer in Pittsburgh PA, get in touch. I can be reached through my <a href="http://www.andygibson.net/blog/contact-me/">contact form</a> which goes straight to my email.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/personal/need-a-java-developer-in-pittsburgh-pa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling missing resources with CDI Events</title>
		<link>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/</link>
		<comments>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 14:18:04 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Master]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1604</guid>
		<description><![CDATA[In part 1, we created a simple application that made use of string resource bundles in JSF and in part 2 we extended it by using CDI to inject the resource provider into beans so we can re-use our code for accessing locale specific string based resources. One benefit of using CDI to inject your [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/">part 1</a>, we created a simple application that made use of string resource bundles in JSF and in <a href="http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/">part 2</a>  we extended it by using CDI to inject the resource provider into beans so we can re-use our code for accessing locale specific string based resources.<br />
<span id="more-1604"></span><br />
One benefit of using CDI to inject your beans instead of just creating them manually is the ability to utilize the event mechanism within those beans. In this example, we are going to fire an event when we discover a resource is missing. </p>
<ol>
<li>Start by creating a <code>MissingResourceInfo</code> class that stores the info regarding the missing resource (key and locale). This will be passed along with the event so the observer has all the info when it receives the event.</p>
<pre class="brush: java;">
public class MissingResourceInfo {

	private final String key;
	private final String locale;

	public MissingResourceInfo(String key, Locale locale) {
		this(key, locale.getDisplayName());
	}

	public MissingResourceInfo(String key, String locale) {
		super();
		this.key = key;
		this.locale = locale;
	}

	public String getKey() {
		return key;
	}

	public String getLocale() {
		return locale;
	}
}
</pre>
</li>
<li>We fire an event when we discover a resource key is missing from the locale specific properties file being used. In the <code>MessageProvider</code> class from part 2, we inject the <code>Event</code> instance in to a field and modify the <code>getValue</code> method to fire off the event when a key is missing.
<pre class="brush: java;">
@RequestScoped
public class MessageProvider {

	@Inject
	private Event&lt;MissingResourceInfo&gt; event;
	....
	....
	public String getValue(String key) {
		String result = null;
		try {
			result = getBundle().getString(key);
		} catch (MissingResourceException e) {
			result = &quot;???&quot; + key + &quot;??? not found&quot;;
			event.fire(new MissingResourceInfo(key, getBundle().getLocale()));
		}
		return result;
	}
}
</pre>
</li>
<li>Finally, we want to add an observer for that event that handles it when it is fired. To do this, we will add a new class for this purpose.
<pre class="brush: java;">
public class MissingResourceObserver {

	public void observeMissingResources(@Observes MissingResourceInfo info) {
		String template = &quot;Oh noes! %s key is missing in locale %s&quot;;
		String msg = String.format(template, info.getKey(), info.getLocale());
		System.out.println(msg);
	}

}
</pre>
</li>
<li>Finally, to see it in action, we need to add bean getter to fetch a non-existing value from the bundle.
<pre class="brush: java;">
@Named
@RequestScoped
public class AnotherBean {

	public String getMissingResource() {
		return provider.getValue(&quot;ImNotHere&quot;);
	}
}
</pre>
</li>
<li>We can see this in action by adding to our JSF page a call to this property
<pre class="brush: xml;">
#{anotherBean.missingResource}
</pre>
<p>Results in the following being displayed in the console :</p>
<pre class="brush: plain;">
Oh noes! 'ImNotHere' key is missing from locale English (United States)
</pre>
</li>
</ol>
<p>Remember, you can have as many event observers as you want so you can have one that just logs it to the console or one that emails if missing text strings are urgent (i.e. production). You could have it write the missing values to the database so during development cycles, the missing strings can be exported and put into the properties files. This is especially useful if you have third parties handling the translation where you can send them a list of missing items to translate in one big batch.</p>
<h1>What about EL?</h1>
<p>This works great when we are accessing resource bundles from Java, but what about when we are using EL expressions to access the values. JSF channels those expressions straight to the resource bundle without the ability to intercept them. One way to fix this would be to write our own EL expression resolver and see if the root of the expression maps to a resource bundle and if so try to obtain the value from the bundle and fire the event if the item is not found. This would work, but it seems overkill since every EL expression  would end up going through the resolver.<br />
Remember that the syntax for accessing resource strings in EL is <code>#{bundlename.key}</code>, and Java <code>Map</code> classes can also be accessed using the same syntax. What we can do is create a named bean that (barely) implements the map interface and in the <code>get</code> method, it gets the value from the injected resource bundle. This means EL expressions will use our Map bean and we can delegate the call to the Message provider which will handle missing expressions.</p>
<ol>
<li>Start by creating a new bean that implements the <code>Map</code> interface. Most of the methods will throw exceptions that they are not implemented, we only really care about the method to get values.</p>
<pre class="brush: java;">
@Named(&quot;messages&quot;)
@RequestScoped
public class ResourceMap implements Map&lt;String, String&gt; {

	@Inject
	private MessageProvider provider;

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	@Override
	public boolean containsKey(Object key) {
		return provider.getBundle().containsKey((String) key);
	}

	@Override
	public boolean containsValue(Object value) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

	@Override
	public String get(Object key) {
		return provider.getValue((String) key);
	}

	@Override
	public String put(String key, String value) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

	@Override
	public String remove(Object key) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

       ....
       ....
       ....
}
</pre>
<p>If the interface method isn&#8217;t listed, assume it throws a &#8220;not implemented&#8221; exception. We inject the <code>MessageProvider</code> instance so we can re-use our message provider bean to fetch messages and fire the events. </li>
<li>
We gave the bean the name <code>messages</code>  so if we go to our web page and add the following to our page :</p>
<pre class="brush: xml;">
First name from map = #{messages.firstName}&lt;br/&gt;
Missing name from map = #{messages.missingValue}&lt;br/&gt;
</pre>
<p>When we run our application and refresh the page, we get the value displayed for <code>messages.firstName</code>, and a missing value for <code>messages.missingValue</code>. In our server log we get </p>
<pre class="brush: plain;">
Oh noes! missingValue key is missing in locale English (United States)
</pre>
<p>Since we re-used the <code>MessageProvider</code> bean, it fires the event when it cannot find a key value so even though we called it from the JSF page, it ended up being routed through to our message provider and the event being fired.
</li>
</ol>
<p>How you use this is up to you, but since the syntax is the same whether you use the Map or the JSF resource variable, you can switch between the two depending on whether it is a development or production environment. You may also use different event handlers depending on the deployment environment. Alternatively, you may be worried about performance in production, or the fact that you lose autocompletion if you use the map in development.<br />
To switch implementations, just give either the JSF resource variable, in <code>faces-config</code> or the <code>MessageProvider</code> bean the name used for your resource string component. You can switch components without having to change either your code or your JSF pages.</p>
<p><a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourceEventDemo.zip'>Download the Maven source code</a> for this project and run it locally by typing unzipping it and running <code>mvn clean jetty:run</code> in the command line, and going to <a href="http://localhost:8080/resourcedemo/">http://localhost:8080/resourcedemo/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Injecting String Resource Services with CDI</title>
		<link>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/</link>
		<comments>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 15:02:26 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1601</guid>
		<description><![CDATA[In this post we looked at adding String resource bundles to our JSF applications to move our string constants into external resources that we can define for different locales. Now I want to extend that example to show how you can expand on that by using injection to access those resources. We finished off with [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/">this post</a> we looked at adding String resource bundles to our JSF applications to move our string constants into external resources that we can define for different locales. Now I want to extend that example to show how you can expand on that by using injection to access those resources.<br />
<span id="more-1601"></span><br />
We finished off with a <code>MessageProvider</code> class that was responsible for fetching the resource bundle and had methods for fetching values from that bundle. We created this class manually and accessed the string resources from it. The problem here is that we need to keep on recreating the provider in each piece of code that needs it.</p>
<h1>Doing things the CDI way</h1>
<p>You could construct an instance of the <code>MessageProvider</code> each time you need it, but instead, we should look at how we can change our existing code to make it more CDI like. We can make the method that fetches the bundle a producer method and then inject the resource bundle where needed. If we give it a long enough scope, we can re-use it in the same request. </p>
<p>First we&#8217;ll write a new Qualifier for the bundle so we can uniquely identify this bundle in a type safe manner. We may want to produce and inject multiple resources that will all be of the same type (<code>ResourceBundle</code>) so using a qualifier is a probably a good idea.</p>
<pre class="brush: java;">
@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface MessageBundle {

}
</pre>
<p>We&#8217;ll add a <code>@Produces</code> annotation to the <code>getBundle()</code> method.</p>
<pre class="brush: java;">
public class MessageProvider {

     @Produces @MessageBundle
     public ResourceBundle getBundle() {
		if (bundle == null) {
			FacesContext context = FacesContext.getCurrentInstance();
			bundle = context.getApplication().getResourceBundle(context, &quot;msgs&quot;);
		}
		return bundle;
	}
	...
        ...
        ...
}
</pre>
<p>Now we just need to inject this into our bean and use the injected bundle instead of constructing our own instance of the <code>MessageProvider</code> class.</p>
<pre class="brush: java;">
@Named
@RequestScoped
public class SomeBean {

	@Inject @MessageBundle
	private ResourceBundle bundle;

	public String getMessage() {
		String msg = null;
		String key = &quot;someMessage&quot;;
		try {
			msg = bundle.getString(key);
		} catch (MissingResourceException e) {
			msg = &quot;??&quot;+key+&quot;?? is missing!&quot;;
		}
		return MessageFormat.format(msg, &quot;SomeValue&quot;);
	}
}
</pre>
<p>While this is more CDI-ish, it does have the problem that it consists of more code since we re-produce the exception handling code each time. So we probably need to use something that consists of more than just the bundle, say maybe the whole <code>MessageProvider</code> class with the methods to fetch key values. The beauty here is that we we don&#8217;t need to do anything to achieve this except give the <code>MessageProvider</code> class a scope : </p>
<pre class="brush: java;">
@RequestScoped
public class MessageProvider {
    ....
    ....
}
</pre>
<p>No we just add an injection point for the <code>MessageProvider</code> class in our bean. We&#8217;ll create a new bean for this called <code>AnotherBean</code> :</p>
<pre class="brush: java;">
@Named
@RequestScoped
public class AnotherBean {

	@Inject
	private MessageProvider provider;

	public String getFirstNameCaption() {
		return provider.getValue(&quot;firstName&quot;);
	}
}
</pre>
<p>In our JSF page we add a reference to the property to display the value :</p>
<pre class="brush: xml;">
First Name Caption = #{anotherBean.firstNameCaption}
</pre>
<p>This results in the following text being displayed :</p>
<pre class="brush: xml;">
First Name Caption = First Name
</pre>
<p>You might notice that our old bean is still using the resource bundle from the producer method, and everything is still working. This is because beans can be injectable and still contain producer methods. You will also find that across the request, the injected instance of the bundle is always the same as the one in <code>provider.getBundle()</code>. This is because every time the bundle is produced, the <code>MessageProvider</code> is constructed and put into request scope and the bundle value is returned. This bundle value is retained in the <code>MessageProvider</code> instance. No matter how many times we inject the bundle, the same one is used, even though we didn&#8217;t give it a request scope. This is actually a useful thing because the resource bundle cannot be proxied by CDI so it cannot be put into request scope itself, but it can be put into request scope if it is contained in another bean (in this case, the <code>MessageProvider</code>).</p>
<p>This shows not only how flexible CDI is in making objects available to your applications, but how easy it is to tweak how those objects are made available, all without changing the underlying code.</p>
<p>Next time we&#8217;ll look at using event handling to notify us of missing resources.</p>
<p>You can <a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourceInjectionDemo.zip'>download the Maven source code</a> for this project and run it locally by unzipping it and running <code>mvn clean jetty:run</code> in the command line and going to <a href="http://localhost:8080/resourcedemo/">http://localhost:8080/resourcedemo/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Resource Bundles in JSF 2.0 Applications</title>
		<link>http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/</link>
		<comments>http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 13:26:08 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1597</guid>
		<description><![CDATA[Setting up resource message bundles in JSF to provide multilingal messages and captions is often overlooked when first creating an application. Leaving it till later in the project means you will have to go back and manually change the constants over to resource based values. Resource bundles JSF 1.2 were far from perfect but fortunately, [...]]]></description>
			<content:encoded><![CDATA[<p>Setting up resource message bundles in JSF to provide multilingal messages and captions is often overlooked when first creating an application. Leaving it till later in the project means you will have to go back and manually change the constants over to resource based values. Resource bundles JSF 1.2 were far from perfect but fortunately, using resource bundles in JSF 2.0 is very easy and this tutorial will show you how to add bundles and use them in your JSF 2.0 pages.<br />
<span id="more-1597"></span><br />
For this example, we&#8217;ll create a new application using the <code>jee6-servlet-basic-archetype</code> Knappsack Maven archetype. The full source can be <a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourcedemo.zip'>downloaded</a> and run using <code>mvn clean jetty:run</code> from the command line.</p>
<p>Message resources are stored in properties files which consist of name value pairs that binds a message key string with the message value. We&#8217;ll use the following example</p>
<pre class="brush: java;">
firstName=First Name
lastName=Last Name
forgotPassword=Forgot Password?
usernameTaken={0} is already taken
</pre>
<p>This file needs to be saved and referenced in a package, which would normally be in the same place as your source code, but Maven provides a separate area for resources. Save the file in the <code>src/main/resources/org/fluttercode/resourcedemo/<code> with the name <code>MessageResources.properties</code>. Open up the <code>faces-config</code> file and add the following XML :</p>
<pre class="brush: xml;">
&lt;application&gt;
	&lt;resource-bundle&gt;
		&lt;base-name&gt;org.fluttercode.resourcedemo.MessageResources&lt;/base-name&gt;
		&lt;var&gt;msgs&lt;/var&gt;
	&lt;/resource-bundle&gt;
&lt;/application&gt;
</pre>
<p>Here, we have told JSF about the resource bundle and assigned a variable name to it. Now we will go and add a reference to one of the messages in our home page. Open <code>home.xhtml</code> and replace the initial message with the following : </p>
<pre class="brush: xml;">
&lt;h:outputText  value=&quot;#{msgs.firstName}&quot;/&gt;
</pre>
<p>This is a JSF output text component that gets its value from the resource bunde, in this case, the <code>firstName</code> value. If you are using JBoss Tools, you will see that it can perform autocompletion for you on both the <code>msgs</code> value and the actual property keys on the <code>msgs</code> resources. It also displays the actual property value in the preview window for the page. If you run the app now by typing <code>mvn jetty:run</code> in the command line, you will see that the word <code>First Name</code> appears in the page.</p>
<h1>Access Resources From Code</h1>
<p>Typically, in your application you will generate messages for the user that also needs to be obtained from the resource bundle. To do this, we will create a bean that can fetch the resource bundle for us and extract strings from it.</p>
<pre class="brush: java;">
public class MessageProvider {

	private ResourceBundle bundle;

	public ResourceBundle getBundle() {
		if (bundle == null) {
			FacesContext context = FacesContext.getCurrentInstance();
			bundle = context.getApplication().getResourceBundle(context, &quot;msgs&quot;);
		}
		return bundle;
	}

	public String getValue(String key) {

		String result = null;
		try {
			result = getBundle().getString(key);
		} catch (MissingResourceException e) {
			result = &quot;???&quot; + key + &quot;??? not found&quot;;
		}
		return result;
	}

}
</pre>
<p>This class fetches the resource bundle from the faces context which will determine the best bundle to use based on the supported locales and the client locale. The second method uses the first method to fetch a string resource from the bundle.<br />
We'll create a JSF backing bean to use this bean to return a message to the user.</p>
<pre class="brush: java;">
@Named
@RequestScoped
public class SomeBean {

	public String getMessage() {
		String msg = new MessageProvider().getValue(&quot;someMessage&quot;);
		return MessageFormat.format(msg, &quot;SomeValue&quot;);
	}
}
</pre>
<p>In our <code>home.jsf</code> page, we display our message by adding </p>
<pre class="brush: xml;">
Message = #{someBean.message}
</pre>
<p>Which results in the following phrase being displayed :</p>
<pre class="brush: plain;">
Message = SomeValue is not valid
</pre>
<p>Having just the one default properties file in place is the bare minimum for using string resource bundles in your applications, and I would recommend using that for any application, even if it is never going to be multi-lingual. At the very least, it keeps your string constants in one place and at best, it makes it really easy to support multiple languages at a later date.</p>
<h1>Handling JSF Locale Information</h1>
<p>If you go multi-lingual you will need to provide multiple versions of the resource file for different locales, and list the supported locales in your <code>faces-config.xml</code> file.<br />
To test this, create multiple copies of the <code>MessageResources</code> file in the same directory with different names such as <code>MessageResources_de.properties</code> or <code>MessageResources_fr.properties</code> and in the content for each, use the same values, but add the locale on the end.</p>
<p><b>MessageResources_fr.properties</b></p>
<pre class="brush: plain;">
firstName=First Name(fr)
lastName=Last Name(fr)
forgotPassword=Forgot Password?(fr)
someMessage={0} is not valid(fr)
</pre>
<p>In the <code>faces-config.xml</code> file you can add the supported locales and set the default locale to use.</p>
<pre class="brush: xml;">
	&lt;application&gt;
		&lt;locale-config&gt;
			&lt;default-locale&gt;en_US&lt;/default-locale&gt;
			&lt;supported-locale&gt;de&lt;/supported-locale&gt;
			&lt;supported-locale&gt;en_GB&lt;/supported-locale&gt;
			&lt;supported-locale&gt;fr&lt;/supported-locale&gt;
		&lt;/locale-config&gt;
		&lt;resource-bundle&gt;
			&lt;base-name&gt;org.fluttercode.resourcedemo.MessageResources&lt;/base-name&gt;
			&lt;var&gt;msgs&lt;/var&gt;
		&lt;/resource-bundle&gt;
	&lt;/application&gt;
</pre>
<p>Now, depending on where you are in the world, and your browser locale, if you plan on following along, you'll have to substitute your own locale for en_US. Since we have a <code>MessageProperties</code> file without a locale in the file name, if it cannot find a matching locale, it will use this default bundle. If the default locale is specified in <code>faces-config</code>,then that locale will be used instead of the non-specific default.<br />
Play around with renaming some of the resource files, especially the file that matches your own locale. If the file exists, but it is not included in the list of supported locales in <code>faces-config</code> it won't be used. You can also change the <code>default-locale</code> value to one other than your own locale and see how the locale would be selected.<br />
JSF will also select a locale that matches based on the language if not the specific region. In my case, having a locale of <code>en_US</code> means that if available, JSF will select the <code>MessageResources_en</code> bundle if there is no bundle specifically for <code>en_US</code>.</p>
<p><a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourcedemo.zip'>Download the Maven source code </a> for this project and run it locally by unzipping it into a folder and typing <code>mvn clean jetty:run</code> and going to <a href="http://localhost:8080/resourcedemo/">http://localhost:8080/resourcedemo/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>CDI Conversations part 2</title>
		<link>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/</link>
		<comments>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 13:07:43 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Conversation]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1279</guid>
		<description><![CDATA[This article will look at using the Conversation scope defined in JSR 299 (Java Contexts and Dependency Injection), and released as part of Java EE 6. For now, we&#8217;ll stick to non-data driven examples as we explore the ins and outs of the Conversation scope. We&#8217;ll finish up by creating a workspace manager so we [...]]]></description>
			<content:encoded><![CDATA[<p>This article will look at using the Conversation scope defined in JSR 299 (Java Contexts and Dependency Injection), and released as part of Java EE 6. For now, we&#8217;ll stick to non-data driven examples as we explore the ins and outs of the Conversation scope. We&#8217;ll finish up by creating a workspace manager so we can list all the active conversations and switch between them.<br />
<span id="more-1279"></span><br />
A Conversation is like a numbered bucket in the session that exists until either the end of the users session, the conversation times out, or the server side code deliberately ends the conversation. The benefits of a conversational scope are many, letting us easily create pages that can be opened in multiple tabs without having to juggle the state on the client without filling the session with data that will last as long as the user session should we forget to remove it.</p>
<p>We&#8217;ll start by creating a project from the <a href="http://www.andygibson.net/blog/projects/knappsack" target="_blank">knappsack</a><code>jee6-servlet-basic</code>  archetype. This gives us all the features of Java EE 6 without too much code to get in the way.  We&#8217;ll start by creating a backing bean that is request scoped and looking at how that is used and what effect request scope has.</p>
<pre class="brush: java;">
import java.io.Serializable;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named(&quot;bean&quot;)
@RequestScoped
public class BackingBean implements Serializable {

	private Long value = new Long(0);

	public Long getValue() {
		return value;
	}

	public void setValue(Long value) {
		this.value = value;
	}

        public String getMessage() {
            return &quot;The value is : &quot;+value;
        }
}
</pre>
<p>Simple enough, now lets add a page called <code>listEdit.xhtml</code>that lets us enter the value, post the value back and see what the message is. </p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:form id=&quot;form&quot;&gt;
            Value : &lt;h:inputText value=&quot;#{bean.value}&quot; /&gt;
			&lt;h:commandButton value=&quot;Submit Value&quot; action=&quot;submit&quot; /&gt;
			&lt;br /&gt;
			&lt;br /&gt;
            Message : #{bean.message}
   &lt;/h:form&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>Edit <code>home.xhtml</code> to include a link to this page :</p>
<pre class="brush: xml;">
&lt;a href=&quot;listEdit.jsf&quot;&gt;Start New List&lt;/a&gt;
</pre>
<p>Open up the home page and click the link to go to the <code>listEdit</code> page. If we enter a value in the input box and click the submit button, predictably, our message says that the value is whatever we entered.</p>
<div class="contentBox alignCenter">
<img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/request_scoped_bean1.png" alt="Request Scoped Bean Entry Screenshot" title="Request Scoped Bean Entry Screenshot" width="578" height="302" class="alignnone size-full wp-image-1285" />
</div>
<p>What is happening here is that when the form is posted back, the value in the input box is sent back to the <code>bean.value</code> attribute. When the page is rendered back to the user and the message is rendered, it is rendered using this value that we passed back to the server. We pass the state of the attribute from the server to the client, and then back to the server, and we can do that all day long using just the request scope without any problems. This is a stateless page and doesn&#8217;t require any state to be held on the server.</p>
<p>Let&#8217;s add something a bit more stateful to the page such as a list of values that we have added previously. In our backing bean, add the following field and getter method and a method to add the value.</p>
<pre class="brush: java;">
private List&lt;Long&gt; values = new ArrayList&lt;Long&gt;();
..
..
..
public List&lt;Long&gt; getValues() {
	return values;
}

public void addToList() {
	values.add(value);
}
</pre>
<p>Now we will add the list of values to our page to be displayed.</p>
<pre class="brush: xml;">
&lt;ui:define name=&quot;content&quot;&gt;
	&lt;h:form id=&quot;form&quot;&gt;
		Value : &lt;h:inputText value=&quot;#{bean.value}&quot; /&gt;
		&lt;h:commandButton value=&quot;Submit Value&quot; action=&quot;#{bean.addToList}&quot; /&gt;
		&lt;br /&gt;
		&lt;br /&gt;
		Message : #{bean.message}
		&lt;h2&gt;Added Values&lt;/h2&gt;
		&lt;ui:repeat var=&quot;v_value&quot; value=&quot;#{bean.values}&quot;&gt;
			#{v_value}&lt;br /&gt;
		&lt;/ui:repeat&gt;
	&lt;/h:form&gt;
&lt;/ui:define&gt;
</pre>
<p>If we refresh our page, enter a number and click submit, you will see that the number appears at the bottom of the page where it should. When we click the submit button on the form the value is assigned to the <code>value</code> attribute. When the <code>addToList</code> method is called, the <code>value</code> attribute is added to the list. When the page is rendered, the latest value is used to generate the message and for the list of items we return the list containing one item, the new value.</p>
<p>So far so good. Let&#8217;s enter a new number and add it to the list. When we click the button the second time, the only number in the list of numbers is the one we just entered. The first value is gone! The problem is that the second time we posted the value the bean was re-constructed from scratch and had no idea whatsoever about the first value we added to the list. There was nothing on the form to tell the bean about the first number even though we displayed it on the page. The backing bean keeps forgetting our list of numbers from one request to the next, or in other words, our application is missing some state.</p>
<p>As per part 1, there are a number of ways we can get around this problem. We could save the list to the database each time we post, which is over kill for this simple task.   We could push the state down to the client, say using a comma delimited list of existing numbers pushed into a hidden field. When the form is posted, the comma delimited list is sent back to the server where the numbers are unpacked and the list is rebuilt on the server side and the state is restored.<br />
Both of these two methods are doable but what happens when we have more information on the server that we need to keep hold of? Do we have to keep adding add each piece of information to the client state manually, including passing it around from one page to the next for multi-page processes? What if it is a list of entity objects we want to hold on to? Do we just save the Ids on the client and keep re-loading them from the database each time?<br />
These solutions are impractical from the perspective of building a maintainable app quickly. However, note that these solutions are completely possible with JSF and CDI. It just offers better alternatives, but the opportunity to get under the hood and use more lower level solutions in the interests of optimizing the application are always there.  This is an important factor since if you have a widely used conversational page that is creating a bottle neck, you can refactor it down to use a more stateless approach. </p>
<p>Since this article is all about conversations, obviously, we are going to solve our problems using the conversation scope. We will change our bean to be <code>@ConversationScoped</code> and <code>@Inject</code> a <code>Conversation</code> instance we&#8217;ll be using. We&#8217;ll then start the conversation for the page when our bean is constructed. This is an example and typically you don&#8217;t start conversations in bean construction but it serves our purpose here.<br />
<small><b>Tip</b> : Conversations are typically started at specific points on certain initialization methods, starting it on bean construction is bad because you never know when another task might use an instance of that bean</small></p>
<pre class="brush: java;">

@Named(&quot;bean&quot;)
@ConversationScoped
public class BackingBean implements Serializable {
	...
	...
	...
	@Inject
	private Conversation conversation;
	...
	...
	@PostConstruct
	public void postConstruct() {
		conversation.begin();
	}

	public Conversation getConversation() {
		return conversation;
	}
	...
	...
}
</pre>
<p>Reload our page and you can see how you can enter and submit as many numbers as you want to the page and the list state is managed.</p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_list.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_list-300x248.png" alt="Conversation Number List Screenshot" title="Conversation Number List Screenshot" width="300" height="248" /></a>
</div>
<p>Conversations are just a natural extension of the existing scopes in current web applications. They also become very natural to use. Let&#8217;s add another page that lets us review our list of numbers before &#8216;confirming&#8217; them. Add the following new button at the bottom of our page : </p>
<pre class="brush: xml;">
	&lt;h:commandButton action=&quot;review&quot; value=&quot;Review Numbers&quot;/&gt;
</pre>
<p>Because the <code>action</code> attribute is set to <code>review</code> we will create a new page called <code>review.xhtml</code> that will display the numbers. Our first concern obviously is &#8216;where does it get the list of numbers from?&#8217;, well the answer is, from the same place it got the numbers from last time, using the expression <code>#{bean.values}</code>.</p>
<p><code>review.xhtml</code></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:form id=&quot;form&quot;&gt;
			&lt;h1&gt;Please Confirm The Values : &lt;/h1&gt;
			&lt;h2&gt;Added Values&lt;/h2&gt;
			&lt;ui:repeat var=&quot;v_value&quot; value=&quot;#{bean.values}&quot;&gt;
			#{v_value}&lt;br /&gt;
			&lt;/ui:repeat&gt;
			&lt;h:commandButton action=&quot;#{bean.confirm}&quot; value=&quot;Confirm&quot;/&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>The way to think about this is to imagine what happens when the page is rendered. JSF will look for the value <code>beans.values</code> which the CDI implementation can provide. Since this page is being rendered in an active conversation, CDI will look in the active conversation &#8216;bucket&#8217; for a bean called <code>bean</code>. Since we are coming from the page that adds the numbers, this bean will already exist in the conversation and so the same instance is returned. Should we render this page without an active conversation, by typing in the URL manually, the page will render, but this time, the instance of <code>beans.xml</code> will not already exist and so CDI will create a new instance of it that doesn&#8217;t contain any items.<br />
<small><b>Tip : </b>There are ways to prevent pages rendering without an active conversation which can also help with duplicate form submissions</b></small></p>
<p>Getting back to the page, we just want to add our confirm method to our backing bean. This method ends the conversation and redirects to the home page which is going back to the number entry page. </p>
<pre class="brush: java;">
public void confirm() {
	conversation.end();
	try {
		FacesContext.getCurrentInstance().getExternalContext().redirect(&quot;home.jsf?faces-redirect=true&quot;);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
</pre>
<p>Add the following at the top of either the review or list edit page to see the conversation Id you are currently in : </p>
<pre class="brush: xml;">
Conversation : #{bean.conversation.id}
</pre>
<p>If you run the application, you can add numbers and when you click review, you get a list of all the numbers you just entered on a separate page.</p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_confirm.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_num_confirm-300x260.png" alt="Conversational Number Confirmation" title="Conversational Number Confirmation" width="300" height="260" /></a>
</div>
<p>If we were managing state ourselves, we would have to pass something to the review page to let is know what the list of numbers was, either a database row key, or the comma delimited values. Again, the more state you have to pass around the less verbose and maintainable the application becomes.  CDI is automatically passing our key (the conversation id) around for us. Under the review button the list edit page, add the following GET link :</p>
<pre class="brush: xml;">
&lt;h:link outcome=&quot;review&quot; value=&quot;Review&quot;/&gt;
</pre>
<p>If you look at the link URL it is <code>http://localhost:8080/conversationdemo/review.jsf?cid=xxx</code> where xxx is some number. CDI automatically creates a URL that propagates the conversation for us. If we didn&#8217;t want to propagate the conversation, we can just add a blank <code>cid</code>  parameter and CDI will leave it alone. This can be useful when you want to launch a page without a conversation from a page that is in a conversation. Add the following link : </p>
<pre class="brush: xml;">
&lt;h:link value=&quot;Start New List&quot; target=&quot;_blank&quot;&gt;
	&lt;f:param name=&quot;cid&quot; /&gt;
&lt;/h:link&gt;
</pre>
<p>This lets you start a fresh new list in a separate window (since we didn&#8217;t specify an outcome it defaults to the current page). If you create a new list and add some numbers you can see that you can manage separate lists independently without doing anything to handle multiple browser windows.</p>
<p>When you have multiple windows open, set the url of one window to the url of other (i.e. <code>http://localhost:8080/conversationdemo/listEdit.jsf?cid=xxx</code> where xxx is the other conversation ID) when you load this page, you see the list from the other conversation so you can just switch conversations using GET requests by specifying a different conversation id. </p>
<h1>Workspace Management</h1>
<p>One cool feature of Seam that had a lot of potential was workspace management which lets you see a list of active conversations and select one. We are going to implement a version of that here by providing the user with a set of links that takes us to the active conversation. Create a new bean that is session scoped that will keep a track of our conversation ids.</p>
<pre class="brush: java;">
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class WorkspaceBean implements Serializable {

	private List&lt;String&gt; conversations = new ArrayList&lt;String&gt;();

	public List&lt;String&gt; getConversations() {
		return conversations;
	}

}
</pre>
<p>This is just a bean that keeps a list of the conversation Ids currently active. When we start a conversation, we need to add that id to the list and when we end a conversation, we need to remove it from the list. </p>
<p>We will inject this session scoped bean into our backing bean and change the <code>postConstruct</code> and <code>confirm</code> methods in the <code>BackingBean</code> class to add and remove the conversation from the list.</p>
<pre class="brush: java;">
@Inject
private WorkspaceBean workspace;

...
...

@PostConstruct
public void postConstruct() {
	conversation.begin();
	workspace.getConversations().add(conversation.getId());
}

public void confirm() {
	workspace.getConversations().remove(conversation.getId());
	conversation.end();

	try {
		FacesContext ctx = FacesContext.getCurrentInstance();
		ctx.getExternalContext().redirect(&quot;home.jsf?faces-redirect=true&quot;);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
</pre>
<p>Now we need some view code to display the list of conversations and provide links to them. Simply add this to the <code>home.xhtml</code> page, and even the <code>listEdit.xhtml</code> or <code>review.xhtml</code> pages if you want : </p>
<pre class="brush: xml;">
	&lt;h1&gt;Workspaces&lt;/h1&gt;
	&lt;ui:repeat var=&quot;v_conv&quot; value=&quot;#{workspaceBean.conversations}&quot;&gt;
		&lt;h:link outcome=&quot;listEdit&quot; value=&quot;Goto Conversation #{v_conv}&quot;&gt;
			&lt;f:param name=&quot;cid&quot; value=&quot;#{v_conv}&quot; /&gt;
		&lt;/h:link&gt;
		&lt;br /&gt;
	&lt;/ui:repeat&gt;
</pre>
<p>This just loops through the conversations and creates a link to the <code>listEdit</code> page and passes the conversation Id as a parameter. Because we pass a value for <code>cid</code> CDI will not try to add the current conversation as the <code>cid</code> value.</p>
<p>That&#8217;s all you need for a workspace demonstration. You can create new lists and if you jump back to the home page, you will see the available conversations and be able to click the link and jump back into the conversation. When you review the list and confirm it and the conversation ends, when you end up back on the front page, that conversation is longer listed. </p>
<div class="contentBox alignCenter">
<a target="_blank" href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_workspace.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/conv_2_workspace-300x235.png" alt="Conversation Workspace Screenshot" title="Conversation Workspace Screenshot" width="300" height="235" class="alignnone size-medium wp-image-1409" /></a>
</div>
<p>This is a fairly powerful mechanism that is built upon the simplicity of CDI Conversations. There is very little work that is required to use conversations, just inject the <code>Conversation</code> instance and call the <code>begin()</code> and <code>end()</code> methods when you need to start and end the conversation. Conversations also have a minimal impact on our code, mainly just an annotation since the getters and settings and other methods don&#8217;t change. We can also easily revert back to a stateless request scoped solution should we have to which would cause additional code to be required to read/write the list to the client.<br />
Conversations should be used with care, especially in terms of making sure you have strict demarcation boundaries, and careful consideration should be given to determining what you include in a conversation.</p>
<p>You can download the maven project source code for this demo (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/conversationdemo.zip'>Conversation Demo </a>), just unzip it and enter <code>mvn jetty:run</code> and navigate to <a href="http://localhost:8080/conversationdemo/home.jsf">http://localhost:8080/conversationdemo/home.jsf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/cdi-conversations-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JSF Basics</title>
		<link>http://www.andygibson.net/blog/tutorial/jsf-basics/</link>
		<comments>http://www.andygibson.net/blog/tutorial/jsf-basics/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 12:51:19 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1372</guid>
		<description><![CDATA[This is a brief tutorial that takes a quick look at some of the very basics of JSF, how we define pages and hook them up to server side objects. Rather than cover the fundamentals of starting a new JSF application, I&#8217;m going to start from one of the Knappsack archetypes which can provide you [...]]]></description>
			<content:encoded><![CDATA[<p>This is a brief tutorial that takes a quick look at some of the very basics of JSF, how we define pages and hook them up to server side objects. Rather than cover the fundamentals of starting a new JSF application, I&#8217;m going to start from one of the Knappsack archetypes which can provide you with a JEE 6 application ready to roll.  In this case, we are going to start with a servlet based example so you can run it using the embedded servlet containers.<br />
<span id="more-1372"></span><br />
To create the new project, we are going to use the following archetype GAV values. You can also read up  on <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-maven-archetypes/" target="_blank">creating a new Knappsack application</a></p>
<pre class="brush: plain;">
groupId = org.fluttercode.knappsack
artifactId=jee6-servlet-basic
version=1.0.5
</pre>
<p>Once you have your project, just run <code>mvn jetty:run</code> in the command line and navigate to <a href="http://localhost:8080/jsfbasics/home.jsf">http://localhost:8080/jsfbasics/home.jsf</a>. Ok, so now we are up and running, lets look at a JSF page and what it contains.</p>
<p>JSF uses a templating language called facelets. JSF 1 originally used JSP as its view language, but for JSF 2.0 Facelets became the defacto standards and was adopted as the standard view definition languages for JSF 2.0. In our application, we have a template file called <code>WEB-INF/templates/template.xhtml</code>. The template just has a lot of boilerplate view code but there are some <code>ui:insert</code> tags that mark places in the template where we should insert content. For example, the main content is inserted in a facelets area called <code>content</code></p>
<pre class="brush: xml;">
&lt;ui:insert name=&quot;content&quot;&gt;Main Content&lt;/ui:insert&gt;
</pre>
<p>These are insertion points which are used by pages that base themselves on this template. One of the great features of facelets is that the template defines the content points, while the page itself is used to define the template used and then push the content into the content points. This is much better than having to include page fragments in a JSP page, using a page decorator or using a template to include the content page. Our main page <code>home.xhtml</code> is one such page that uses this template. </p>
<p><code>home.xhtml</code></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;

	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h1&gt;&lt;h:outputText value=&quot;Hello From JSF&quot; /&gt;&lt;/h1&gt;
	&lt;/ui:define&gt;

&lt;/ui:composition&gt;
</pre>
<p>At the very top, in the composition tag, we tell Facelets that we want to use the file <code>template.xhtml</code> as our template page. Next we have a <code>ui:define</code> tag that defines the content that is to be used in the template. Facelets works by having the page pull the template into the page and pushing its content into the slots provided by the template. This is much better than pulling content into the main page using includes, or specifying a template used everywhere and decorating the content with it. This is the best of both worlds. Each page defines which template page it uses and pushes the content into it. </p>
<h2>Our first used component</h2>
<p>In here you can see we have used our first JSF component : </p>
<pre class="brush: xml;">
&lt;h:outputText value=&quot;Hello From JSF&quot; /&gt;
</pre>
<p>This is a standard JSF component that is used to output text. We could have just written the text right in the page, but the goal of this page is to test that the JSF configuration is working and to do that, we need to see if the JSF component is rendered correctly.  You can edit the text in the value and obviously it will change the text displayed on the page.</p>
<h2>Our first backing bean</h2>
<p>Displaying static text isn&#8217;t what web frameworks were built for, what we really want is to display something that comes from some java code. To do this, we will create a backing bean which is a java object that is part of the web application that JSF is aware of. To create backing bean, create a new class and call it <code>PageBean</code>.</p>
<pre class="brush: java;">
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class PageBean {

	private String message = &quot;Mighty apps from little java beans grow&quot;;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}
</pre>
<p>The code itself is pretty simple. One field with a default value and getters and setters. However, we have a couple of new annotations at the class level. First is the <code>@Named</code> annotation that tells CDI that this bean has a name that be used to refer to this bean using EL expressions. Since we didn&#8217;t supply a name the default name of <code>pageBean</code> is used. The <code>@RequestScope</code> annotation tells CDI that this bean is request scoped so when it is created, it should last till the end of the current request and then be destroyed. This means that the next time we call this page, this bean will be re-created and a fresh version used which again will be destroyed at the end of the request.</p>
<p>Now we are going to change our application to display this message instead.From now on, we will just be showing the code within the <code>ui:define</code> statements:</p>
<pre class="brush: xml;">
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h:outputText value=&quot;#{pageBean.message}&quot; /&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>If we run the application now, you should see the message displayed on the main page:</p>
<div class="alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_motd.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_motd-300x190.png" alt="JSF Basic message of the day screenshot" title="JSF Basic message of the day screenshot" width="300" height="190" /></a>
</div>
<p>Now let&#8217;s take look at a producer method that can be used to display the date and time the page was rendered. First, open up the template file and look for the footer panel at the bottom and change it to :</p>
<pre class="brush: xml;">
&lt;h:panelGroup id=&quot;footer&quot; layout=&quot;block&quot;&gt;This page was rendered at #{currentSysDate}&lt;/h:panelGroup&gt;
</pre>
<p>What is <code>currentSysDate</code> value? Well, we need to go back to our <code>PageBean</code> and define it. We will add a new method that returns a new <code>Date</code> object and we&#8217;ll annotate it with <code>@Named</code> and <code>@Produces</code>. </p>
<pre class="brush: java;">
@Produces @Named(&quot;currentSysDate&quot;)
public Date produceDate() {
	return new Date();
}
</pre>
<p>The <code>Produces</code> and <code>Named</code> annotation tells CDI that this method can be used to produce a value with the name <code>currentSysDate</code>. When our application is deployed, CDI makes a note that this value comes from this method so when our page is rendered and JSF is looking for the value <code>currentSysDate</code>, CDI calls the method and returns the value obtained from this method.</p>
<p>If we refresh the page we can see that our new timestamp function is on there.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic_timestamp.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic_timestamp-300x185.png" alt="JSF Basic Timestamp Screenshot" title="JSF Basic Timestamp Screenshot" width="300" height="185"  /></a>
</div>
<p>This will come in handy later on when we start using AJAX and want to check that the full page has not updated (the timestamp will stay the same because that portion of the page won&#8217;t change). We&#8217;ve shown how we can pull data from the server onto the page so let&#8217;s take a look at how we send data back to the server.</p>
<p>In our <code>home.xhtml</code> page, we&#8217;ll add a text input to edit the message and a button to post it back.</p>
<pre class="brush: java;">
&lt;h:form id=&quot;messageForm&quot;&gt;
	&lt;h:outputText value=&quot;#{pageBean.message}&quot; /&gt;&lt;br/&gt;
	&lt;br/&gt;
	New Message : &lt;h:inputText value=&quot;#{pageBean.message}&quot;/&gt;
	&lt;h:commandButton action=&quot;update&quot; value=&quot;Update&quot;/&gt;
&lt;/h:form&gt;
</pre>
<p>First, we added the <code>h:form</code> tags which gives us an HTML form in which to put input controls. Any data entry in a JSF page needs to be enclosed in a JSF form tag in order to be passed back to the server. We defined an input text box that was bound to the same value as the message display and a command button that is used to post the values back. If we refresh the page, enter a new message and click the button our message changes.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_form_post.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_form_post-300x184.png" alt="JSF Basic Form Post Screenshot" title="JSF Basic Form Post Screenshot" width="300" height="184"  /></a>
</div>
<p>However, this is the age of Web 2.0, and just posting back a form and displaying the results isn&#8217;t enough, we need to do it with AJAX. AJAX is a mechanism by which the browser makes an asynchronous request to the server and gets a response back. When the response is returned, the browser will call a javascript function that will update part of the page instead of all of it. Sounds complicated, but the nice folks that wrote JSF wrapped all that functionality up in one little tag called <code>f:ajax</code></p>
<p>What we want to do is make our command button an AJAX button which we can do by placing the <code>f:ajax</code> tag as a child tag of the button. All we need to supply the AJAX tag with is the <code>execute</code> and <code>render</code> attributes. This indicates which parts of the page we want to post back to the server, and which parts we want to re-render when the response comes back.  We want to execute the form and re-render the form, so we could use the component id (<code>messageForm</code>) for the attribute values. JSF also provides a couple of shortcuts that we can use. The value <code>@form</code> references the form the button is in so rather than hardcode the form id, the <code>@form</code> value will let us reference the form without doing so by name.</p>
<pre class="brush: java;">
&lt;h:commandButton action=&quot;update&quot; value=&quot;Update&quot;&gt;
	&lt;f:ajax execute=&quot;@form&quot; render=&quot;@form&quot; /&gt;
&lt;/h:commandButton&gt;
</pre>
<p>Notice that now you have an ajax button, the timestamp in the footer doesn&#8217;t change when you post the value back. </p>
<h1>Performing Actions</h1>
<p>So far we have covered displaying information from the server side bean and writing values back, but often we want some user action to execute some code on the server. </p>
<p>Start by adding a <code>Integer</code> attribute on to our <code>PageBean</code> class and two methods, one to increase it, and another to decrease it as well as getters and setters for the value.</p>
<pre class="brush: java;">
	private int value = 0;

	public void increase() {
		value++;
	}

	public void decrease() {
		value--;
	}
</pre>
<p>In the view, we want to display the value and have a couple of buttons to increase and decrease the value. Add the following view code in <code>home.jsf</code> somewhere between the <code>h:form</code> tags :</p>
<pre class="brush: xml;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
     &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot; /&gt;
     #{pageBean.value}
     &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
&lt;/h:panelGroup&gt;
</pre>
<p>Refresh the page and click away, and you&#8217;ll notice something is wrong. Press the increase button and the value goes to 1, click it again and it&#8230;goes to 1. Click the decrease button and it will always go to -1. The problem is an issue of state. Each time we click the button, we post back to the server, and the server creates a new instance of the <code>pageBean</code> and calls the increase or decrease methods. The problem is that each time we create the bean, the value starts at zero and so is only ever increased to 1 or decreased to -1.<br />
Now you may be wondering that since you are displaying the value on the page, isn&#8217;t that enough to post it back to the server, after all, we displayed the message in an input box and it got passed back to the server. The difference is that an input box is known as a JSF value holder, which means it actually holds the value it is bound to on the client and posts it back to the server when the form is posted back. We can see this demonstrated by changing the value text display component to an input text box component:</p>
<pre class="brush: java;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
    &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot;/&gt;
    &lt;h:inputText value=&quot;#{pageBean.value}&quot;/&gt;
    &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
&lt;/h:panelGroup&gt;
</pre>
<p>Now when you click the +/- buttons the value changes beyond -1 and 1. This is because when the page is rendered, the value is stored on the client. When the button is clicked and the form is posted back, the client side value is sent back to the server side attribute and then the increase/decrease method is called with the value that is set. This is fairly common with web forms, and one way of handling state by putting it in client side forms, even as hidden field values.</p>
<p>We can demonstrate this further by manually entering a value into the text input and then clicking a button. Enter 1000 in the input text box and click the increase button. The value should now be 1001. </p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasics1_manual_input.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasics1_manual_input-300x184.png" alt="JSF Basics Manual Value Input" title="JSF Basics Manual Value Input" width="300" height="184" /></a>
</div>
<p>When we manually enter a value, we are changing the value held on the client in the value holder represented by the input text box. When we click the increase button we are sending that value back to the server. On postback, the server creates an instance of our <code>PageBean</code> class, sets the value attribute to the value in our text box (1000) and then calls the <code>increase</code> method which increases the value to 1001. Once the method has finished, JSF then must render a response which includes taking the value from the <code>pageBean.value</code> attribute and putting it in our text box which is how the text box shows 1001 after clicking the button. At this point, once our request is complete, the page bean is destroyed as it is only request scoped.</p>
<h2>Validating the value</h2>
<p>If we only want the value to be between 0 and 10, we can add validation annotations onto the value field to enable it to be checked for correctness when we post back the values. In our <code>PageBean</code> class, we&#8217;ll add the annotations as follows : </p>
<pre class="brush: java;">
@Min(value=0)
@Max(value=10)
private int value = 0;
</pre>
<p>We also need some way to display error messages if the user enters an invalid value so we&#8217;ll add a <code>h:message</code> tag. The message tag is used to associate a JSF message with a component and display it. We give the input text box a name and add the message for that component :</p>
<pre class="brush: java;">
&lt;h:panelGroup layout=&quot;block&quot; id=&quot;spinner&quot;&gt;
	  &lt;h:commandButton action=&quot;#{pageBean.decrease}&quot; value=&quot;-&quot;/&gt;
	  &lt;h:inputText value=&quot;#{pageBean.value}&quot; id=&quot;valueInput&quot;/&gt;
	  &lt;h:commandButton action=&quot;#{pageBean.increase}&quot; value=&quot;+&quot; /&gt;
	  &lt;h:message for=&quot;valueInput&quot; styleClass=&quot;errorMessage&quot;/&gt;
&lt;/h:panelGroup&gt;
</pre>
<p> Now refresh the page and enter 1000 into the value text input and click the increase button. You should see an error message next to the text editor because the value is above 10. Try entering the value of -1000 and clicking a button.</p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_input_error.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/jsfbasic1_input_error-300x185.png" alt="JSF Basic Input Error Screenshot" title="JSF Basic Input Error Screenshot" width="300" height="185"/></a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/jsf-basics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My Framework Picks</title>
		<link>http://www.andygibson.net/blog/article/my-framework-picks/</link>
		<comments>http://www.andygibson.net/blog/article/my-framework-picks/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 14:30:59 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1494</guid>
		<description><![CDATA[When I talked about how Context Matters When Discussing Frameworks I intentionally left out naming any picks because the point of that article wasn&#8217;t to start a framework debate (neither is this one, but at least it will get isolated in here). In this post, I&#8217;ll cover my choice of frameworks. My Personal Choices For [...]]]></description>
			<content:encoded><![CDATA[<p>When I talked about how <a href="http://www.andygibson.net/blog/article/context-matters-when-discussing-frameworks/">Context Matters When Discussing Frameworks</a> I intentionally left out naming any picks because the point of that article wasn&#8217;t to start a framework debate (neither is this one, but at least it will get isolated in here). In this post, I&#8217;ll cover my choice of frameworks.<br />
<span id="more-1494"></span></p>
<h1>My Personal Choices</h2>
<p>For me personally, nothing does Web Applications better than JSF backed by Java EE 6. A year ago I would have said Seam, but Java EE 6 now carries most of the Seam functionality. Java EE 6 with Seam 3 sprinkled in for good measure will rock. (if you think Java EE 6 sucks for not being whole until it has Seam 3 added, think of it more like adding jQuery to your web pages). I do like Wicket, but for me, it&#8217;s one of those that sits in the middle and does a bit of both.  It&#8217;s like riding a bike to the mailbox (only a little bit of overkill), or to the store (better than walking, but still with limits). However, it is a very viable alternative.</p>
<p>For web site type projects, I would look for a framework that is more client oriented since people will want to start leveraging the advancements with HTML 5 and Javascript. I would probably use Spring MVC or at a stretch, possibly Grails. Primarily because it offers a development structure that is not so dissimilar to using JSF, and can include Spring Web Flow for more statefulness. At the same time it lets you get under the hood more with CSS, HTML and JavaScript if you choose to. It also gives you some more deployment options without taking features away. </p>
<p>Note that these are merely my personal choices and their selection says nothing about the choices made by anyone else any more than choosing to drive a Ford is being critical of someone driving a Honda. Similarly, if you think Fords suck, you should have at least have a good reason for believing so, other than you couldn&#8217;t drive one before you learned how to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/my-framework-picks/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

