Skip to main content

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

Posted by caroljmcdonald on January 7, 2008 at 2:36 PM PST


Sample Application using JSF, Spring 2.5, and Java Persistence APIs
with Netbeans 6.1 and Glassfish v2



You can href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555&expandFolder=7555&folderID=0">dowload
the Sample
Application using JSF, Spring 2.5, and Java Persistence APIs 
on Glassfish v2 and a related presentation  href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555&expandFolder=7555&folderID=0">JavaServer
Faces, Java Persistence API, Java EE, Spring, Seam. style="font-weight: bold;">



A Summary of the Technologies and Frameworks in the Sample
Application

If you're not familiar with JavaServerFaces technology, the Java
Persistence API, or Spring, here are brief descriptions:

  • JavaServer
    Faces Technology

    (often referred to as JSF) is a server-side user interface (UI)
    component framework for web applications. It simplifies the development
    of sophisticated interactive web UIs by providing configurable,
    reusable, extendable UI components, support for event handling, input
    converters and validators, a navigation model, a component rendering
    model, and a managed bean model for translating input events to
    server-side behavior.


  • The
    Java Persistence API

    provides a (plain old Java object) POJO-based persistence model for
    Java EE and Java SE applications. It handles the details of how
    relational data is mapped to Java objects, and it standardizes
    Object/Relational (O/R) mapping.


  • Spring
    is a lightweight, POJO-oriented, open source framework for developing
    Java enterprise applications. Spring does not reinvent application
    server functionality such as connection pooling, or provide an
    object-relational mapping layer. Instead it provides support for
    Inversion of Control (IoC), dependency injection, Aspect Oriented
    Programming (AOP), and an abstraction/services layer designed to make
    existing Java Enterprise application server technologies easier and
    more transparent to use.




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

The sample application is an online catalog 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 table 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. The UIData
component does the
work of iterating over each record in the collection of
data objects. 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;">#{itemController. 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 value attribute in the dataTable tag
points to a list of catalog items identified by the expression

 style="font-weight: bold;">#{itemController. style="color: rgb(0, 102, 0); font-weight: bold;">items style="font-weight: bold;">}
. The value is bound to the
 style="color: rgb(0, 102, 0); font-weight: bold;">items style="font-weight: bold;">
property of a managed bean
that has the managed bean name
 style="color: rgb(0, 102, 0);">itemController
.



The var
attribute specifies a
name ,
dataTableItem, 
which is used as an alias for a single item in the  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);">itemController

ManagedBean.

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
    package controller;

    import org.springframework.context.annotation.Scope;

    import org.springframework.stereotype.Component; 

 

 
