Sunday, January 17, 2010

Shopping Cart Web Application - Play Framework

 Shopping Cart Application – Play Framework

I recently spent time stepping through the yabe (yet another blog engine) tutorial for the Play Framework.

"The Play framework makes it easier to build Web applications with Java"


What is Play?
Play is a full stack open source web framework for Java that focuses on developer productivity.

"The Play framework compiles your Java sources directly and hot-reloads them into the JVM without the need to restart the server. You can then edit, reload and see your modifications immediately"


Why Play?
There are a number of reasons why the Play framework is cool and I highly recommend you take a look at it: 5 cool things you can do with Play. The one that caught my eye was that the Play framework eliminates the time spent in compiling Java source files, packaging the code into an archive and then deploying that archive to a server. Already I am hooked. This is great! For something similar to this for JEE development take a look at JRebel. Depending on which license you get you may have to pay a fee.

Shopping Cart
In an effort to learn more I decided to build my own Play web application based on the very basic Shopping Cart application I have used in the past.

Here are a few comparisons between the original Shopping Cart web application and this one written for the Play framework:

1. JPA
The Play framework supports JPA so there really isn’t any difference with the entity classes in the domain model.

2. Spring
In the original application I was mainly using Spring for dependency injection. I didn’t need to use Spring in my application but the Play framework supports Spring as well as dependency injection (in version 1.0.1).

3. JSF Components vs HTML
The original application used JSF to build the GUI interface whereas Play uses plain HTML. There are many different JSF components to choose from and you can use additional JSF component libraries besides the standard components that come with JSF such as RichFaces / ICEfaces and many more. With very little effort you can include a JSF component within your page and bind it to a Java class. It is all very cool for a Java developer who wants a nice looking website without hiring a web developer to do it for them. However there are a few drawbacks to this approach, some of the main ones being:

  • The JSF components render down to HTML and JavaScript. You have no real control over how the rendering takes place. You could be rendering a HTML table whereas you would prefer to use a DIV.
  • Some JSF components reference custom JavaScript files. These JavaScript files could be quite large and you may not even be referencing them but because they form part of the JSF library you automatically reference it. 
  • Not that easy to change the behaviour of the JSF components to do something that it was never designed to do.

The Play framework uses standard HTML as well as its own template engine. The drawbacks for a Java developer is there are no drag and dropping of components into a JSP page. However if you’re a web developer you would most likely prefer to work with plain HTML files. You have more control over your page and there are 100’s of CSS / JavaScript libraries you can pull into your project without much hassle.

4. AJAX
The original project used a very cool JSF library called RichFaces. RichFaces has many ‘rich’ components to choose from with built in Ajax support.

I used JQuery to do all the Ajax requests and responses in the Play framework. JQuery is a very powerful JavaScript library. However you are not forced to use it, you could just as easily do it with your own JavaScript or another library that offers similar functionality.

5. JUnit
Both the original application and Play use JUnit as the test framework. The Play framework has a couple of nice utilities you can use and comes with a test suite out of the box to run all your tests from.

That’s all I wanted to say on that, the Play documentation is quite good, for a taste of what you can do I highly recommend the yabe tutorial and they have an active forum for any questions.

Saturday, January 9, 2010

Shopping Cart Web Application - Part 7 - TopLink and EAR

I recently received a response from someone who was stepping through my Shopping Cart Web Application tutorial and who wanted to deploy the application on GlassFish and use TopLink Essentials (EclipseLink) as the reference implementation for JPA as opposed to Hibernate.

Thankfully there wasn't that much change that needed to be made to the existing ShoppingCartHibJpaPart7 application. This application (ShoppingCartTopLinkJpaPart7.zip) is available to download in case anyone would like to take a look. I chose to use EclipseLink which is the successor to TopLink. In order to get it working with GlassFish 2.0 there are a few simple steps to take. The biggest change I needed to make was in the persistence.xml file:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">

 <persistence-unit name="shopping-cart"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
  <non-jta-data-source>jdbc/__shoppingcart</non-jta-data-source>
  <exclude-unlisted-classes>false</exclude-unlisted-classes>
  <properties>
   <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
   <property name="eclipselink.logging.level" value="FINE" />
  </properties>
 </persistence-unit>
