The Source for Java Technology Collaboration
User: Password:



Carol McDonald

Carol McDonald's Blog

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

Posted by caroljmcdonald on January 07, 2008 at 02:36 PM | Comments (19)


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



I took this example  Sample Application using JSF, Spring 2.0, and Java Persistence APIs  and updated it to use the Spring 2.5 framework (which comes with Netbeans 6) on Glassfish v2.
You can dowload the  sample code   and a related presentation  JavaServer Faces, Java Persistence API, Java EE, Spring, Seam.


Explanation of the usage of JSF, Spring 2.5 , 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

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, Blue for Spring specific and Green for my code or variables)

Code Sample from:  List.jsp

<h:dataTable value='#{itemController.items}' var='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 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 dataTableItem points to the current item in the list.

The dataTable's value is bound to the items property of the itemController ManagedBean.
This ItemController ManagedBean items property is defined as shown below:

Code Sample from: ItemController.java
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller; 
 
  @Controller("itemController")
  @Scope("session")

  public class ItemController {

    public DataModel getItems() {
        if (model==null  || index != firstItem){
            model=getNextItems();
        }
        return this.model;
    }
   
    public DataModel getNextItems() {      
        model = new ListDataModel(catalogService.getItems(firstItem,batchSize));
        index = firstItem;      
        return this.model;
    }




@Controller is a Spring 2.5 "stereotype" annotation, @Repository, @Service and @Controller are role designations for a common three-tier architecture (data access objects, services, and web controllers). By clearly indicating application roles, these stereotypes facilitate the use of Spring AOP and post-processors for providing additional behavior to the annotated objects based on those roles. The @Scope("session") annotation binds a web-tier Spring-managed object to the specified scope.  The  Spring  2.5 component scanning functionality removes the need to define Web tier "controllers"  in the faces-config.xml.  The following configuration is used to trigger the auto-detection of all web controllers:

Code Sample from: applicationContext.xml

  <context:component-scan base-package="sessionpagination" />

 

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. Configure this resolver in your faces-config.xml file as follows:

Code Sample from: faces-context.xml

  <application>
    <el-resolver>
    org.springframework.web.jsf.el.SpringBeanFacesELResolver
    </el-resolver>
 </application>
 




The ItemController getItems() method wraps a List of item objects, returned from the catalogService,  in a DataModel.
UIData, the superclass of dataTable, supports data binding to a collection of data objects represented by a 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 price  are displayed with the column component:

Code Sample from: List.jsp

  <h:column>
      <f:facet name="header">
          <h:outputText value="Price"/>
      </f:facet>
      <h:outputText value="#{dataTableItem.price}"/>
  </h:column>


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 (item.items)  and displays the dataTableItem.price. Each time UIData iterates through the list of items, it renders one cell in each column.

The dataTable and column tags use facet to represent parts of the table that are not repeated or updated. These include headers, footers, and captions.

The catalogService, and its implementation  CatalogDAO,  is defined as a Spring bean in the Spring configuration resource file /WEB-INF/applicationContext.xml :

Code Sample from: applicationContext.xml
  
    <bean id="catalogService" class="service.CatalogDAO"/>     
 
   
</beans>


  The Spring root WebApplicationContext will inject the catalogService Spring Bean into the catalogService property of the ItemController JSF ManagedBean :

Code Sample from: ItemController.java
    @Controller("itemController")
  @Scope("session")

  public class ItemController {

  private CatalogService catalogService ;
  @Autowired
  public void setCatalogService(CatalogService catalogService) {
        this.catalogService = catalogService; 
  }



@Autowired is a Spring 2.5 annotation that makes it possible to inject dependencies that match by type. This behavior is enabled for fields, constructors, and methods. To enable this, add this to the applicationContext.xml:

Code Sample from: applicationContext.xml

<context:annotation-config/>




For more information on using JSF with Spring, see Spring - Java/J2EE Application Framework Integrating with JavaServer Faces .

Using the Java Persistence API (JPA) with Spring 2.5

The Spring bean CatalogDAO uses the Java Persistence API EntityManager Query object to return a list of items. The CatalogDAO annotates the field private EntityManager em;  with @PersistenceContext , which causes an entity manager to be injected. (note that using the @PersistenceContext annotation is the same way an Entity Manager is injected for a EJB 3.0 Session Bean.)
 

Code Sample from: CatalogDAO.java

@Repository
@Transactional
public class CatalogDAO implements CatalogService {
   
    @PersistenceContext(unitName="PetCatalogPu")
    private EntityManager em;

    @Transactional(readOnly = true)
    public List<Item>  getItems(int firstItem,int batchSize) {      
       Query q = em.createQuery("select object(o) from Item as o");
       q.setMaxResults(batchSize);
       q.setFirstResult(firstItem);
       List<Item> items= q.getResultList();
       return items;      
   }
   

The Java Persistence 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.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.setFirstResult(int startPosition) sets the position of the first result to retrieve.

In the code below, we show the 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 @Entity annotation.
  2. annotating   the primary key identifier with @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 Address and Product are also annotated. For more information on defining JPA entities see Pro EJB 3: Java Persistence API book.

Code Sample from: Item.java

@Entity
public class Item implements java.io.Serializable {

   
@Id  
    private String itemID;

    private String name;   
    private String description;   
    private String imageurl;   
    private String imagethumburl; 
    private BigDecimal price;
    @OneToOne(cascade={CascadeType.PERSIST})
    private Address address;
    @ManyToOne
    private 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 Items by maintaining the firstItem and batchSize attributes and passing these as parameters to the CatalogService getItems(firstItem, batchSize) method. The ItemController's <managed-bean-scope> is defined as 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 items in the  data base on the List.jsp page:

Code Sample from: List.jsp

<h:outputText value="Item #{
itemController.firstItem +1} ..#{itemController.lastItem} of #{itemController.itemCount}"/>


This ItemController ItemCount property is defined as shown below:

Code Sample from: ItemController.java

    public int getItemCount() {      
        int count = catalogService.getItemsCount();
        return count;     
    }

The ItemController getItemCount() method calls the CatalogService interface to get the count of the list of items. The CatalogDAO Spring bean  getItemCount() method uses the JPA Query interface to get the count of all items in the database item table:

Code Sample from: CatalogDAO.java
@Repository
@Transactional

public class CatalogDAO implements CatalogService {
  @PersistenceContext(unitName="PetCatalogPu")
  private EntityManager em;

. . .
  @Transactional(readOnly = true)
  public int  getItemCount() {
      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 commandLink tag represents an HTML hyperlink and is rendered as an HTML <a> element. The commandLink tag is used to submit an action event to the application. 

Code Sample from: List.jsp

 <h:commandLink action="#{
itemController.next}" value="Next #{itemController.batchSize}"
    rendered="#{itemController.lastItem + itemController.batchSize <= itemController.itemCount}"/> 


This commandLink action attribute references the ItemController backing bean next() method which calculates the next page's first row number  and returns a logical outcome String, which causes the List.jsp page to display the next page's list . The ItemController next method is defined as shown below:

Code Sample from: ItemController.java

   public String next() {
       if (firstItem + batchSize < getItemCount()) {
           firstItem += batchSize;
       }
       return "item_list";
   }


The JavaServer Faces 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

  <navigation-rule>
      <navigation-case>
          <from-outcome>
item_list</from-outcome>
          <to-view-id>/item/List.jsp</to-view-id>
      </navigation-case>
  </navigation-rule>


A JSF commandLink is  used to provide a link to click on to display the previous page of items. This commandLink action attribute  references the  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

 <h:commandLink action="#{
itemController.prev}" value="Previous #{itemController.batchSize}"        
        rendered="#{itemController.firstItem >=itemController.batchSize}"/>


 This ItemController  prev() method  is defined as shown below: 
 
Code Sample from: ItemController.java

    public String 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 item details. This commandLink action attribute  references The ItemController detailSetup() method:

Code Sample from: List.jsp

   <h:column>
       <f:facet name="header">
          <h:outputText value="Name"/>
       </f:facet>
       <h:commandLink action="#{
itemController.detailSetup}" value="#{dataTableItem.name}"/>   
   </h:column>


The ItemController detailSetup() method  gets the item data from the current row of the dataModel, and returns a string which causes the Detail.jsp page to display the item details :

Code Sample from: ItemController.java

    public String detailSetup() {
        item = (Item) model.getRowData();
        return "item_detail";
    }


The JavaServer Faces NavigationHandler matches the logical outcome,  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 Detail.jsp page after this method returns.

Code Sample from: faces-config.xml

    <navigation-rule>
        <navigation-case>
            <from-outcome>item_detail</from-outcome>
            <to-view-id>/item/Detail.jsp</to-view-id>  
        </navigation-case>
    </navigation-rule>    

   

The Detail.jsp uses the outputText component to display the ItemController ManagedBean's item properties:

Code Sample from: detail.jsp

    <h:outputText value="#{itemController.item.name}" title="Name" />
    <h:outputText value="#{itemController.item.description}" title="Description"/>
    <h:graphicImage url="#{itemController.item.imageurl}" title="Imageurl" />
    <h:outputText value="#{itemController.item.price}" title="Price" />
    <h:outputText value="#{item
Controller.item.address.city}" title="Address" />
    <h:outputText value="#{item
Controller.item.contactinfo.email}" title="Address"/>  


    detailpage.jpg