@Component("
 style="color: rgb(0, 102, 0);">itemController
 style="font-weight: bold; color: rgb(0, 0, 153);">")

  @Scope("session")

 
public class ItemController
{


   
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;

    }


     

     





@Component

 style="color: rgb(51, 51, 255); font-weight: bold;"> 
is
a Spring 2.5
"stereotype" annotation. @Repository,
@Service
and @Controller extend @Component
and are role designations for a common
three-tier architecture components (data access objects, services, and
web
controllers).  href="http://www.infoq.com/articles/spring-2.5-part-1"> these
stereotypes facilitate the
use of Spring AOP and post-processors for providing additional behavior
to the annotated objects based on those roles and can also be used for
auto-detection of components on the classpath.



The @Scope("session")
annotation binds a web-tier Spring-managed object to the specified
scope. "session"
scopes a  bean definition to the lifecycle of a HTTP class="interfacename">Session.



The  Spring  2.5 component scanning
functionality removes the need to define  JSF Managed Beans or Web
tier "controllers" 
in the faces-config.xml,
and other components in the Spring style="color: rgb(0, 0, 153);">applicationContext.xml. The
following configuration is used to
trigger the
auto-detection of all components in the controller package:


class="bg-white">
Code Sample from: applicationContext.xml


 
base-package="controller"
/>


     

     

 

href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/jsf/el/SpringBeanFacesELResolver.html">

To integrate Spring with JSF configure the Spring 
JSF 1.2 ELResolver that delegates to the Spring root WebApplicationContext,
resolving name references to Spring-defined beans. 

 style="color: rgb(0, 0, 153); font-weight: bold;">
style="color: rgb(204, 0, 0); font-weight: bold;"> style="color: rgb(0, 0, 0);">Configure this resolver in
your faces-config.xml file as follows:



   
 
Code Sample from: faces-context.xml


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

    <el-resolver>

    org.springframework.web.jsf.el.SpringBeanFacesELResolver

   

 

 


     

     





The ItemController
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="font-weight: bold; color: rgb(204, 0, 0);">dataTable

column
component, which displays a table column:


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;">#{itemController. 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">

     

     
  < style="color: rgb(204, 0, 0); font-weight: bold;">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

 style="font-weight: bold; color: rgb(204, 0, 0);">dataTable
.
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 class="cCode">UIData
component  iterates through the list
of items returned by
 style="color: rgb(0, 102, 0); font-weight: bold;">ItemController

style="color: rgb(0, 102, 0); font-weight: bold;">getItems()
, ( referenced by
 style="font-weight: bold; color: rgb(204, 0, 0);">value=' style="font-weight: bold;">#{itemController. style="color: rgb(0, 102, 0); font-weight: bold;">items style="font-weight: bold;">}') , 

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
row  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 in the rows. These include
 style="color: rgb(204, 0, 0); font-weight: bold;">header
s,
footers,
and captions.



Auto-Detection of Spring Components



The 
 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO
, 
is defined as a Spring
bean
by the  @Repository
stereotype which
extends
the @Component annotation and can be  style="text-decoration: underline;">
href="http://www.infoq.com/articles/spring-2.5-part-1">used for
auto-detection of components on the classpath.


Code Sample from: CatalogDAO.java


package service;

     

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

public class CatalogDAO
implements CatalogService
{

   

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

   

     





The
href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html"> style="color: rgb(0, 0, 153); font-weight: bold;">The Spring IoC
container 
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
   
 style="font-weight: bold; color: rgb(0, 0, 153);">
 style="font-weight: bold; color: rgb(0, 0, 153);">
 style="font-weight: bold; color: rgb(0, 0, 153);">

 
public class ItemController
{

     

  private CatalogService catalogService ;

     

  @Autowired

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

        this.catalogService =
catalogService; 

  }





href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html">

 style="color: rgb(51, 51, 255); font-weight: bold;"> style="color: rgb(0, 0, 153);">@Autowired
 
marks a constructor, field, setter method or config method to be
autowired by Spring's dependency injection facilities.
 style="color: rgb(51, 51, 255); font-weight: bold;"> style="color: rgb(0, 0, 153);">@Autowired 
makes
it possible to
inject
dependencies that match by type.
   The
 style="color: rgb(0, 102, 0); font-weight: bold;">setCatalogService

is marked as @Autowired and accepts an argument of
type CatalogService. This is Spring 2.5 annotation-driven
dependency injection: This setter will be called passing in a Spring
bean of type CatalogService, obtained by type from the
Spring ApplicationContext.

To enable this, add this to
the Spring
applicationContext.xml:


border="1" cellpadding="2" cellspacing="0">
Code Sample from: style="color: rgb(0, 0, 153); font-weight: bold;">applicationContext.xml
 style="color: rgb(0, 0, 153);"> 
[prettify]<context:component-scan base-package="service" />

[/prettify]
 style="font-weight: bold;">

     


Using the Java Persistence API (JPA) with Spring 2.5

The Spring bean

 style="color: rgb(0, 102, 0); font-weight: bold;">CatalogDAO 
uses
an EntityManager
Query object in the Java Persistence API to return a list of items. If
you look at the source code for CatalogDAO , you'll
notice that it annotates an EntityManager field with a
 style="font-weight: bold; color: rgb(204, 0, 0);">@PersistenceContext

annotation. This injects an entity manager into the Spring Bean 
the
same way that an Entity Manager is injected into an Enterprise
JavaBeans Technology (EJB) session bean.


Code Sample from: CatalogDAO.java
 package service;

      @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;

     

         
      @Transactional(readOnly =
true)


    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 createQuery method creates an instance of a Query
class for executing a Java Persistence query language statement. The setMaxResults()
method in Query sets the maximum number of results to
retrieve, and the setFirstResult method sets the position
of the first result to retrieve.

Item is an Entity class -- a typical Java
Persistence entity object -- which maps to an ITEM table that stores
the item instances. If you examine the source code for Item,
you'll see that it meets the two requirements for an entity:

  • The class is annotated with an @Entity annotation.
  • The primary key identifier is annotated with an @Id
    annotation.





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 getName() {

       
return name;

    }


    public void setName(String name) {

       
this.name = name;

    }
    

     


     

    ...

}   

     

     







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, which gets the items for display in the table of
pets.





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
#{
 style="font-weight: bold;">itemController
 style="color: rgb(0, 0, 0);">.firstItem +1} ..#{
 style="font-weight: bold;">itemController