</persistence>
The real difference here is the use of EclipseLink properties as opposed to Hibernate properties. I also had to define the non-jta-data-source attribute. Another one of the requirements was to have GlassFish manage the database connections so my application needed to be configured to lookup the resource via the datasource JNDI name.

Java Transaction API  (JTA) inside a web application
After doing this I was asked if I could change the transaction type from RESOURCE_LOCAL to JTA. In order to do this I made the following changes:

I changed the value of the transaction-type in the persistence.xml file from RESOURCE_LOCAL to JTA and changed the non-jta-data-source attribute to jta-data-source.

Secondly I needed to do a JNDI lookup for the EntityManager managed by the container, one way is to do it by annotation on the Dao class:

@PersistenceContext(name="persistence/ShoppingCart", unitName="shopping-cart")
public class BasketDaoImpl implements BasketDao {

and then the lookup:

Context ctx = new InitialContext();
em =  (EntityManager) ctx.lookup("java:comp/env/persistence/ShoppingCart");

Our application is managing the transaction however in a JTA entity manager entityManager.getTransaction() calls are not permitted so instead I needed to get a UserTransaction by doing a JNDI lookup for the UserTransaction:

Context ctx = new InitialContext();
(UserTransaction)ctx.lookup("java:comp/UserTransaction");

If you are interested in seeing how I implemented this you can download the ShoppingCartJtaTopLinkJpaPart7.zip file and view the DAO classes in the shopping-cart-core-jta-toplink-jpa-part7 project.

BasketDaoImpl.java
@PersistenceContext(name="persistence/ShoppingCart", unitName="shopping-cart")
public class BasketDaoImpl implements BasketDao {

  public Basket updateBasket(Basket basket) throws Exception {
    EntityManager em = null;
    UserTransaction utx = null;
    try {
      em = JPAUtil.getEntityManager();
      utx = JPAUtil.getUserTransaction();
      utx.begin();
      basket = em.merge(basket);
      utx.commit();
      return basket;
    } catch (RuntimeException e) {
      if (utx != null) {
        utx.rollback();
      }
      throw e;
    }
  }

Java Transaction API  (JTA) inside a JEE application
In this example our application is going to make use of an EJB session bean. Unlike in the previous example where our application was controlling the transaction via the UserTransaction class here the container will manage and control the transaction for us. Once again you can download the full source of the ShoppingCartEJBTopLinkJpaPart7.zip file and take a look at what I did.

Using JEE annotations it was very simple to turn the ShoppingManager class into a session bean. The @PersistenceContext annotation was used to obtain an EntityManager instance and you will also notice I got rid of the DAO classes as there really was no need for them anymore as the container manages the transaction.

ShoppingManager.java
@Stateless(name="ShoppingManager")
public class ShoppingManager implements ShoppingService {

  @PersistenceContext(unitName="shopping-cart")
  private EntityManager em;

