Skip to main content

Sample Application using JSF, Spring 2.0, and Java Persistence APIs

Posted by caroljmcdonald on June 19, 2007 at 12:53 PM PDT

Pagination of Data Sets in a Sample Application using JSF, Spring
2.0, and Java Persistence APIs on Glassfish





This Sample Store Catalog app demonstrates the usage of JavaServer
Faces, the new Java Persistence APIs, and Spring 2.0 to implement
pagination. I took this example  href="http://weblogs.java.net/blog/caroljmcdonald/archive/2007/05/pagination_of_d.html">Pagination
of Data Sets in a Sample Application using JSF, Catalog Facade
Stateless Session, and Java Persistence APIs  and modified it
slightly to use a Spring Bean instead of a EJB 3.0 Stateless Session
Bean.  If you compare the two, you will see that the code is
almost the same, the main difference is the extra xml configuration for
Spring, and for me it wasn't easy to get the .xml
configuration right. It took looking at several articles, blogs,
examples, and some trial and error to get it working.  (see the
references at the end).

href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555&expandFolder=7555&folderID=0">
download the SpringJPA sample application code

Note: I updated the  Spring  JSF integration part of this
application to use style="font-family: mon;">the
org.springframework.web.jsf.DelegatingVariableResolver
instead
of a  JSF Managed Bean ServiceLocator in order to get a
reference to the CatalogService Spring
Bean from the Spring
application context.


Explanation of the usage of JSF, Spring 2.0 , and Java Persistence
APIs in a sample Store Catalog Application

The image below shows the Catalog Listing page, which allows a user to
page through a list of items
in a store.


listpage.jpg src="http://weblogs.java.net/blog/caroljmcdonald/archive/images/listpage.jpg">



The List.jsp page uses a JSF dataTable
component to display a list of
catalog items



The dataTable component is useful when you want to show a set of
results in a table. In a JavaServer Faces application, the UIData
component
(the superclass of dataTable)  supports binding to a collection of
data objects. It does the
work of iterating over each record in the data source. The HTML dataTable
renderer
displays the data as an HTML table.



In the List.jsp web page the dataTable is defined as shown below: 
(Note: Red
colors
are for Java EE
tags, annotations code, style="color: rgb(0, 0, 153); font-weight: bold;">Blue for style="color: rgb(0, 0, 153); font-weight: bold;">Spring
specific
and Green
for my code
or variables)


Code Sample from:  List.jsp



     
< style="font-weight: bold; color: rgb(204, 0, 0);">h:dataTable style="color: rgb(204, 0, 0);">  style="font-weight: bold; color: rgb(204, 0, 0);">value=' style="font-weight: bold;">#{item. style="color: rgb(0, 102, 0); font-weight: bold;">items style="font-weight: bold;">}'  style="font-weight: bold; color: rgb(204, 0, 0);">var=' style="color: rgb(0, 102, 0); font-weight: bold;">dataTableItem'
border="1"

      cellpadding="2" cellspacing="0">


     

     



The value attribute of a dataTable
tag references the data to be included
in the table. The var
attribute specifies a
name that is used by the components within the dataTable
tag as an alias to the data referenced in the value
attribute of dataTable.  In the dataTable
tag from the

 style="color: rgb(0, 102, 0); font-weight: bold;">List.jsp

page, the value attribute points to a list
of catalog items. The var
attribute points
to a single item in that list. As the UIData
component iterates through the list, each reference to
 style="color: rgb(0, 102, 0); font-weight: bold;">dataTableItem
 points to the current item in the
list.



The dataTable's class="cCode">value

is bound to the
 style="color: rgb(0, 102, 0); font-weight: bold;">items

property
of the
 style="color: rgb(0, 102, 0);">item
controller
class, ItemController style="font-weight: bold;">,
which is defined in the
faces-config.xml file:


Code Sample from: faces-context.xml


 <managed-bean>

    < style="color: rgb(204, 0, 0); font-weight: bold;">managed-bean-name> style="color: rgb(0, 102, 0); font-weight: bold;">item style="font-weight: bold;">

      < style="color: rgb(204, 0, 0); font-weight: bold;">managed-bean-class>

         style="font-weight: bold; color: rgb(0, 102, 0);">sessionpagination.ItemController

     

   
<managed-bean-scope> style="color: rgb(204, 0, 0); font-weight: bold;">session

     
    
     
<managed-property> style="font-weight: bold;">
               
<property-name> style="color: rgb(0, 102, 0);">catalogService
style="font-weight: bold;">
               
     
<value> style="font-weight: bold;">#{ style="color: rgb(0, 102, 0); font-weight: bold;">catalogService style="font-weight: bold;">} style="font-weight: bold;">
          style="font-weight: bold;">


 

     


     

     





This ItemController style="font-weight: bold;"> ManagedBean

 style="color: rgb(0, 102, 0); font-weight: bold;">items

property is defined as shown below:


Code Sample from:
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
style="font-weight: bold;">.java


   
public DataModel
getItems()
{

        if (model==null  ||
index != firstItem){

           
model=getNextItems();

        }

        return this.model;

    }

   

    public DataModel getNextItems()
{      

        model = new style="color: rgb(204, 0, 0); font-weight: bold;">ListDataModel
( style="color: rgb(0, 102, 0); font-weight: bold;">catalogService.getItems(firstItem,batchSize));

        index =
firstItem;      

        return this.model;

    }


     

     





The style="color: rgb(0, 102, 0); font-weight: bold;">getItems()
method wraps a List of item objects, returned from the style="font-family: monospace;"> style="color: rgb(0, 102, 0); font-weight: bold;">catalogService, 
in a style="color: rgb(204, 0, 0); font-weight: bold;">DataModel.


UIData,
the superclass of dataTable,
supports data binding to a
collection of data objects represented by a style="font-family: monospace;"> style="color: rgb(204, 0, 0); font-weight: bold;">DataModel
instance.  The data
collection underlying a DataModel instance is modeled as a collection
of row objects that can be accessed by a row index.  The APIs
provide mechanisms to position to a specified row index, and to
retrieve an object that represents the data that corresponds to the
current row index.   



The Item
properties Name, Photo, and

 style="color: rgb(0, 102, 0); font-weight: bold;">price
  
 style="color: rgb(0, 102, 0); font-weight: bold;">
are
displayed with the
 style="color: rgb(204, 0, 0); font-weight: bold;">column

component:


Code Sample from: List.jsp



  <h:column>

      < style="color: rgb(204, 0, 0); font-weight: bold;">f:facet name=" style="color: rgb(204, 0, 0); font-weight: bold;">header">

          < style="color: rgb(204, 0, 0); font-weight: bold;">h:outputText style="color: rgb(204, 0, 0); font-weight: bold;">value="Price"/>

     

      < style="color: rgb(204, 0, 0); font-weight: bold;">h:outputText style="color: rgb(204, 0, 0); font-weight: bold;">value="#{ style="color: rgb(0, 102, 0); font-weight: bold;">dataTableItem.price}"/>

 


     

     



The column
tags represent columns of data in a UIData
component. While
the UIData component is iterating over the rows of data, it processes
the UIColumn component associated with each column tag for each row in
the table.



The UIData component  iterates through the list
of items
(

 style="color: rgb(0, 102, 0);">item. style="color: rgb(0, 102, 0); font-weight: bold;">items

and displays the
 style="color: rgb(0, 102, 0); font-weight: bold;">dataTableItem.price
.
Each
time UIData iterates through the list of items, it renders one cell in
each column.



The dataTable and column tags use
 style="color: rgb(204, 0, 0); font-weight: bold;">facet

to represent parts of the
table that are not repeated or updated. These include
 style="color: rgb(204, 0, 0); font-weight: bold;">header
s,
footers,
and captions.

href="http://static.springframework.org/spring/docs/1.2.x/reference/webintegration.html">

The  recommended way to integrate Spring with JSF is to
configure the Spring
 style="color: rgb(0, 0, 153); font-weight: bold;">DelegatingVariableResolver

in the
faces-context.xml
style="color: rgb(204, 0, 0);">The
< style="color: rgb(204, 0, 0); font-weight: bold;">application>
<variable-resolver> style="color: rgb(204, 0, 0);">
elements in a faces-config.xml file allows a Faces-based application to
register a custom replacement class for the implementation of the
standard Faces VariableResolver
implementation. The Spring
 style="color: rgb(0, 0, 153); font-weight: bold;">DelegatingVariableResolver
  style="color: rgb(204, 0, 0);">
first delegates to the original resolver of the underlying JSF
implementation, then to the Spring root
WebApplicationContext.  
style="color: rgb(204, 0, 0);">This
allows you to configure Spring Beans as managed properties of your JSF
Managed Beans. For example, below the 
 style="font-weight: bold;">catalogService
style="color: rgb(0, 0, 0);">Spring
Bean
style="color: rgb(0, 0, 0);">is configured as a managed property of the
ItemController
JSF ManagedBean:


Code Sample from: faces-context.xml


 
< style="color: rgb(204, 0, 0);">application>

    <variable-resolver>

      org.springframework.web.jsf.DelegatingVariableResolver

   

 

 <managed-bean>

    <managed-bean-name>item

      <managed-bean-class>

         style="color: rgb(0, 102, 0);">sessionpagination.ItemController

     

   
<managed-bean-scope> style="color: rgb(204, 0, 0);">session

     
    
<managed-property>

         
<property-name> style="color: rgb(0, 102, 0);">catalogService

          < style="color: rgb(204, 0, 0);">value>#{ style="color: rgb(0, 102, 0);">catalogService}

   


 






The catalogService,
and its implementation 

 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO
, 
is defined as a Spring
bean
in the Spring configuration resource file style="color: rgb(0, 0, 153); font-weight: bold;"> style="color: rgb(0, 0, 0);">/ style="color: rgb(204, 0, 0);">WEB-INF style="color: rgb(0, 0, 0);">/applicationContext.xml style="font-style: italic;"> :


Code Sample from: style="color: rgb(0, 0, 153); font-weight: bold;">applicationContext.xml
    

    < style="color: rgb(0, 0, 153); font-weight: bold;">bean style="font-weight: bold;"> style="color: rgb(0, 0, 153); font-weight: bold;">id style="font-weight: bold;">=" style="color: rgb(0, 102, 0); font-weight: bold;">catalogService style="font-weight: bold;">" style="color: rgb(0, 0, 153); font-weight: bold;">class style="font-weight: bold;">=" style="color: rgb(0, 102, 0); font-weight: bold;">service.CatalogDAO style="font-weight: bold;">"/>      style="font-weight: bold;">
        style="font-weight: bold;">
          < style="color: rgb(0, 0, 153); font-weight: bold;">bean name style="font-weight: bold;">=" style="color: rgb(0, 102, 0); font-weight: bold;">itemController style="font-weight: bold;">" class=" style="color: rgb(0, 102, 0); font-weight: bold;">sessionpagination.ItemController style="font-weight: bold;">">

             
<property
name
="
style="color: rgb(0, 102, 0); font-weight: bold;">catalogService style="font-weight: bold;">">

                 
<ref bean="
style="color: rgb(0, 102, 0); font-weight: bold;">catalogService style="font-weight: bold;">"/>

             


          style="font-weight: bold;">
          style="font-weight: bold;">
     


< style="color: rgb(0, 0, 153);">property
name
=" style="color: rgb(0, 102, 0); font-weight: bold;">catalogService style="font-weight: bold;">">
refers to the
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController 
 style="color: rgb(0, 102, 0); font-weight: bold;">setCatalogService
method. style="color: rgb(0, 0, 0);"> The style="color: rgb(0, 0, 153); font-weight: bold;">Spring style="font-weight: bold;"> root
WebApplicationContext will inject the
 style="color: rgb(0, 102, 0); font-weight: bold;">catalogService

Spring Bean
into the
catalogService
property
of the
  style="color: rgb(0, 102, 0); font-weight: bold;">ItemController
JSF
ManagedBean
:


Code Sample from:
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
style="font-weight: bold;">.java


 
public class ItemController
{

     

  private CatalogService catalogService ;

   

  public void style="color: rgb(0, 102, 0); font-weight: bold;">setCatalogService(CatalogService
catalogService) {

        this.catalogService =
catalogService; 

  }



For more information on using JSF with Spring, see href="http://static.springframework.org/spring/docs/1.2.x/reference/webintegration.html">Spring
- Java/J2EE Application Framework Integrating with JavaServer Faces
.


Using the Java Persistence API (JPA) with Spring 2.0

The Spring bean CatalogDAO
uses the Java
Persistence API
EntityManager
Query
object to return a list of items.
The CatalogDAO annotates the field

 style="font-weight: bold;">private  style="color: rgb(204, 0, 0);">EntityManager em;
 
with
 style="font-weight: bold;">@PersistenceContext

, which causes an entity manager to be
injected. (note that using the
 style="color: rgb(204, 0, 0);">
@PersistenceContext
 style="color: rgb(153, 0, 0);"> 
annotation is the same
way an
Entity Manager is injected for a EJB
3.0 Session Bean
.)

 




 
   
     
   
   
     
Code Sample from: CatalogDAO.java


      @Repository style="color: rgb(0, 0, 153); font-weight: bold;">
      @Transactional

public class CatalogDAO
implements CatalogService
{

   

    style="font-weight: bold; color: rgb(204, 0, 0);">@PersistenceContext(unitName="PetCatalogPu")

    private style="color: rgb(204, 0, 0); font-weight: bold;">EntityManager
      em;

     

    public List  style="color: rgb(0, 102, 0); font-weight: bold;">getItems(int
firstItem,int batchSize) {      

       style="color: rgb(204, 0, 0); font-weight: bold;">Query q = style="font-weight: bold;">em.createQuery("select
object(o)
from Item as o");

       q. style="color: rgb(204, 0, 0); font-weight: bold;">setMaxResults(batchSize);

       q. style="color: rgb(204, 0, 0); font-weight: bold;">setFirstResult(firstItem);

       List items=
q.getResultList();

       return
items;      

   }

   

     


The Java Persistence href="http://java.sun.com/javaee/5/docs/api/javax/persistence/Query.html">Query
APIs are used to create and execute queries that can return a
list of results.  The JPA Query interface provides
support for pagination via the setFirstResult() and setMaxResults()
methods:
q. style="color: rgb(204, 0, 0); font-weight: bold;">setMaxResults
(int maxResult)
sets the maximum number of results to retrieve. style="font-family: mon;">
q. style="color: rgb(204, 0, 0); font-weight: bold;">setFirstResult
(int startPosition)
sets the position of the first result to retrieve.

In the code below, we show the

 style="color: rgb(0, 102, 0); font-weight: bold;">Item

entity class which maps to the  ITEM table that stores the
item instances. This is a
typical Java Persistence entity object. There are two requirements for
an entity:

  1. annotating the class with an style="color: rgb(204, 0, 0); font-weight: bold;">@Entity
    annotation.
  2. annotating   the primary key identifier with style="color: rgb(204, 0, 0); font-weight: bold;">@Id

Because the fields name, description.... are basic mappings from the
object fields to columns of the same name in the database table, they
don't have to be annotated.  The O/R  relationships with

 style="color: rgb(0, 102, 0); font-weight: bold;">Address

and Product
are also annotated. For more information on
defining JPA entities see href="http://www.apress.com/book/bookDisplay.html?bID=10093">Pro
EJB 3: Java Persistence API book.



Code Sample from: Item.java


      @Entity

public class Item
implements java.io.Serializable {

     

   
@Id
 style="color: rgb(204, 0, 0); font-weight: bold;">   

    private String itemID;


    private String name;   

    private String description;   

    private String imageurl;   

    private String imagethumburl; 

    private BigDecimal price;

    style="color: rgb(204, 0, 0); font-weight: bold;">@OneToOne style="color: rgb(204, 0, 0);">(cascade={CascadeType.PERSIST})

    private style="color: rgb(0, 102, 0); font-weight: bold;">Address
address;

     
     style="color: rgb(204, 0, 0); font-weight: bold;">@ManyToOne

    private style="color: rgb(0, 102, 0); font-weight: bold;">Product
product;


     

    public Item() { }

     

    public String getItemID() {

       
return itemID;

    }


    public void setItemID(String itemID) {

       
this.itemID = itemID;

   
}


    public String getName() {

       
return name;

    }


    public void setName(String name) {

       
this.name = name;

    }
    

    public String getDescription() {

       
return description;

    }


    public void setDescription(String
description) {

       
this.description = description;

    }


    public BigDecimal getPrice() {

       return
price;

    } 


    public void setPrice(BigDecimal price) {

       
this.price = price;

    }

    public void setAddress(Address address) {

       
this.address = address;

    }

    public Product getProduct() {

        return product;

    }

    public void setProduct(Product product) {

        this.product = product;

    }

     

    ...

}   

     

     







The ItemController
ManagedBean pages through the list of

 style="color: rgb(0, 102, 0); font-weight: bold;">Item
s
by
maintaining the firstItem and batchSize attributes and passing these as
parameters to the
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogService 
 style="color: rgb(0, 102, 0); font-weight: bold;">getItems
(firstItem,
batchSize) method.
The ItemController's
<managed-bean-scope> style="color: rgb(204, 0, 0); font-weight: bold;">
is
defined as
 style="color: rgb(204, 0, 0); font-weight: bold;">session
,
a JSF Managedbean
with session scope will be stored in the session meaning that the
bean's properties will stay alive for the life of the Http Session.





The ItemController
ItemCount 
property is  used to get and display
the number of Catolog
 style="color: rgb(0, 102, 0); font-weight: bold;">item
s
in the  data base on the style="color: rgb(0, 102, 0); font-weight: bold;">List.jsp page:


Code Sample from: List.jsp


<h:outputText
      value="Item
#{item.firstItem +
1}..#{item.lastItem} of

    
#{item.itemCount}"/>

     

     



This

ItemController
 style="color: rgb(0, 102, 0); font-weight: bold;">ItemCount 
property
is defined as shown below:


Code Sample from: ItemController.java


    public int style="color: rgb(0, 102, 0); font-weight: bold;">getItemCount()
{      

        int count = style="color: rgb(0, 102, 0); font-weight: bold;">catalogService.getItemsCount();

        return
count;     

    }

     



The ItemController
getItemCount()
method calls the

 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogService

interface to get
the count of the list of items. The
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO

Spring bean 
 style="color: rgb(0, 102, 0); font-weight: bold;">getItemCount
()
method uses the JPA Query interface to get the count of
all items in the database item table:


Code Sample from: 
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO
.java
public class  style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO
implements CatalogService
{

. . .

     
    public int 
 style="color: rgb(0, 102, 0); font-weight: bold;">getItemCount
()
{

        style="color: rgb(204, 0, 0); font-weight: bold;">Query q =
entityManager.createQuery("select
count(o) from Item as
o");     

        int count =
((Long)q.getSingleResult()).intValue();     
     

        return count;

    }   

    

     



A JSF commandLink
is  used to provide a link to click on to
display the next page of items. The

 style="color: rgb(204, 0, 0); font-weight: bold;">commandLink

tag represents an HTML hyperlink and is rendered as an HTML element. The commandLink
tag is used to submit an style="color: rgb(204, 0, 0); font-weight: bold;">action event
to the application. 


Code Sample from: List.jsp


       
      action="#{ style="color: rgb(0, 102, 0); font-weight: bold;">item.next
}"
value="Next
#{item.batchSize}"

   
rendered="#{item.lastItem + item.batchSize <=
item.itemCount}"/>   

     



This

 style="color: rgb(204, 0, 0); font-weight: bold;">commandLink action
attribute
references the
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController

backing bean
 style="color: rgb(0, 102, 0); font-weight: bold;">next
()
method which calculates
the
next page's first row number  and returns a logical outcome
String, which causes the style="color: rgb(0, 102, 0); font-weight: bold;">List.jsp page
to display the next page's
list .
The ItemController
next
method is defined as shown below:


Code Sample from:
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
.java


   public String  style="color: rgb(0, 102, 0); font-weight: bold;">next() {

       if (firstItem + batchSize
< getItemCount()) {

          
firstItem += batchSize;

       }

       return " style="color: rgb(0, 102, 0); font-weight: bold;">item_list";

   }

     



The JavaServer Faces style="color: rgb(204, 0, 0); font-weight: bold;"> NavigationHandler
matches the logical outcome,  item_list
against the navigation rules in the application configuration resource
file faces-config.xml
to determine which page to access next. In this case, the
JavaServer Faces implementation loads the List.jsp
page after this method returns.


Code Sample from: faces-config.xml


  < style="color: rgb(204, 0, 0);">navigation-rule> style="font-weight: bold;">
           
<navigation-case>
style="font-weight: bold;">
               
<from-outcome>
item_list
 style="font-weight: bold;"> style="font-weight: bold;">
               
<to-view-id>/item/ style="color: rgb(0, 102, 0);">List
.jsp style="font-weight: bold;">
           


       

     

     



A JSF

 style="color: rgb(204, 0, 0); font-weight: bold;">commandLink 
is 
used to provide a link to click on to
display the previous page of items. This
 style="color: rgb(204, 0, 0);">commandLink
action
attribute 
references the 
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
 
prev() method
that
calculates the
previous page's first row number  and returns a logical outcome
String, which causes the List page to display the previous page of
items :


Code Sample from: List.jsp


 commandLink
action="#{item.prev}"
value="Previous
#{item.batchSize}"        

       
rendered="#{item.firstItem >=item.batchSize}"/>

     

     



 This

 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
 
prev()
method  is defined as shown
below: 

 

Code Sample from:
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
.java


    public String  style="color: rgb(0, 102, 0);">prev()
{

        firstItem -= batchSize;

        if (firstItem < 0) {

           
firstItem = 0;

        }

        return "
item_list
";

    }     

     



A JSF ommandLink
is  used to provide a link to click on to
display a page with the

 style="color: rgb(0, 102, 0);">item
details. This 
 style="color: rgb(204, 0, 0);">commandLink
action
attribute 
references The
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController

detailSetup()
method:


Code Sample from: List.jsp


  

      

          value="Name"/>

      


       style="color: rgb(204, 0, 0); font-weight: bold;">commandLink action="#{ style="color: rgb(0, 102, 0); font-weight: bold;">item. style="color: rgb(0, 102, 0); font-weight: bold;">detailSetup}"
value="#{dataTableItem.name}"/>   

  


     



The ItemController
detailSetup()
method  gets the

 style="color: rgb(0, 102, 0); font-weight: bold;">item

data from the
current row of the style="color: rgb(204, 0, 0); font-weight: bold;">dataModel,
and returns a string which causes the
Detail.jsp
page to display
the item details :


Code Sample from:
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController
.java


    public String style="color: rgb(0, 102, 0); font-weight: bold;">detailSetup()
{

        item = ( style="color: rgb(0, 102, 0); font-weight: bold;">Item)
      model.getRowData();

        return " style="color: rgb(0, 102, 0); font-weight: bold;">item_detail";

    }

     



The JavaServer Faces NavigationHandler
matches the logical outcome, 

 style="color: rgb(0, 102, 0); font-weight: bold;">item_detail

against the navigation rules in the application configuration resource
file to determine which page to access next. In this case, the
JavaServer Faces implementation loads the style="font-weight: bold;">Detail.jsp

page after this method returns.


Code Sample from: faces-config.xml
 

          < style="color: rgb(204, 0, 0);">navigation-rule> style="font-weight: bold;">
             
<navigation-case>
style="font-weight: bold;">
                 
<from-outcome>
style="color: rgb(0, 102, 0); font-weight: bold;">item_detail style="font-weight: bold;"> style="font-weight: bold;">
                 
<to-view-id>/item/ style="color: rgb(0, 102, 0);">Detail
.jsp   style="font-weight: bold;">
             


         

   


   



The Detail.jsp uses the

 style="color: rgb(204, 0, 0); font-weight: bold;">outputText

component to display the
 style="font-weight: bold; color: rgb(0, 102, 0);">ItemController

ManagedBean's
 style="font-weight: bold; color: rgb(0, 102, 0);">item

properties:


Code Sample from: detail.jsp
 

   
outputText
value="#{item.item.name}"
title="Name" />

   
title="Description"/>

   


   


   


   
title="Address"/>
 




    alt="detailpage.jpg"
src="http://weblogs.java.net/blog/caroljmcdonald/archive/images/detailpage.jpg"
height="800" width="646">







Conclusion

This concludes the sample application which demonstrates how to work
with the JSF
dataTable
and  style="color: rgb(204, 0, 0); font-weight: bold;">DataModel 
to page through a list
of  Item
Entities
which are retrieved using the style="color: rgb(0, 102, 0); font-weight: bold;">Catalog
methods which use  the
Java
Persistence APIs
with style="color: rgb(0, 0, 153); font-weight: bold;">Spring 2.0.






Setting up the database tables for the
sample application:

  • edit the properties in the SpringJPA\setup\javadb.properties
    file, then run the
    ant script in the directory SpringJPA\setup, or just run the sql in the
    directory
    SpringJPA\setup\sql\javadb with whatever tool you have.

Configuration of the Application
for Spring 2.0, JSF, JPA, running on Glassfish


 To set up glassfish and the netbeans project for Spring, I
modified the steps from  href="http://blogs.sun.com/dochez/page/%2020060127">Spring and
Hibernate in GlassFish
  :

    Setting Things Up:

  • download and extract 
    Spring
      ( I downloaded 2.1).
  • Download
    and install NetBeans 5.5.1
  • href="https://glassfish.dev.java.net/public/downloadsindex.html">Download
    and install GlassFish V1, following the instructions on the download
    page. Alternatively you can use Sun Java System Application Server PE
    9, Sun's GlassFish distribution.
  • Add the Glassfish server to Netbeans:
  • Start NetBeans and switch to the Runtime window (Ctrl+5).
  • Right-click the Servers node and select Add Server.
  • select Sun Java System Application Server (Sun's binary
    distribution of GlassFish).
  • Browse to the location where you installed GlassFish and
    select Finish.

    style="font-weight: bold;">Create the Spring Library in Netbeans:

  • Open the Netbeans Library Manager (Tools menu) and create a new
    library
    called Spring.
  • Add the following jars to the Classpath:
  • dist/spring.jar, dist/weaving/spring-aspects.jar,
    lib/jakarta-commons/commons-logging.jar, lib/log4j/log4j-1.2.9.jar .
  • Set the Sources to the Spring src
    directory.
  • Set the Javadoc to the Spring docs\api
    directory.

    This library is now available for use by any project.

Open and Run the SpringJPA Project

href="http://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555">Download
The SpringJPA application. Unzip the code. From Netbeans do Open
Project
and select the Netbeans project SpringJPA
from the unzipped directory. The SpringJPA application is a
NetBeans Enterprise Application
Project, which is actually comprised of 2 projects: SpringJPA and
SpringJPA-war. SpringJPA-war is a Java EE Module
of the SpringJPA project.  SpringJPA-war generates the war file
and SpringJPA generates the ear file which contains the war.

Open the SpringJPA project. You will
see this dialog when you open the project, because the
Enterprise Application Project stores the absolute location to its
J2EE Modules, you need to configure the location for the SpringJPA-war.



reference_problems
  • Click Close. The SpringJPA project will be in class="style8">bold red.
  • Right click the project and select Resolve Reference Problems
    from the context menu.
  • Use the Resolve Reference Problems dialog to map the
    SpringJPA-war
    module to its
    project, which you'll find is a subdirectory beneath the SpringJPA
    directory .
  • After the references are resolved, right-click the SpringJPA
    project
    and select Open Required Projects (now that the dependencies are
    correct, the SpringJPA-war project will always open with the SpringJPA
    project).
  • There are still additional references problems with the web
    module,  since it references the
    Spring jar files that are needed to build the project.
  • add the new Spring
    library to the SpringJPA-war...

    in the project window under  SpringJPA-war:

    right click on Librairies, Add Library

    Select the Spring Library (that you created above) from the list, then
    click Add Library . This will add the Spring jar files to your
    SpringJPA-war project.
  • All references should now be resolved.  Right-click the
    SpringJPA project and select clean and build project.
  • Press F6 to test run the
    project. NetBeans will build, package, deploy and launch the
    application.



     Creating
your own Netbeans with Spring & Glassfish Project :

  • If you want to create your own application, Create a new
    Netbeans Enterprise Application:
  • In Netbeans  select File New Project, then select
    Enterprise ..Enterprise Application, on the New Enterprise Application
    Window, for Server select Sun Java System Applicaton server,  Java
    EE 5 Version, and Select the Create Web Application Module as shown
    below:

               
      newentapp.jpg src="http://weblogs.java.net/blog/caroljmcdonald/newentapp.jpg"
height="535" width="640">

  • change your Netbeans project properties to add the new Spring
    library...

    in the project window under  your application's war:

    right click on Librairies, Add Library

    Select Spring Library from the list, then click Add Library .
  • to Generate Entity classes from the database tables: In the
    project window, right click on the war, select new File..Persistence
    Entity classes from database.  Click next, then select your
    datasource, tables and create your persistence unit. For more info on
    how to do this try out the following Hands On Lab: href="http://www.javapassion.com/j2ee/#Java_EE_5__EJB_3.0">Java EE 5,
    EJB 3.0, Java Persistence API (JPA)
  • For Spring configuration add the style="color: rgb(0, 0, 153); font-weight: bold;">applicationConfiguration.xml
    and modify the web.xml
    and faces-config.xml
    as described below.

    Configuration of
the XML files for Spring 2.0, JSF, and JPA, running on Glassfish

  •  Add the file style="font-weight: bold;"> style="color: rgb(204, 0, 0); font-weight: bold;">/WEB-INF/ style="color: rgb(0, 0, 153);">applicationContext.xml
    to the war WEB-INF
    directory.  This file is where you define your
    Spring
    service beans
    , and resources. Below is the style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 0, 153);">applicationContext.xml for
    the sample app.  For more information about configuring the Spring
    applicationContext.xml for JPA see this article: href="http://java.sys-con.com/read/366275.htm">Using the Java
    Persistence API (JPA) with Spring 2.0

Code Sample from: applicationContext.xml
  style="color: rgb(0, 0, 153); font-weight: bold;">version="1.0"
encoding="UTF-8"?> style="color: rgb(0, 0, 153); font-weight: bold;">
      xmlns="http://www.springframework.org/schema/beans" style="color: rgb(0, 0, 153); font-weight: bold;">
            
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
style="color: rgb(0, 0, 153); font-weight: bold;">
            
xmlns:aop="http://www.springframework.org/schema/aop"
style="color: rgb(0, 0, 153); font-weight: bold;">
            
xmlns:tx="http://www.springframework.org/schema/tx"
style="color: rgb(0, 0, 153); font-weight: bold;">
            
xsi:schemaLocation="
style="color: rgb(0, 0, 153); font-weight: bold;">
            
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
style="color: rgb(0, 0, 153); font-weight: bold;">
            
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
style="color: rgb(0, 0, 153); font-weight: bold;">
      http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
style="color: rgb(0, 0, 153); font-weight: bold;">
         
     


         
catalogService
"
class="service.CatalogDAO"/>     
     

         
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="dataSource" ref="dataSource"/>
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="loadTimeWeaver">
style="color: rgb(0, 0, 153); font-weight: bold;">
                 
class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
style="color: rgb(0, 0, 153); font-weight: bold;">
             
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="jpaVendorAdapter">
style="color: rgb(0, 0, 153); font-weight: bold;">
                 


                     
class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
style="color: rgb(0, 0, 153); font-weight: bold;">
                     
style="color: rgb(0, 0, 153); font-weight: bold;">
                     


               
style="color: rgb(0, 0, 153); font-weight: bold;">
                               
value="oracle.toplink.essentials.platform.database.DerbyPlatform"
/>


                 
style="color: rgb(0, 0, 153); font-weight: bold;">
             
style="color: rgb(0, 0, 153); font-weight: bold;">
         
      
style="color: rgb(0, 0, 153); font-weight: bold;">
         
style="color: rgb(0, 0, 153); font-weight: bold;">
               
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"
/>


             
value="jdbc:derby://localhost:1527/pet-catalog"
/>


             
username
"
value="app" />
style="color: rgb(0, 0, 153); font-weight: bold;">
             
password
"
value="app" />
style="color: rgb(0, 0, 153); font-weight: bold;">
         
     
style="color: rgb(0, 0, 153); font-weight: bold;">
         
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>   
     


         
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>      
     


         
class="org.springframework.orm.jpa.JpaTransactionManager">
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="entityManagerFactory" ref="entityManagerFactory"/>
style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="dataSource" ref="dataSource"/>
style="color: rgb(0, 0, 153); font-weight: bold;">
         
   
style="color: rgb(0, 0, 153); font-weight: bold;">
         
  
style="color: rgb(0, 0, 153); font-weight: bold;">
         
itemController
"
class="sessionpagination.ItemController"
scope="session"> style="color: rgb(0, 0, 153); font-weight: bold;">
             
name="catalogService">
style="color: rgb(0, 0, 153); font-weight: bold;">
                 
catalogService
"/> style="color: rgb(0, 0, 153); font-weight: bold;">
             
style="color: rgb(0, 0, 153); font-weight: bold;">
         
style="color: rgb(0, 0, 153); font-weight: bold;">
         
     


     

     

     


  • Add the spring framework ContextLoaderListener and context
    parameter to your application's web.xml as shown below. For more
    information on configuring Spring see these references: href="http://www.thearcmind.com/confluence/display/SHJFT/Using+Spring+2+with+JSF">Using
    Spring 2 with JSF , href="http://static.springframework.org/spring/docs/1.2.x/reference/webintegration.html">Spring
    - Java/J2EE Application Framework Integrating with JavaServer Faces, 
    Advanced Configuration
    of the
    Spring MVC Framework


Code Sample from: web.xml
 

         
style="color: rgb(204, 0, 0); font-weight: bold;">
             
contextConfigLocation
style="color: rgb(204, 0, 0); font-weight: bold;">
             
/WEB-INF/applicationContext.xml
style="color: rgb(204, 0, 0); font-weight: bold;">
         
style="color: rgb(204, 0, 0); font-weight: bold;">
         
style="color: rgb(204, 0, 0); font-weight: bold;">
             
style="color: rgb(204, 0, 0); font-weight: bold;">
                 
      org.springframework.web.context.ContextLoaderListener
style="color: rgb(204, 0, 0); font-weight: bold;">
             
style="color: rgb(204, 0, 0); font-weight: bold;">
         
style="color: rgb(204, 0, 0); font-weight: bold;">
         
style="color: rgb(204, 0, 0); font-weight: bold;">
             
    
style="color: rgb(204, 0, 0); font-weight: bold;">
                 style="color: rgb(0, 0, 153);">org.springframework.web.context.request.RequestContextListener      style="color: rgb(204, 0, 0); font-weight: bold;">
             
style="color: rgb(204, 0, 0); font-weight: bold;">
         
   


   

  • Add the
     style="color: rgb(0, 0, 153);">DelegatingVariableResolver 
    and
    any Spring style="color: rgb(0, 0, 153);">beans (i.e.
    catalogService)
       
    referenced as JSF
    Managed Bean
    (i.e. 
     style="color: rgb(0, 102, 0);">ItemController
    ) properties 
    to the faces-config.xml : 
Code Sample from: faces-config.xml


     
 
< style="color: rgb(204, 0, 0);">application>

    <variable-resolver>

    org.springframework.web.jsf.DelegatingVariableResolver 

   

 

 <managed-bean>

    <managed-bean-name>item

      <managed-bean-class>

         style="color: rgb(0, 102, 0);">sessionpagination.ItemController

     

   
<managed-bean-scope> style="color: rgb(204, 0, 0);">session

     
    
<managed-property>

         
<property-name> style="color: rgb(0, 102, 0);">catalogService

          < style="color: rgb(204, 0, 0);">value>#{ style="color: rgb(0, 102, 0);">catalogService}

   


 


     

     

     


References

  • Using the Java
    Persistence API (JPA) with Spring 2.0
  • href="http://java-x.blogspot.com/2006/12/data-access-with-spring-and-jpa.html">Data
    Access with Spring and JPA on Glassfish
  • href="http://blog.interface21.com/main/2006/08/07/using-jpa-in-spring-without-referencing-spring/">Using
    JPA in Spring without referencing Spring
  • href="http://static.springframework.org/spring/docs/1.2.x/reference/webintegration.html">Spring
    - Java/J2EE Application Framework Integrating with JavaServer Faces
  • href="http://www.thearcmind.com/confluence/display/SHJFT/Using+Spring+2+with+JSF">Using
    Spring 2 with JSF
  • href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-7082&yr=2007&track=6">Building
    JavaServer Faces Applications with Spring and Hibernate
  • Spring and
    Hibernate in GlassFish
  • href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-43350&yr=2007&track=3">Harnessing
    the Power of Java Platform, Enterprise Edition (Java EE) Technology
    With Spring
  • Java
    EE tutorial (includes great tutorial for JSF and JPA)
  • Pro
    EJB 3: Java Persistence API book
  • href="https://blueprints.dev.java.net/bpcatalog/ee5/persistence/index.html">Java
    BluePrints Solutions Catalog for the Java Persistence APIs
    contains a collection of topics and example applications.
  • target="bpcatalog">Java
    Persistence reference page on GlassFish Project 
  • href="http://www.javaworld.com/javaworld/jw-07-2004/jw-0719-jsf.html">Build
    a real-world Web application with JavaServer Faces, the Spring
    Framework, and Hibernate




Related Topics >>

Comments

Sample Application using JSF,

Hello Carol,
I want to dowload the code of this example, but I can't. It says that I can't
"Your account does not have the "Project Document - View" permission needed for you to access the page you requested in the techdayscode project (view your permissions). Either ask the project administrator for more permission, or log in using a different account."
Can you help me?
Greetings.

Sample Application using JSF,

Hy Carol,
Seems me a nice article but ..... i'v the same problem..... also i can't download the sample code?
What should/can i do?
Greetings

Thank You.

Very nice article.