.lastItem}
of #{
 style="font-weight: bold;">itemController
 style="color: rgb(0, 102, 0); font-weight: bold;">.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
 style="color: rgb(0, 0, 153); font-weight: bold;">@Repository style="color: rgb(0, 0, 153); font-weight: bold;">
      @Transactional


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

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

 
private EntityManager
      em;


. . .

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


  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;

  }   

    

     



Displaying the Next List of items



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;">
 style="font-weight: bold;">itemController
 style="color: rgb(0, 102, 0); font-weight: bold;">.next}"
value="Next
#{
itemController
.batchSize}"

   
rendered="#{itemController.lastItem + itemController.batchSize <=
itemController.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;">
           


       

     

     





When the

 style="color: rgb(0, 102, 0);">List.jsp
 style="font-weight: bold; color: rgb(204, 0, 0);">dataTable style="color: rgb(204, 0, 0);"> 
is rendered, the
 style="font-family: mon;">
 style="font-weight: bold; color: rgb(204, 0, 0);"> value 
binding
causes the 
 style="color: rgb(0, 102, 0); font-weight: bold;">ItemController

style="color: rgb(0, 102, 0); font-weight: bold;">getItems method
to be called, as discussed before, which will cause the next list of
items to be displayed. 
 style="color: rgb(0, 102, 0); font-weight: bold;">
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;">#{itemController. 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">

     


     

     





Displaying an Item's Details 



A JSF commandLink
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;">
 style="font-weight: bold;">itemController
 style="color: rgb(0, 102, 0); font-weight: bold;">. 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) style="color: rgb(204, 0, 0); font-weight: bold;">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="#{itemController.item.name}"
title="Name" />

   
title="Description"/>

   
title="Imageurl" />

   
/>

   
Controller
.item.address.city}"
title="Address" />

   
Controller
.item.contactinfo.email}"
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.5.


Running the Sample Code

The sample code for this tip is available as a NetBeans project. You
can build and run the sample code using the NetBeans IDE.


Set up the Development Environment: (these directions are also href="http://www.javapassion.com/handsonlabs/spring25jpa/">here
with screenshots)

  1. Download
    and install NetBeans 6.1 . Get the full distribution with Java EE and
    Glassfish v2.
  2. Install the Spring
    Framework Plug-in into the NetBeans IDE:

    • Select Tools from the NetBeans menu bar and
      select Plugins.
    • Select Available Plugins tab and
      then select Spring Framework Support and then click the Install
      button.
  3. Open the Admin Console of the GlassFish V2 application server in
    order to create the JDBC
    Connection pool and JDBC resource:

    1. Select the NetBeans Services
      tab
      window.
    2. Expand Servers.
    3. Right click GlassFish V2
      and select View Admin Console.
    4. Enter values to User Name
      and Password fields - the
      default is admin for User
      Name
      and adminadmin for the
      Password
  4. Create a connection pool using the Admin Console:
    1. Expand Resources->JDBC.
    2. Click Connection Pools.
    3. Click New on the
      right
      of the page.
    4. For the Name field,
      enter PETCatalogPool.
    5. For Resource Type,
      select javax.sql.DataSource
      from the drop-down
      menu.
    6. For Database Vendor field, select style="font-weight: bold;">JavaDB from the drop-down menu.
    7. Click Next.
    8. Scroll down to the end of the page to see the style="font-weight: bold;">Additional Properties section.
    9. For Connection Attributes
      field, enter
      ;create=true
      .
    10. For DatabaseName
      field,
      enter pet-catalog.
    11. For Password field,
      enter app.
    12. For User field,
      enter app.
    13. Click Finish.
    14. Remove the SecurityMechanism property
      from the PETCatalogPool:.

      1. Select PetCatalogPool under
        Connection Pools
        node
        on
        the left.
      2. Select Additional
        Properties

        tab on the right and observe that the Edit
        Connection Pool Properties
        are displayed.
      3. Check Security Mechanism
        and click Delete Properties.Click
        Save.
  5. Start the Java DB server using NetBeans:
    1. Select Tools from
      the
      NetBeans
      top-level menu
      bar and select Java DB
      Database->Start Server
      .
  6. Make sure the PetCatalogPool is
    operational using the Admin Console:

    1. Start the Java DB server (if it is not started already)
    2. Select the Admin Console General
      tab
      window.
    3. Click Ping button.
    4. Make sure that the Ping
      Succeeded
      message is displayed on the top.
  7. Create a JDBC resource using the Admin Console:
    1. Select JDBC Resources
      under JDBC on the left of the
      Admin Console .
    2. Click New button on
      the
      right.
    3. For JNDI Name field,
      enter jdbc/PETCatalogDB.
    4. For Pool Name field,
      select PETCatalogPool from the
      drop-down menu.
    5. Click OK.
  8. Create a Database connection using NetBeans:
    1. Select the NetBeans Services tab window.
    2. Right click Database and select New Connection.
    3. Observe that the New
      Database
      Connection
      dialog box appears.
    4. For the Database URL field, enter style="font-weight: bold; color: rgb(255, 0, 0);">jdbc:derby://localhost:1527/pet-catalog.
    5. For User Name field, enter style="font-weight: bold; color: rgb(255, 0, 0);">app.
    6. For Password field, enter style="font-weight: bold; color: rgb(255, 0, 0);">app.
    7. Click OK.
  9. Create a database using NetBeans:

    Select Tools from the
    NetBeans top-level menu bar and select Java
    DB
    Database->Create Database
    .

    1. Observe that the Create Java DB Database dialog appears.
    2. For the Database Name field, enter style="font-weight: bold; color: rgb(255, 0, 0);">pet-catalog.
    3. For User Name field, enter style="font-weight: bold; color: rgb(255, 0, 0);">app.
    4. For Password field, enter style="font-weight: bold; color: rgb(255, 0, 0);">app.
    5. Click OK.
  10. Populate the database tables  in the pet-catalog database as
    follows:

    1. Under Databases, select the connection pet-catalog that you
      just created.
    2. Right mouse click on pet-catalog and select Excecute Command.

    3. In the SQL command window copy paste all the sql text from
      the file /SpringJPA/setup/sql/javadb/catalog.sql,

    4. At the top of the window click on the icon for Run SQL. This
      will create all of the tables and data for the application.