  public Basket updateBasket(Basket basket) throws ShoppingException {
    try {
      return em.merge(basket);
    } catch (Exception e) {
      logger.error("There was an error updating the basket, exception: " + e);
      throw new ShoppingException("There was an error updating the basket", e);
    }
  }

All these applications were written in Eclipse and tested in a GlassFish 2.0 application server.

Monday, December 21, 2009

WebSphere JMS Sample Application

My previous blog I outlined the steps required to configure JMS resources for WebSphere Application Server 7.0. In that blog I promised to put together a sample application that can be installed to WebSphere Application Server and demonstrates three different implementations of sending JMS messages to a queue and retrieving the messages from a queue. The sample application is an Eclipse project interchange file. If you have Rational Application Developer installed on your computer you should be able to import this project into your workspace without too much hassle. Alternatively you can always use your favourite decompression tool to extract the contents to your local drive and then view the source from there.

Below are two diagrams describing the JMS runtime resources configured for the sample application:

Programmatic / Spring implementation



EJB3 implementation



Web client
To test the application I created a very simple web application that is used to trigger the sending of a JMS text message to a queue as well as to retrieve the message from the queue. I decided to use the Spring MVC  web framework to keep things simple. Below is a screen shot of the jms-tester web page:




Wednesday, December 9, 2009

WebSphere SIB, JMS queues and connection factory configuration

I was recently given a task to migrate an enterprise application that was running on SAP NetWeaver across to WebSphere application server. The application had a few session beans as well as a few message-driven beans. It used JMS to publish messages to a number of queues. This blog entry outlines the steps I took to configure the JMS queues and connection factories on WebSphere. It is pretty plain and boring but is really for my own benefit to be used as a reference and who knows maybe if you are reading this it may come in handy as well.

The following configurations were done on a single server of WebSphere application server 7.0. It assumes that the user is logged into the administration console and where global security has been enabled:

Create J2C authentication user
  • Security -> Global security -> Expand Java Authentication and Authorization Service -> J2C authentication data -> New
  • Enter in the following values:
    • Alias: myusr
    • User ID: myusr
    • Password: myusr
  • Click the OK button
  • Save to the master file configuration

Create group
  • Users and Groups -> Manage Groups -> Create
  • Enter in the following values:
    • Group name: mygrp
  • Click on the Group Membership button
  • Add the mygrp
  • Click the close button

Create user
  • Users and Groups -> Manage Users -> Create
  • Enter in the following values:
    • User ID: myusr
    • First name: Myusr
    • Last name: Mysurname
    • Password: mypassword
    • Confirm password: mypassword
  • Click on the Group Membership button
  • Click the Search button
  • Add the mygrp
  • Click the Close button
  • Click the Create button

Create SIB
  • Service integration -> Buses -> New
  • Bus Name: my_bus
  • Bus Security: enabled
  • Press next to enter the security wizard
  • Complete the wizard by accepting all the defaults
  • Save your changes by clicking the save link

Configure Authorization for the SIB
  • Service integration -> Buses
  • Select the Enabled link for the my_bus
  • [Authorization Policy] -> Users and groups in the bus connector role -> New
  • Enable Groups radio button and click the Next button
  • Select the mygrp checkbox and then the Next button
  • Click the OK button
  • Save to the master file configuration

Create Bus member for SIB
  • Service integration -> Buses -> my_bus -> [Topology] Destinations -> Bus members -> Add button
    • Enable the server radio button
  • Click the Next button
    • Enable the File store radio button
  • Finish the wizard by accepting all defaults
  • Save to the master file configuration

Create destinations for SIB
  • Service integration -> Buses -> my_bus -> [Destinations resources] Destinations -> New
  • Type: Queue
  • Next
  • Identifier: myFirstD
  • Select the bus member you created in the previous step
  • Finish the wizard by accepting all defaults
  • Save to the master file configuration

Configuring authorization on queue destinations
Optional because already has AllAuthenticated by default however it is recommended to remove this and add your own
  • Service integration -> Buses
  • Select the Enabled link for the my_bus
  • [Authorization Policy] -> Manage destination access roles
  • Select the myFirstD destination
  • Select the Add button
  • Enable Groups radio button and click the Next button
  • Select the mygrp checkbox and then the Next button
  • Check the Sender, Receiver and Browser checkboxes
  • Click the Finish button
  • Click the OK button
  • Save to the master file configuration

Create Connection Factory (Can also create Queue / Topic Connection Factory in a similar way)
  • Resources -> JMS -> Connection factories -> select server scope from the drop down list -> New
  • Default messaging provider -> Next
  • Enter in the following values:
    • Name: MyConnectionFactory
    • JNDI name: jms/MyConnectionFactory
    • Bus name: my_bus
    • Container-managed authentication alias: myusr
  • Click the OK button
  • Save to the master file configuration

Create JMS Queues (Can also create Topics in a similar way)
  • Resources -> JMS -> Queues -> select server scope from the drop down list -> New
  • Select the Default messaging provider radio button
  • Click the OK button
  • Enter in the following values:
    • Name: myFirstQ
    • JNDI name: jms/myFirstQ
    • Bus name: my_bus
    • Queue name: myFirstD
  • Select the OK button
  • Save to the master file configuration

Create Activation specifications
  • Resources -> JMS -> Activation specifications -> select server scope from the drop down list -> New
  • Select the Default messaging provider radio button
  • Click the OK button
  • Enter in the following values:
    • Name: myFirstSpec
    • JNDI name: eis/myFirstSpec
    • Destination type: Queue
    • Destination JNDI name: jms/myFirstQ
    • Bus name: my_bus
    • Authentication alias: myusr
  • Select the OK button
  • Save to the master file configuration

That's all there is to it. The next step will be configuring you application's resources and assigning them the correct authentication methods. I will describe those steps in my next blog along with a sample application.

Saturday, November 7, 2009

Scala – Transition from Java to Scala - My initial experience and thoughts

A couple of months ago I was given a task at work that required code to be written in Scala. At first I wasn't so thrilled about the fact that I would be learning a new language but I must say after spending some time with it I am glad I did. The hardest part in learning Scala was the "getting started" part. The syntax of the Scala code is very different from Java and it required me to "concentrate" and to think a little before I could start my very first "Hello World" application…as you can see I wasn't very motivated. The sample applications were also a little difficult to follow because I wasn’t familiar with the syntax it required a lot more thinking and a lot more concentration…sigh…yeah like I said in the beginning I wasn't very motivated. However having spent a couple of months programming in Scala I am a lot more familiar with the syntax and believe it or not  the code has become a lot more readable, a lot more flexible and more desirable to write than Java code. I am amazed at how much you can do with so little effort.

It doesn't take too much effort for somebody who is a Java programmer to learn Scala. Like I said in the beginning the hardest part for me was getting started but after that I became excited about what I could do with this language and I became motivated to learn more. Scala compiles to Java byte code and runs on the Java VM. You can reference existing Java libraries in your code and make full use of their classes. Scala pretty much does everything Java does but on top of that it offers a whole lot more. I am also enjoying learning other programming concepts and techniques. Scala is an object-oriented and functional programming language. I am learning a lot about functional programming and I have started thinking differently about how I can use these techniques and concepts to produce better code.

So if you are interested in learning Scala and come from a Java programming background like me than I would recommend the following links:

There are also a number of open source projects written in Scala and I would recommend anyone getting started to download the projects and take a look at the source code. Below are a few I have come across and learnt from:
  • Lift - Scala web framework
  • TalkingPuffin - Twitter client
  • Scalaffinity - library containing core functionality used by any social networking web site

Tuesday, September 1, 2009

SEAM - The Shopping Cart Web Application

Seam is ANOTHER web application framework. SIGH. Ok yes sigh another framework to learn but it is not entirely new, if you have been following along with the Shopping Cart tutorials where we used JSF, Facelets, Hibernate, JPA and RichFaces you will see that Seam is not something new just something extra.

This is not a tutorial in Seam more like a brief overview, introduction and comparison. Seam's documentation is pretty good to get started with. They also have sample applications so you can have a look to see how Seam is configured. I have also created a Seam web application based on the Shopping Cart application I did in previous posts. It is an Eclipse project. You will need to download the archived file and import it into your Eclipse workbench. I used JDK 1.6. The download is broken up into two parts simply because the file was too big to store on the server on its own:

