<?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; JEE</title>
	<atom:link href="http://www.andygibson.net/blog/tag/jee/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>JSTL 1.2 Missing From Maven Repositories</title>
		<link>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 12:45:04 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1802</guid>
		<description><![CDATA[It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a number of issues around the web. Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one javax.servlet.jstl [...]]]></description>
			<content:encoded><![CDATA[<p>It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a <a href="http://www.google.com/search?q=jstl%201.2%20missing">number of issues</a> around the web.</p>
<p>Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one <code>javax.servlet.jstl</code> dependency you will use the following :</p>
<pre class="brush: xml;">
&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.glassfish.web&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-impl&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>If you are running code in a container that already contains JSTL you will just use the <code>jstl-api</code> dependency with a <code>scope</code> of <code>provided</code>. This way your code has access to the API that will be provided by the container.</p>
<p>For those of you using the Knappsack archetypes or using the JBoss Java EE 6 API pom, or no doubt some other dependencies that use <code>javax.servlet.jstl</code>, you will have problems because the Java EE 6 pom relies on the <code>javax.servlet.jstl</code> dependency. The answer here is to exclude it from the Java EE 6 dependency and add it separately using the api dependencies described above.</p>
<pre class="brush: xml;">
&lt;dependency&gt;
    &lt;groupId&gt;org.jboss.spec&lt;/groupId&gt;
    &lt;artifactId&gt;jboss-javaee-6.0&lt;/artifactId&gt;
    &lt;version&gt;1.0.0.Final&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
    &lt;type&gt;pom&lt;/type&gt;
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;jstl&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;

&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>I&#8217;m surprised that they would eliminate the pom like that, but it may have been due to licensing issues for the reference implementation which I believe has been an issue for some of the standard Java EE APIs and the reason that there is no real definitive deployment of the APIs and we have to mix and match API dependencies from different sources unless you are using the <a href="http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/">JBoss Java EE 6 dependency</a> to solve the problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>Simple RESTful services in Glassfish Pt 2</title>
		<link>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/</link>
		<comments>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 12:39:13 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1765</guid>
		<description><![CDATA[In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page. In part 1, we looked at creating simple web services and now [...]]]></description>
			<content:encoded><![CDATA[<p>In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page.<br />
<span id="more-1765"></span><br />
In part 1, we looked at creating simple web services and now we&#8217;re going to look at making something more practical and interesting. We&#8217;ll start from where we left off with the source code as it was at the end of the part 1 which you can download from here (<a href="http://www.andygibson.net/blog/wp-content/uploads/2011/02/restwebdemo_pt1.zip">restwebdemo_pt1</a>) if you want to follow along. If not, the final source can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>).</p>
<ol>
<li>First off, we&#8217;re going to change the entity manager that is available for injection to be request scoped. To do this, open up <code>DataRepositoryProducer.java</code> and change the <code>@ConversationScoped</code> annotation on the <code>getEntityManager()</code> method to be <code>@RequestScoped</code>.  The reason for this is documented here in <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>.</li>
<li>Next we are going to create a simple dao for Course objects, and the only reason to do this is to demonstrate the integration of CDI and the ability to layer your code. Create a new class called <code>CourseDao</code> with the following code.
<pre class="brush: java;">
package org.fluttercode.restwebdemo.bean;

@Stateless
@LocalBean
public class CourseDao {

	@Inject @DataRepository
	private EntityManager entityManager;

	public void save(Course course) {
		entityManager.persist(course);
	}

	public Course update(Course course) {
		return entityManager.merge(course);
	}

	public Course find(Long id) {
		return entityManager.find(Course.class, id);
	}
}
</pre>
<p>This just injects an entityManager and uses it to locate, save and update Course objects.
</li>
<li>Now create a new <code>CourseService</code> bean that will handle the web services. To start with we want to make it a stateless EJB and inject the course Dao. We are going start by re-implementing the method to return the course name for the given id.
<pre class="brush: java;">
	@Path(&quot;courseName/{id}&quot;)
	@GET
	public String getCourseName(@PathParam(&quot;id&quot;) Long id) {
		Course course = courseDao.find(id);
		if (course == null) {
			return &quot;Course not found&quot;;
		} else {
			return course.getTitle();
		}
	}
</pre>
</ol>
<p>To see this method in action, deploy the application and go to <a href="http://localhost:8080/restwebdemo/rest/course/courseName/126">http://localhost:8080/restwebdemo/rest/course/courseName/126</a>. Now we know everything is working and hooked up together, we can look at adding some new functionality. </p>
<p>Let&#8217;s start by returning a course with a given id from the service. This is fairly simple given what we already know. The only thing to determine now is what format to return the object as and to convert it to that type. Luckily, Java EE already provides JAXB which can take an object graph and convert it to XML for us as long as we annotate the classes with the annotations to let the JAXB implementation know how to convert it. The same annotations can be used by the body writer that handles JSON.</p>
<p>First we&#8217;ll annotate the <code>Course</code> class and make a couple of changes that we need to. Next we&#8217;ll create methods to return a <code>Cource</code> object from the service in XML or JSON format.</p>
<ol>
<li>Open the <code>Course</code> class and add the following annotations to the class. </p>
<pre class="brush: java;">
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Course extends BaseEntity {
   ...
   ...
}
</pre>
<p>This tells the JAXB processor that this class can be serialized and to access the values using fields in the class. This also means that any other annotations we want to add to control the serialization needs to be applied to the fields.
</li>
<p>This is a simple example, so we don&#8217;t want to serialize the <code>teacher</code> or <code>enrolled</code> properties which we can do by marking them with the <code>@XmlTransient</code> attributes. Also, remove the <code>@NotNull</code> annotation from the <code>teacher</code> attribute as we will need it blank later. The following code shows the fields with both the JAXB and JPA annotations. JAXB (like JPA) uses default conventions for fields that don&#8217;t have annotations : </p>
<pre class="brush: java;">
	@Column(length = 32, nullable = false)
	@Size(max = 32)
	@NotEmpty(message = &quot;title is required&quot;)
	private String title;

	@Column(length = 8, nullable = false)
	@Size(max = 8  )
	@NotEmpty(message = &quot;code is required&quot;)
	private String code;

	@ManyToOne(fetch = FetchType.LAZY)
	@XmlTransient
	private Teacher teacher;

	@ManyToMany(mappedBy = &quot;enrolled&quot;)
	@XmlTransient
	private List&lt;Student&gt; students = new ArrayList&lt;Student&gt;();
</pre>
<p>We are just using a simple JAXB model for the sake of the example which is why we aren&#8217;t including the <code>Teacher</code> and <code>Student</code> classes.
</li>
<li>Now in our <code>CourseService</code> class we will create methods to return the course entity and we will create one for JSON and one for XML.
<pre class="brush: java;">
	@Path(&quot;find/{id}/xml&quot;)
	@GET
	@Produces(MediaType.APPLICATION_XML)
	public Course getCourseAsXml(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}

	@Path(&quot;find/{id}/json&quot;)
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Course getCourseAsJson(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}
</pre>
</li>
<p><small>(note : At this point, I had to switch to using Hibernate as the JPA provider since JAXB didn&#8217;t like the interface EclipseLink used for proxying the properties. You can do this using the Glassfish update tool).</small><br />
If you redeploy the application and browse to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/json">http://localhost:8080/restwebdemo/rest/course/find/1/json</a> you should be prompted to save a file, or it will display the text, but the content should be something like : </p>
<pre class="brush: plain;">
{&quot;createdOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;id&quot;:&quot;1&quot;,
  &quot;modifiedOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;title&quot;:&quot;Computing for Beginners&quot;,
   &quot;code&quot;:&quot;CS101&quot;}
</pre>
<p>or if you go to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/xml">http://localhost:8080/restwebdemo/rest/course/find/1/xml</a> you will get an XML version :</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;course&gt;
	&lt;createdOn&gt;2010-08-27T16:36:57.015-04:00&lt;/createdOn&gt;
	&lt;id&gt;1&lt;/id&gt;
	&lt;modifiedOn&gt;2010-08-27T16:36:57.015-04:00&lt;/modifiedOn&gt;
	&lt;title&gt;Computing for Beginners&lt;/title&gt;
	&lt;code&gt;CS101&lt;/code&gt;
&lt;/course&gt;
</pre>
<p>Now we can grab objects from our web service, we should look at creating objects from the service. We add a new method that takes the title and code values, creates a new <code>Course</code> with those values and saves it using the <code>courseDao</code>.</p>
<pre class="brush: java;">
	@Path(&quot;create&quot;)
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	public Course createCourse(@FormParam(&quot;title&quot;) String title,@FormParam(&quot;code&quot;) String code) {
		Course course = new Course();
		course.setTitle(title);
		course.setCode(code);
		courseDao.save(course);
		return course;
	}
</pre>
<p>Here I&#8217;ve used the <code>FormParam</code> annotations to plug form values into the method call. You&#8217;ll notice that using REST conventions, the method to create a course uses the PUT type of request. Now let&#8217;s create a page to enter a title and code and create the course. Notice that our method returns the created course so we can return the course back to the user. This is probably not ideal, but suits for the purposes of demonstration. Now lets create a new HTML page to allow for data entry and calling the web service to create the Course.</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot;
	src=&quot;http://localhost:8080/restwebdemo/jquery-1.4.min.js&quot;&gt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;message&quot;
	style=&quot;display: none; background: #d0d0f0; padding: 12px&quot;&gt;Message Div&lt;/div&gt;
&lt;form action=&quot;rest/course/create&quot; method=&quot;POST&quot;&gt;

    &lt;fieldset&gt;
    	&lt;legend&gt;Create Course&lt;/legend&gt;
    	&lt;p&gt;
	        Title&lt;br /&gt;
    	    &lt;input id=&quot;title&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;p&gt;
        	Code&lt;br /&gt;
        	&lt;input id=&quot;code&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;input type=&quot;submit&quot; id=&quot;submit&quot; /&gt;
	&lt;/fieldset&gt;
&lt;/form&gt;
&lt;/body&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

//jquery pieces
$(document).ready(function() {

    //change the submit button behaviouus.
    $('#submit').click(function () {
		var title = $(&quot;input#title&quot;).val();
		var code = $(&quot;input#code&quot;).val();

		params = &quot;title=&quot;+title+&quot;&amp;code=&quot;+code;
		//alert(&quot;posting form : &quot;+data);
        $.ajax({
               type: &quot;PUT&quot;,
               url: &quot;rest/course/create&quot;,
               data: params,
               success: function(result) {
        		   showMessage(&quot;Created Course &quot;+result.title+&quot; with id &quot;+result.id+&quot; on &quot;+result.createdOn);
               }
        });
		return false;
    });
});

function showMessage(msg) {
	  $('#message').html(msg);
	  $('#message').fadeIn('fast');
	   $('#message').delay(3000).fadeOut('slow');
}
&lt;/script&gt;
&lt;/html&gt;
</pre>
<p>This looks a lot code, but not really. We import jquery to help us post our form, and we create our form with the two fields. We use JQuery to add an event handler so when you click submit, it packages up the form, calls our web service with a PUT type of request and grabs the returned object as a JSON object, and displays a message using the values from the new instance obtained from the server. To verify that your course has been created, go to the <a href="http://localhost:8080/restwebdemo/home.jsf">front page</a> and you should see it listed.</p>
<p>That about wraps it up for this post, the source code can be downloaded from (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>), just unzip it, use <code>mvn clean package</code> and deploy the war to glassfish and use the URLs mentioned in the article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/feed/</wfw:commentRss>
		<slash:comments>0</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>Shrinkwrap DSLs Makes Building Config Files Easy</title>
		<link>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/</link>
		<comments>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 13:22:08 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Arquillian]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Shrinkwrap]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1720</guid>
		<description><![CDATA[If you&#8217;ve used Shrinkwrap you might have noticed that creating configuration files can be a bit of a burden requiring you to manually build XML configuration files yourself as strings. This article shows how the DSLs being added to Shrinkwrap will make configuring your deployments far easier. I&#8217;m not sure on the current status of [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve used <a href="http://community.jboss.org/wiki/ShrinkWrap">Shrinkwrap</a> you might have noticed that creating configuration files can be a bit of a burden requiring you to manually build XML configuration files yourself as strings. This article shows how the DSLs being added to Shrinkwrap will make configuring your deployments far easier.<br />
<span id="more-1720"></span><br />
I&#8217;m not sure on the current status of the DSL project, but you can find it on GitHub on the <a href="https://github.com/shrinkwrap/descriptors">shrinkwrap / descriptors</a> page. These are still in development, but as they are fairly stand-alone, they work well enough to use. To get started, download the maven project from the GitHub page, build and install it.</p>
<p>The descriptors project contains classes implementing DSLs for creating configuration files that can be exported to text. These files can then be added to the Shrinkwrap archive. Here&#8217;s a basic example that adds a <code>beans.xml</code> for CDI support.</p>
<pre class="brush: java;">
// first create the descriptor
BeansDescriptor bd = Descriptors.create(BeansDescriptor.class);

// add alternatives classes
bd.alternativeClasses(EmailEventHandler.class, LogEventHandler.class)
.decorator(BillingProcessorDecorator.class);// add decorator classes

System.out.println(bd.exportAsString());
</pre>
<p>Produces a result of </p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;beans xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans1_0.xsd&quot;&gt;
    &lt;decorators&gt;
        &lt;class&gt;org.demo.beans.BillingProcessorDecorator&lt;/class&gt;
    &lt;/decorators&gt;
    &lt;alternatives&gt;
        &lt;class&gt;org.demo.EventHandlers.EmailEventHandler&lt;/class&gt;
        &lt;class&gt;org.demo.EventHandlers.LogEventHandler&lt;/class&gt;
    &lt;/alternatives&gt;
&lt;/beans&gt;
</pre>
<p>First you must get an instance of the descriptor which is the basis for the dsl, and then you can define the properties for the descriptor using the methods defined on it, chaining the calls as needed.</p>
<p>Another example uses the <code>PersistenceDescriptor</code> and can be used to create <code>persistence.xml</code> files :</p>
<pre class="brush: java;">
PersistenceDescriptor pd = Descriptors.create(PersistenceDescriptor.class);

pd.persistenceUnit(&quot;myUnit&quot;)
		.classes(Person.class, User.class)
		.description(&quot;Default Persistence Unit&quot;)
		.formatSql()
		.schemaGenerationMode(SchemaGenerationModeType.CREATE_DROP)
		.jtaDataSource(&quot;java:/DefaultDS&quot;)
		.property(&quot;hibernate.cache.provider_class&quot;,&quot;org.hibernate.cache.HashtableCacheProvider&quot;)
		.version(&quot;2.0&quot;);

		System.out.println(pd.exportAsString());
</pre>
<p>Produces : </p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;persistence xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; version=&quot;2.0&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd&quot;&gt;
    &lt;persistence-unit name=&quot;myUnit&quot;&gt;
        &lt;description&gt;Default Persistence Unit&lt;/description&gt;
        &lt;jta-data-source&gt;java:/DefaultDS&lt;/jta-data-source&gt;
        &lt;class&gt;org.demo.model.Person&lt;/class&gt;
        &lt;class&gt;org.demo.model.User&lt;/class&gt;
        &lt;properties&gt;
            &lt;property name=&quot;hibernate.format_sql&quot; value=&quot;true&quot;/&gt;
            &lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create-drop&quot;/&gt;
            &lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;drop-and-create-tables&quot;/&gt;
            &lt;property name=&quot;hibernate.cache.provider_class&quot; value=&quot;org.hibernate.cache.HashtableCacheProvider&quot;/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<p>The project also supports importing configuration files to the associated description type since the descriptors are modeled using JAXB XML bindings. At the moment the following descriptor types are supported : </p>
<ul>
<li><b>web.xml</b> &#8211; Web deployment descriptor file</li>
<li><b>persistence.xml</b> &#8211; JPA Persistence config file</li>
<li><b>faces-config.xml</b> &#8211; Configuration file for Java Server Faces</li>
<li><b>beans.xml</b> &#8211; Triggers the use of CDI and can contain configuration info</li>
</ul>
<p>While the goal is to use these to help generate Shrinkwrap archives, particularly for Arquillian testing, there&#8217;s nothing wrong with using them to automatically generate configuration files, especially for new projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JBoss Java EE 6 spec dependency in Maven</title>
		<link>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 13:52:47 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1733</guid>
		<description><![CDATA[Adam Bien wrote about the Troubled with the crippled Java EE 6 APIs in Maven and a solution for them. Another solution has presented itself now that JBoss has finalized the Java EE 6 spec pom and added it to their public repositories as of early January 2011. You can include the spec in your [...]]]></description>
			<content:encoded><![CDATA[<p>Adam Bien wrote about the <a href="http://www.adam-bien.com/roller/abien/entry/trouble_with_crippled_java_ee">Troubled with the crippled Java EE 6 APIs in Maven</a> and a solution for them. Another solution has presented itself now that JBoss has finalized the Java EE 6 spec pom and added it to their public repositories as of early January 2011.</p>
<p>You can include the spec in your own project by adding the following to your <code>pom.xml</code> :</p>
<pre class="brush: xml;">
&lt;dependency&gt;
	&lt;groupId&gt;org.jboss.spec&lt;/groupId&gt;
	&lt;artifactId&gt;jboss-javaee-6.0&lt;/artifactId&gt;
	&lt;version&gt;1.0.0.Final&lt;/version&gt;
	&lt;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
</pre>
<p>You may also need to add the JBoss repository to your <code>pom.xml</code> which is defined as :</p>
<pre class="brush: xml;">
&lt;repositories&gt;
	&lt;repository&gt;
		&lt;id&gt;repository.jboss.org&lt;/id&gt;
		&lt;name&gt;JBoss Repository&lt;/name&gt;
		&lt;url&gt;http://repository.jboss.org/nexus/content/groups/public-jboss/&lt;/url&gt;
	&lt;/repository&gt;
&lt;/repositories&gt;
</pre>
<p>I&#8217;ll be adding this pom to the Knappsack archetypes to resolve some of the issues people have been facing with the broken spec dependency.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/feed/</wfw:commentRss>
		<slash:comments>2</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>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>Considering Thick Client Javascript Applications</title>
		<link>http://www.andygibson.net/blog/article/considering-thick-client-javascript-apps/</link>
		<comments>http://www.andygibson.net/blog/article/considering-thick-client-javascript-apps/#comments</comments>
		<pubDate>Wed, 10 Nov 2010 13:34:06 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[soa]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1617</guid>
		<description><![CDATA[A post on Javalobby (Are Serverside Web Frameworks Becoming Irrelevant?) got me thinking again about javascript based web apps also called SOFEA or SOUI applications. While I don&#8217;t believe that the end is near for server side frameworks, (after all a similar post was written 3 years ago), I think it there is a growing [...]]]></description>
			<content:encoded><![CDATA[<p>A post on Javalobby (<a href="http://java.dzone.com/news/are-serverside-web-frameworks">Are Serverside Web Frameworks Becoming Irrelevant?</a>) got me thinking again about javascript based web apps also called SOFEA or SOUI  applications. While I don&#8217;t believe that the end is near for server side frameworks, (after all a <a href="http://raibledesigns.com/rd/entry/sofea_also_known_as_soui">similar post</a> was written 3 years ago), I think it there is a growing interest in these development models.</p>
<p>Now and again I take a look at javascript based client side web development interacting with web services since the notion of a thick, rich client using distributed stateless reusable web services  that can just be deployed off into the cloud can be very alluring.<br />
<span id="more-1617"></span><br />
In practice though, I generally find problems with the essential basics.  Data binding is still immature, and I have doubts about using a single page interface for something more complex than Facebook, GMail or google search pages, not to mention having to code your own browser history.</p>
<p>In other examples, the list of items was rendered in the page, and upon completing some Ajaxy action, the HTML for the extra item was added to the list in a separate piece of code. Such practices, which I would imaging are fairly common in these kind of frameworks, are just begging to be a maintenance nightmare (DRY anyone?). You could write some javascript method to render the item in the page and use it in both places, but that seems to defy the syntactic sugar these frameworks target.</p>
<p>There still seems to be some debate as to whether the server side methods are supposed to return XML, JSON or plain HTML. If you return HTML, you may as well stick with a server side framework since that&#8217;s where the view layer is still coming from. JSON and XML could make for an interesting development model especially since there is already a lot of support for them. (I planning on a post about Java EE 6 web services returning XML and JSON soon).</p>
<p>I still believe server side component frameworks are the way to go for now. People don&#8217;t want to be hand coding moving data values around and micro-managing HTML any more than they want to be pushing values around in CPU registers in assembly language. *Something* (akin to the controller) needs to mediate between the back end and the UI layers, currently, that something resides at the front of the server side. Could it possibly reside on the client? Maybe. </p>
<p>Taking the quote &#8220;<a href="http://www.joelonsoftware.com/items/2005/10/17.html">Google uses Bayesian filtering the way Microsoft uses the if statement</a>&#8221; and applying it to frameworks, Component frameworks uses pagination controls the way other frameworks use page parameters. They just operate at a higher level of abstraction that makes development much faster without requiring the application framework generate most of the content (i.e. Rails, Grails). </p>
<p>Another (easily resolved) criticism is that the UI needs to know about the data model in order to know what data to fetch. For example, loading a person and knowing to include the phone and address as well for the person details page. Other times though, you will want just the person instance and their name to display them. This is also a problem for server side frameworks, but the logic to deal with it is on the server as well so it&#8217;s still able to load that data. Once it has shuttled off to the client, there&#8217;s no ability to lazily load. </p>
<p>On the other hand, this problem gives you the opportunity to introduce a more interesting way of dealing with the data model. You could have a very decoupled data model by using multiple data requests to fetch the data needed for the page. First you load the basic person instance, then make separate requests to fetch an address for a person and then their phone number as they are needed in the page. I remember an interview with <a href="http://www.allthingsdistributed.com/">Werner Vogels</a>, CTO of Amazon.com claiming.</p>
<blockquote><p>&#8220;If you hit one of Amazon&#8217;s pages, it goes out to between 250 and 300 services to build that page.&#8221;</p></blockquote>
<p>  The interview itself is quite an interesting read for those interested in SOA  (<a href="http://www.informationweek.com/news/global-cio/interviews/showArticle.jhtml?articleID=212501404">Amazon CTO Werner Vogels</a>). The notion of a very decoupled data model is again rather alluring. </p>
<p>One of my personal problems when looking at most of this technology is that I can&#8217;t help but think how much easier and less convoluted it is to do similar things with JSF and CDI or how lacking it is in terms of features.  In the back of my mind, the specters of more complex use cases (i.e. multi-page state management, or pages using multiple pagination) cast doubts that these frameworks will be able to be as usable as other frameworks. This probably curtails my ability to experience the benefits of such frameworks and gain enough knowledge to tackle some of the thornier issues leaving me safely in my comfort zone. I also find most excitement over new technology misplaced as people mistake a compact and concise technology for one with a a lack of features.<br />
In the end though, with the Google App Engine, Amazons Web Services, Spring&#8217;s cloud efforts, and the focus on cloud based solutions, it is a programming model that well supported and attractive enough to developers that it will probably mature well and is no doubt worth looking at.</p>
<p>Feel free to post in the comments which libraries you are using for the view and server side layers that might be worth taking a look at.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/considering-thick-client-javascript-apps/feed/</wfw:commentRss>
		<slash:comments>1</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>
	</channel>
</rss>