Open and Run the Sample code:

  1. Download the href="https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=7555&expandFolder=7555&folderID=0">sample
    code and extract its contents. You should now see the newly
    extracted directory as /SpringJPA,
    where is the directory where
    you installed the sample package. For example, if you extracted the
    contents to C:\ on a Windows machine, then your newly
    created directory should be at C:\SpringJPA.


  2. Start the NetBeans IDE. Click Open Project in the File menu and
    select the SpringJPA directory you just unzipped.
  3. You will see a Reference Problems dialog when you open the
    project.
    That's because you need to add the Spring Framework to the
    project.   click Close in the dialog.
  4. Right click the SpringJPA project libraries node
    and select add Library, then select Spring Framework 2.5  (the
    Spring
    Framework Plug-in which you installed earlier), then click Add Library.


  5. Build the project as follows:


    • Right click the SpringJPA node in the Projects
      window.
    • Select Clean and Build Project.


  6. Run the project as follows:


    • Right click the SpringJPA node in the Projects
      window.
    • Select Run Project.

When you run the project, your browser should display the opening page
of the JSF, Java Persistence API, and Spring 2.5 Sample Application (at
http://localhost:8080/SpringJPA/).


Creating
your own Netbeans Project with Spring 2.5 & Glassfish  :

  1. If you want to create your own application, Create a new
    Netbeans Web Application:

    1. In Netbeans  select File New Project, then select Web
      ..Web Application, on the New Web Application
      Window, for Server select Sun Java System Applicaton server,  Java
      EE 5 Version,  set a project name and context path  and click
      Next .
    2. on the frameworks window select Spring Framework 2.5, click
      Finish.
  2. To Generate Entity classes from database tables: In the
    project window, right click on the project, 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)
  3. Configuration of
    the XML files for Spring 2.5, JSF, and JPA, running on Glassfish.

    For Spring configuration modify the style="color: rgb(0, 0, 153); font-weight: bold;">applicationConfiguration.xml
    and modify the web.xml
    and faces-config.xml
    as described below.

    1.  modify 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 style="color: rgb(0, 0, 153); font-weight: bold;">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.5

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

         

         
               
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"

               
      p:location="/WEB-INF/jdbc.properties" /> 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;">
                      
                   
      style="color: rgb(0, 0, 153); font-weight: bold;"> style="color: rgb(0, 0, 0);">

         
               
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"

               
      p:dataSource-ref="dataSource">

              name="jpaVendorAdapter">

                 
      class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter"

                       
      p:databasePlatform="${jpa.databasePlatform}"

                       
      p:showSql="${jpa.showSql}"/>          
                   

             

              name="loadTimeWeaver">

                 
      class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>

             

         
          

         

         
               
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"

               
      p:driverClassName="${jdbc.driverClassName}"

               
      p:url="${jdbc.url}"

               
      p:username="${jdbc.username}"

               
      p:password="${jdbc.password}" />   style="color: rgb(0, 0, 153); font-weight: bold;">
                    style="color: rgb(0, 0, 153); font-weight: bold;">  style="color: rgb(0, 0, 0);"> style="color: rgb(0, 0, 0);">

          class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
                   

        

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

                   

        

          class="org.springframework.transaction.jta.JtaTransactionManager" />

                   

         

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

         

          base-package="controller" />

          />

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

         

                   
       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;">
                   

                   

    2. 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

      cellspacing="0">
      Code Sample from: style="color: rgb(204, 0, 0);">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;">
                       
         


         
    3. Add the 
       style="color: rgb(0, 0, 153);">SpringBeanFacesELResolver
      to
      the faces-config.xml : 

      cellspacing="0">
      Code Sample from: style="color: rgb(204, 0, 0);">faces-config.xml


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

          <el-resolver>

         org.springframework.web.jsf.el.SpringBeanFacesELResolver
                   

         

       

                   


                   

                   





For additional information see:





Related Topics >>

Comments

Hi Carol, I have tried to set my application as indicated but I get the following exception when starting the context. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalRequiredAnnotationProcessor': BeanPostProcessor before instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/reflect/AjTypeSystem Then remove the line " aop:aspectj-autoproxy " and the context start but Spring Beans are injected as null and the application thows nullpointer Exceptions... any idea that can be wrong? Sorry for my English

Java EE 6 will have bean validation (seam already has it)

Very good...! I love you Carol.