  • ShoppingCartSeam.zip - This is the main archive that contains all 4 projects.
  • jboss-embedded-all.jar - A library used to run the embedded JBoss server when running our tests. Once you have imported the ShoppingCartSeam.zip archive into your Eclipse workbench please copy this file to the lib folder of the shopping-cart-test project.


Shopping Cart
I will highlight the major differences between the shopping cart application (that I will call Spring Application) we did in previous tutorials with this Seam shopping cart application.

1. Class diagrams
Below you will be able to compare the class diagram of the Spring application with the class diagram of the Seam application.

Spring class diagram


Seam class diagram


2. Spring vs EJB3
The design of our two applications stays pretty much the same, we still have our 3-tier architecture, i.e.
  • Presentation - GUI
  • Application - Business Logic
  • Data - Database

The difference being:
  • In the Spring application we have loosely coupled our application tier from our presentation tier by using Spring to manage and configure how we use and call our business layered objects. The view package contains all the logic for our GUI and is separated from our business logic. Also we use Spring to manage and configure our transactions.
  • In the Seam application we have tightly coupled our application tier to our presentation tier using Seam annotations and EJB3. There is some debate whether this is good or bad, at the end of the day they both have their advantages and disadvantages and it really depends on the type of project you are working on before deciding on which is better or worse. The Seam application uses an EJB3 session bean.

3. EAR vs WAR
The Spring application was packaged as a WAR as it didn’t have any EJB’s there was no need to create an EAR for it. There were two projects:
  • shopping-cart-web – web application
  • shopping-cart-core – project that contains all our business logic classes. It gets packaged as a JAR file and then added to our web application

Because it is packaged as a WAR we also didn’t need a full blown JEE server to deploy it to so Tomcat did the job quite nicely for us.

The Seam application is packaged as an EAR as it makes use of EJB3’s session beans. The project structure that was created for me when I used JBoss Tools to create a Seam project was the following:
  • shopping-cart – main web app
  • shopping-cart-ear – contains 3rd party libraries as well as datasource resource file used to connect to database
  • shopping-cart-ejb – EJB project that contains all our business logic classes (our entity beans and session beans)
  • shopping-cart-test – a standalone project that contains all our test classes

4. Entity classes
Both projects use the Java Persistence API (JPA) in the Entity classes (Basket, Item and BasketItem) to manage relational data and therefore the Entity classes are the same.

5. Faces Managed Beans
In our Spring application we are using the standard JSF library to manage our beans. We define our managed beans and set properties for it in the faces-config.xml file.

In the Seam application we define our managed beans in the beans class by using a Seam annotation (the annotation is called name and occurs just above the class declaration). Only navigational rules are defined in the faces-config file.

6. Web deployment descriptor
The Seam application has an additional filter and servlet defined in the web deployment descriptor, namely:

<filter>
 <filter-name>Seam Filter</filter-name>
 <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>Seam Filter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
 <listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<servlet>
 <servlet-name>Seam Resource Servlet</servlet-name>
 <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>*.seam</url-pattern>
</servlet-mapping>
<servlet-mapping>
 <servlet-name>Seam Resource Servlet</servlet-name>
 <url-pattern>/seam/resource/*</url-pattern>
</servlet-mapping>

7. JSPX vs XHTML
In the Spring application I created .jspx files for our web pages. I would have preferred to use .xhtml but Eclipse didn’t recognize code completion for me and showed that there were warnings when in actual fact there weren’t. I am sure there is some tweak out there to get rid of the warnings and to include code completion but I couldn’t find it and the hassle was not worth the time spent on it. So instead I used .jspx files which worked nicely for me.

In the Seam application I installed the JBoss Tools plugin for Eclipse and .xhtml files seemed to work fine without any errors.

8. Session vs Conversation
Seam introduces two new contexts, conversation and business process. In the Spring application I define the ShoppingViewHelper class with Session scope in the faces-config.xml file.

I could have done the same with the Seam application (by adding another Seam annotation to my class called Scope and given it a value of Session) instead I opted for the better more manageable context provided by Seam called Conversation context.

9. JUnit vs TestNG
In the Spring application we used the JUnit test framework for all our unit tests.

TestNG is another test framework that works the same as JUnit. TestNG is the default test framework chosen by Seam. You are not restricted to TestNG and can can still use JUnit if you like. You can create unit tests just like we did in the Spring application. Seam allows you to create integration tests quite easily to test a complete process from request to response without too much of an overhead. In order to do this Seam uses an embedded JBoss server. The embedded JBoss server is a lightweight server that only starts up the necessary services required to test your application.

Seam application:

The sample application was a really basic one, there is a lot more to Seam than what I touched on here.

Wednesday, August 5, 2009

Shopping Cart Web Application - Part 10 - AJAX

Introduction
Asynchronous JavaScript and XML (AJAX) is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data is retrieved using the XMLHttpRequest object or through the use of Remote Scripting in browsers that do not support it. Despite the name, the use of JavaScript and XML is not required, and they do not have to be used asynchronously

What you need before we get started

What we will cover
  • Advantages of AJAX
  • RichFaces
  • Limitations and rules
  • Shopping cart

Level
  • Beginner

Advantages of AJAX
  • Nice user experience - AJAX gives the user a way to interact with a website without having to wait for lengthy refreshes on a website. Sections of pages can be reloaded individually without having to reload the whole page
  • Less bandwidth used - instead of the full contents of the HTML page being sent to and from the server only the required information is transmitted. The network utilization is minimized and quicker operations occur
  • Limited processing on the server — Users may perceive the application to be faster or more responsive because only the necessary data is sent to the server, the server is not required to process all form elements. By sending only the necessary data, there is limited processing on the server. There is no need to process all form elements, process the viewstate, send images back to the client, and no need to send a full page back to the client

RichFaces 
RichFaces is an open source framework that adds Ajax capability into existing JSF applications without resorting to JavaScript. RichFaces leverages JavaServer Faces framework including lifecycle, validation, conversion facilities and management of static and dynamic resources. RichFaces UI library contains components for adding rich user interface features to JSF applications. Create a modern rich user interface look-and-feel with skins-based technology. RichFaces UI components come ready to use out-of-the-box, so developers save their time and immediately gain the advantage of the mentioned above features in Web applications creation. As a result, usage experience can be faster and easily obtained.

RichFaces allows to define (by means of JSF tags) different parts of a JSF page you wish to update with an Ajax request and provide a few options to send Ajax requests to the server. JSF page doesn't change from a "regular" JSF page and you don't need to write any JavaScript or XMLHTTPRequest objects by hands, everything is done automatically.

  • Ajax Filter - RichFaces uses a filter for a correction of code received on an Ajax request. In case of a "regular" JSF request a browser makes correction independently. In case of Ajax request in order to prevent layout destruction it's needed to use a filter, because a received code could differ from a code validated by a browser and a browser doesn't make any corrections
  • Ajax Action Components - There are Ajax Action Components: <a4j:commandButton>, <a4j:commandLink>, <a4j:poll>, <a4j:support>, etc. You can use them to send Ajax requests from the client side
  • Ajax Containers - AjaxContainer is an interface that describes an area on your JSF page that should be decoded during an Ajax request. AjaxViewRoot and AjaxRegion are implementations of this interface
  • JavaScript Engine - RichFaces JavaScript Engine runs on the client-side. It knows how to update different areas on your JSF page based on the information from the Ajax response. Do not use this JavaScript code directly, as it is available automatically

Limitations and Rules
  • Any Ajax framework should not append or delete, but only replace elements on the page. For successful updates, an element with the same ID as in the response must exist on the page. If you'd like to append any code to a page, put in a placeholder for it (any empty element). For the same reason, it's recommended to place messages in the "AjaxOutput" component (as no messages is also a message)
  • Don't use <f:verbatim> for self-rendered containers, since this component is transient and not saved in the tree
  • Ajax requests are made by XMLHTTPRequest functions in XML format, but this XML bypasses most validations and the corrections that might be made in a browser. Thus, create only a strict standards-compliant code for HTML and XHTML, without skipping any required elements or attributes. Any necessary XML corrections are automatically made by the XML filter on the server, but lot's of unexpected effects can be produced by an incorrect HTML code
  • The RichFaces ViewHandler puts itself in front of the Facelets ViewHandlers chain
  • RichFaces components uses their own renderers. On the Render Response Phase RichFaces framework makes a traversal of the component tree, calls its own renderer and puts the result into the Faces Response

Shopping Cart Application

1. RichFaces Filter
I added the RichFaces filter to the web deployment descriptor:

<filter>
 <display-name>RichFaces Filter</display-name>
 <filter-name>richfaces</filter-name>
 <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
 <filter-name>richfaces</filter-name>
 <servlet-name>Faces Servlet</servlet-name>
 <dispatcher>REQUEST</dispatcher>
 <dispatcher>FORWARD</dispatcher>
 <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

2. RichFaces components
I will only be adding AJAX components to the items.jspx page. The other pages can stay as they are as there isn’t a need to add any AJAX components to them. The first thing I did was add the RichFaces tag library xml namespaces to the items.jspx page. Below is the completed items.jspx page. I you compare it to the previous version you would realize that there is very little change, I just replaced most of the standard JSF components with RichFaces components.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" 
    xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core" 
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich"
    version="2.0">
<ui:composition template="/template.jspx">
 <ui:define name="body">
  <h:outputText id="headingOutTxt" value="#{msg.items_txt_heading}"
   styleClass="headingOutputText" />
  <a4j:form id="itemListFrm">
   <rich:dataTable id="itemsTbl" var="items" value="#{pc_Items.items}"
    binding="#{pc_Items.itemsTable}" styleClass="dataTable"
    columnClasses="dataTableCol1" rowClasses="dataTableRow1"
    headerClass="dataTableHeader">
    <rich:column id="nameCol">
     <f:facet name="header">
      <h:outputText id="nameHeaderOutTxt"
       value="#{msg.items_txt_name_col_header}" />
     </f:facet>
     <h:outputText id="nameOutTxt" value="#{items.name}" />
    </rich:column>
    <rich:column id="descriptionCol">
     <f:facet name="header">
      <h:outputText id="descriptionHeaderOutTxt"
       value="#{msg.items_txt_description_col_header}" />
     </f:facet>
     <h:outputText id="descriptionOutTxt" value="#{items.description}" />
    </rich:column>
    <rich:column id="priceCol">
     <f:facet name="header">
      <h:outputText id="priceHeaderOutTxt"
       value="#{msg.items_txt_price_col_header}" />
     </f:facet>
     <h:outputText id="priceOutTxt" value="#{items.price}">
      <f:convertNumber pattern="#{msg.currency_pattern}" />
     </h:outputText>
    </rich:column>
    <rich:column id="addActionCol">
     <a4j:commandLink id="buyLnk" value="#{msg.items_lnk_buy}"
      action="#{pc_Items.addItemToBasket}" reRender="basketTbl" />
    </rich:column>
   </rich:dataTable>
   <p />
   <h:outputText id="basketOutTxt" value="#{msg.items_txt_basket}" />
   <p />
   <rich:dataTable id="basketTbl" var="basketItem" styleClass="dataTable"
    columnClasses="dataTableCol1" rowClasses="dataTableRow1"
    value="#{shoppingViewHelper.basket.basketItems}"
    binding="#{pc_Items.basketTable}">
    <rich:column id="basketItemCol">
     <f:facet name="header">
      <h:outputText id="basketTblHeaderOutTxt"
       value="#{msg.items_txt_basket_item_col_header}" />
     </f:facet>
     <h:outputText id="basketItemOutTxt" value="#{basketItem.item.name}" />
    </rich:column>
    <rich:column id="basketItemQuantityCol">
     <f:facet name="header">
      <h:outputText id="basketTblQuantityOutTxt"
       value="#{msg.items_txt_basket_quantity_col_header}" />
     </f:facet>
     <h:outputText id="basketItemQuantityOutTxt" value="#{basketItem.quantity}" />
    </rich:column>
    <rich:column id="basketItemPriceCol">
     <f:facet name="header">
      <h:outputText id="basketTblPriceOutTxt"
       value="#{msg.items_txt_basket_price_col_header}" />
     </f:facet>
     <h:outputText id="basketItemPriceOutTxt" value="#{basketItem.price}" />
    </rich:column>
    <rich:column id="removeActionCol">
     <a4j:commandLink id="removeLnk" value="#{msg.items_lnk_remove}"
      action="#{pc_Items.removeItemFromBasket}" reRender="basketTbl" />
   </rich:column>
   </rich:dataTable>
   <p />
   <h:commandButton id="checkoutBtn" value="#{msg.btn_checkout}"
    action="#{pc_Items.checkout}" />
   <rich:messages errorClass="errorText" /> 
  </a4j:form>
 </ui:define>
</ui:composition>
</jsp:root>

3. Items backing bean
There are two very small changes we need to make to the Items backing bean (Items.java). Our itemsTbl datatable and our basketTbl datatable are bound to javax.faces.component.html.HtmlDataTable objects within our Items.java backing bean. Because our datatables are no longer standard JSF datatables but RichFaces datatables we need to change this binding from a javax.faces.component.html.HtmlDataTable to a org.richfaces.component.UIDataTable.

The end result:



As you can see it was actually pretty simple to get up and running. Please visit the RichFaces demo site to see the full range of RichFaces components in action. You may have to register on their website to view the demo but it is well worth it. Also please read through the RichFaces developers guide . It is very useful reference manual that contains a comprehensive guide to all of the RichFaces components.