Conclusion
This concludes the sample application which demonstrates how to work with the JSF dataTable and  DataModel  to page through a list of  Item Entities which are retrieved using the Catalog methods which use  the Java Persistence APIs with 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 here with screenshots)

  1. Download and install NetBeans 6.0 . 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 JavaDB from the drop-down menu.
    7. Click Next.
    8. Scroll down to the end of the page to see the 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 jdbc:derby://localhost:1527/pet-catalog.
    5. For User Name field, enter app.
    6. For Password field, enter 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 pet-catalog.
    3. For User Name field, enter app.
    4. For Password field, enter 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 <sample_install_dir>/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 sample code and extract its contents. You should now see the newly extracted directory as <sample_install_dir>/SpringJPA, where <sample_install_dir> 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. Build the project as follows:

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

  4. 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: 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 applicationConfiguration.xml and modify the web.xml and faces-config.xml as described below.
    1.  modify the file /WEB-INF/applicationContext.xml to the war WEB-INF directory.  This file is where you define your Spring service beans, and resources. Below is the applicationContext.xml for the sample app.  For more information about configuring the Spring applicationContext.xml for JPA see this article: Using the Java Persistence API (JPA) with Spring 2.5
      Code Sample from: applicationContext.xml
      <?xml version="1.0" encoding="UTF-8"?>

      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:p="http://www.springframework.org/schema/p"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:jee="http://www.springframework.org/schema/jee"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="
             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
             http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-2.5.xsd
             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

         
          <bean id="propertyConfigurer"
                class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
                p:location="/WEB-INF/jdbc.properties" />

              
         
          <!-- JPA EntityManagerFactory -->
          <bean id="entityManagerFactory"
                class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
                p:dataSource-ref="dataSource">
              <property name="jpaVendorAdapter">
                  <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter"
                        p:databasePlatform="${jpa.databasePlatform}"
                        p:showSql="${jpa.showSql}"/>          
              </property>
              <property name="loadTimeWeaver">
                  <bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
              </property>
          </bean>    
         
          <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}" />  

          <!--
              PostProcessors to perform exception translation on @Repository classes
          -->
          <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
        
          <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

          <!-- Transaction manager for  JTA  -->
          <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
          <!--
           Instruct Spring to perform declarative transaction management
           automatically on annotated classes.
          -->
          <tx:annotation-driven />
          <!--
           Activates various annotations to be detected in bean classes: Spring's
           @Required and @Autowired, as well as JSR 250's @PostConstruct,
           @PreDestroy and @Resource (if available) and JPA's @PersistenceContext
           and @PersistenceUnit (if available).
          -->
          <context:annotation-config/>
          <context:component-scan base-package="sessionpagination" />
          <!--
           Instruct Spring to retrieve and apply @AspectJ aspects which are defined
           as beans in this context (such as the UsageLogAspect below).
          -->
          <aop:aspectj-autoproxy/>
          <!--
           CatalogDAO Will automatically be transactional due to @Transactional.
           EntityManager will be auto-injected due to @PersistenceContext.
           PersistenceExceptions will be auto-translated due to @Repository.
          -->
         
      <bean id="catalogService" class="service.CatalogDAO"/>

         
      </beans>


    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: Using Spring 2 with JSF , Spring - Java/J2EE Application Framework Integrating with JavaServer FacesAdvanced Configuration of the Spring MVC Framework
      Code Sample from: web.xml

          <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>/WEB-INF/applicationContext.xml</param-value>
          </context-param>
          <listener>
              <listener-class>
                  org.springframework.web.context.ContextLoaderListener
              </listener-class>
          </listener>
          <listener>
              <listener-class>    
                org.springframework.web.context.request.RequestContextListener     
              </listener-class>
          </listener>   

         
    3. Add the SpringBeanFacesELResolver to the faces-config.xml : 
      Code Sample from: faces-config.xml

        <application>
          <el-resolver>
         org.springframework.web.jsf.el.SpringBeanFacesELResolver
          </el-resolver>
       </application>