Thanks Carol for your answer, I have another big question: what's the best way (in your experience) to provide validation on the beans if I don't use Spring MVC (so I cannot use Validator interface) ?

the ItemConverter converts an Item object to a string. The dispatcher-servlet.xml file is not necessary, I left that there by mistake, it was created by Netbeans when creating a spring web project.

Hi Carol, I really appreciated this application and your explanations. I have two questions: 1) What's the ItemConverter used for ? 2) Why have you put a dispatcher-servlet.xml file under WEB-INF if you don't use Spring MVC ? Thanks

Hi Carol, I really appreciate this application and you explanations. I'm just approching Spring and there are not to many good example to watch out there. Anyway I have two questions: 1) What's the ItemConverter used for ? 2) Why have you put a dispatcher-servlet.xml file under WEB-INF ? Thanks

Hello Carol, I think it's not a good idea to keep DB credentials in jdbc.properties file in J2EE environment. I propose to use JNDI-mapping instead. It can be easily reached by substituting the code <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> for the code <jee:jndi-lookup id="dataSource" jndi-name="jdbc/PETCatalogDB"/> What do you think about it?

if you nest non-JSF tags within JSF tags, you must wrap the non-JSF tags in f:verbatim; if you dynamically include JSP pages that contain JSF content, you must use f:subview and also wrap all included non-JSF content in f:verbatim.

Hi Carol, How the Spring DataAccessExceptions propagated are handled in your JSF controller/JSP pages?

Hmmm, checked with <f:verbatim/> too (with the following code). But still not working. Still shows the same output. This is surprising!! Is it possible for you to provide an example?

<f:verbatim>
<c:choose>
<c:when test="${dataUser.active==true}">Process Finished</c:when>
<c:otherwise>Enable or Disable</c:otherwise>
</c:choose>
</f:verbatim>

Thanks,

... Chisty

I added instructions on how to define a connection pool and jdbc resource using the Glassfish Admin console.

Thanks. with each version I have to change something to get it to work, really a pain.

Using Spring 2.5.5, I had to copy the jar file: aspectjweaver.jar to this directory in my NetBeans-6.1 installed Glassfish Server: C:\Program Files\glassfish-v2ur2\lib\endorsed\ before the SpringJPA sample would work. Before doing this, it would fail with: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/lang/reflect/AjTypeSystem

Je parle francais aussi

Thanks, I will try that out

Hi Carol and thanks for the article. Just to mention two things about JSF and Spring 2.5 integration:
*1* Spring 2.5 (finally) provides a JSF 1.2 compliant EL Resolver (the old one is JSF 1.1 compliant I think, but certainly not with 1.2). In the faces-config.xml, one should use:
<application> <el-resolver> org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application>
instead of the old:
<application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> </application>
*2* And now this is really fun ! you can get Spring to manage the JSF managed-beans instead of the JSF implementation, hence enabling a first class citizen acces to Spring functionalities within a JSF managed bean. You can even drop declaring these beans in faces-config.xml (and applicationContext.xml).
To do so, one have to:
  • As you did, annotate his controller with the @Controller annotation, optionally providing a name (String) under which the bean will be exposed to the JSF pages.
  • Optionally, add a @Scope annotation to specify the ... well, you should have guessed: @Scope("session"), @Scope("request"), etc.
    But you have to add Spring's RequestContextListener to web.xml in order to get the Scope control working.
  • Add those two lines in applicationContext.xml (you did so for the first):
<context:annotation-config /> <context:component-scan base-package="foo.bar" />
where foo.bar is the package where you controllers classes lie.

That's it ! you can now use those beans in the JSF pages or anywhere else (within the Spring container naturally). You can also use the @Autowired annotation on these beans, etc.
Anyway, I've talked about this point in my blog (in french).

Regards,
djo.mos

The focus of this series of blogs was to show the same app build using first just Java EE , then Java EE with Spring , then Java EE with Seam (with Netbeans and Glassfish). I also did the same app using JRuby and Rails. I don't think I will have time to do this using JPOX. I want to also show groovy and grails in the future.

Hi Carol, Can you do a similar example using (JPOX)? Thanks

Correction I added aspectjweaver.jar to the Spring library not aspectj

Could you please point out which Spring 2.5 features you used and where you used them? Regards.

The main changes I made in this app between Spring 2.0 and Spring 2.5 was to use the @Autowired annotation to inject the CatalogService into the ItemController. Other changes were in the applicationContext.xml to update for changes from Spring 2.0 to Spring 2.5.

Hi,

Regarding my previous post, here is some code portion:

The following code demonstrates this:

<f:view>
<h:form>
<h:dataTable value="#{userAction.usersList}" var="dataUser" border="1">

<h:column>
<f:facet name="header"><h:outputText value="Name" /></f:facet>
<h:commandLink action="#{userAction.viewUserDetail}" value="#{dataUser.name}" />
</h:column>

<h:column>
<f:facet name="header"><h:outputText value="Is Enabled?" /></f:facet>
<h:outputText value="#{dataUser.active}" />
</h:column>

<h:column>
<f:facet name="header"><h:outputText value="Status" /></f:facet>
<!-- PLEASE NOTE THE FOLLOWING JSTL CONDITION CHECKING -->
<c:choose>
<c:when test="${dataUser.active=='true'}">Process_Finished</c:when>
<c:otherwise>Show_something_else</c:otherwise>
</c:choose>
</h:column>

</h:dataTable>
</h:form>

</f:view>



The output shown is like this (which is WRONG):

Name Email Address Is Enabled? Status
a a aaaa true Show_something_else
b b bbbb false Show_something_else


Whereas the correct output should be like this (the CORRECT form):

Name Email Address Is Enabled? Status
a a aaaa true Process_Finished
b b bbbb false Show_something_else


NOTE: Even if I do the condition checking like this: test="${dataUser.active==true}" or, test="${dataUser.active}", it does not work either. Interestingly it is showing the Boolean value correctly in the 4th column 'Is Enabled'.

What might be wrong? Any suggestion?



Hi Carol,, After intergrating Spring, JSF1.2 (web 2.4 or, web 2.5), everything worked fine except that there was a simple problem. If I use JSTL's tag for conditional checking, it does not seem to work at all. Have you faced this problem before? Could you just update this article slightly by adding a simple JSTL tag in your jsp page so that we have some idea about how to get JSTL tags work in sync with JSF1.2? Thanks, .... Chisty

Oui m'dame :-)
Je le sais, vous être membre dans nos forums (developpez.com).

So, how would some one do this in a real application where you would not want to have these pools and connections defined with your application?

Is there some other tool that you would use to define the Pool and the JDBC connection?

I got it to work.

However I am not sure that the way I got this to work follows best practices.

What I ended up doing was

  1. Creating a new JDBC pool, PETCatalogPool
  2. Creating a new JDBC connection, jdbc/PETCatalogDB
  3. adding spring-framework-2.5\lib\aspectj to the Spring library

Still getting the java.lang.RuntimeException: java.lang.RuntimeException: javax.naming.NameNotFoundException

My theory is that the jdbc/PETCatalogDB is not being created. In your setup.xml file I see the following a 'create-resource-local" that looks like it would create this JNDI.

How do I create the JNDI jdbc/PETCatalogDB from the jdbc:derby://localhost:1527/pet-catalog connection?

Hi Again.
Just to mention that with the release of Spring 2.5.1 yesterday, Spring introduced two new Resolvers for JSF 1.2:
  • DelegatingFacesELResolver
  • WebApplicationContextFacesELResolver
Which acts as the old DelegatingVariableResolver for JSF 1.1. It's a bit blurred to be honest, and I definitely have to go back to Spring Reference and sort this out.
Regards.

Hello Carol, I thank you a lot for your tutorial. I know little about spring. The use of the beans in this tutorial was clear. But i wonder if there's any form of statefull session beans in the spring framework. If so, how do i could use them and in what scenarios?. Thank you very much.