For additional information see:






Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

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

    Regards.

    Posted by: dxxvi on January 08, 2008 at 06:36 AM

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

    Posted by: caroljmcdonald on January 08, 2008 at 08:50 AM

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

    Posted by: paksegu on January 08, 2008 at 02:14 PM

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

    Posted by: caroljmcdonald on January 08, 2008 at 03:29 PM

  • 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

    Posted by: djomos on January 08, 2008 at 06:18 PM

  • Thanks, I will try that out

    Posted by: caroljmcdonald on January 08, 2008 at 07:13 PM

  • Je parle francais aussi

    Posted by: caroljmcdonald on January 08, 2008 at 07:13 PM

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

    Posted by: djomos on January 09, 2008 at 06:14 AM

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

    Posted by: djomos on January 10, 2008 at 01:44 AM

  • 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?

    Posted by: andreakendall on January 10, 2008 at 07:10 PM

  • 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

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

    Posted by: andreakendall on January 10, 2008 at 08:04 PM

  • 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?

    Posted by: andreakendall on January 10, 2008 at 08:06 PM

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

    Posted by: andreakendall on January 11, 2008 at 09:57 AM

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

    Posted by: caroljmcdonald on January 15, 2008 at 04:37 PM

  • 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

    Posted by: mchisty on March 31, 2008 at 12:06 AM

  • 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_elseb             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?
     

    Posted by: mchisty on March 31, 2008 at 12:34 AM

  • Hi Carol,

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

    Posted by: johnnyren on April 02, 2008 at 06:58 PM

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

    Posted by: caroljmcdonald on April 02, 2008 at 07:48 PM


  • 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

    Posted by: mchisty on April 03, 2008 at 03:36 AM



Only logged in users may post comments. Login Here.


Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds