Sample application using JSF, Spring 2.0, and Java persistence Apis__java

Source: Internet
Author: User
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 pagination of the Data Sets in a Sample application using JSF, Catalog façade stateless session, and Java  Persistence APIs and modified it slightly to use a Spring bean instead of an EJB 3.0 session bean. If you are compare the two, you'll be the code is almost the same and 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. (The references at the end).
Download the SPRINGJPA sample application code
Note:i updated the "Spring JSF Integration part of" application to use The Org.springframework.web.jsf.DelegatingVariableResolverInstead of a  JSF Managed Bean Servicelocator in order to get a reference to the CatalogService spring beans from the spring application Context.

explanation of the usage of JSF, Spring 2.0, and Java persistence APIs in a sample Store Catalog applicationThe image below shows the Catalog Listing page, which allows a user to page through a-list of items in a store.



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

The dataTable component is useful if you are 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.

The LIST.JSP Web page is defined as shown below: (note:red colors are for Java EE tags, annotations cod E, Blue for Spring specific and Green for my Code or variables

Code Sample from:List.jsp

cellpadding= "2" cellspacing= "0" >


The value of the a dataTable tag references the data to is included in the table. The var attribute specifies a name that's used by the components within the dataTable tagged as an alias to the data Referen  CED in the value of the dataTable. In the dataTable tag from the list.jsp page, the value is 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 item controller class, Itemcontroller, which be defined in th E faces-config.xml File:

Code Sample From:faces-context.xml

<managed-bean>
<managed-bean-name>item</managed-bean-name>
<managed-bean-class>
Sessionpagination. Itemcontroller
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>catalogService</property-name>
<value>#{catalogService}</value>
</managed-property>
</managed-bean>




This itemcontroller Managedbean The Items property is defined as shown below:

Code Sample from: itemcontroller . Java

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



The GetItems () method is 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 inst  Ance. The data collection underlying a Datamodel instance is modeled as a collection of row objects, can be accessed by a RO  W index. The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the "data" Corresponds to the current row index.

The Item properties Name, Photo, and price are displayed with the column component:

Code Sample from:List.jsp

<f:facet name= "Header" >
</f:facet>


The column tags represent columns of data in a UIData component. While the UIData component are iterating over the rows of data, it processes the Uicolumn component and each CO Lumn 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 is the list of items, it renders one cell in each column.

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

The recommended way to integrate spring with JSF are to configure the spring Delegatingvariableresolver In the Faces-context.xml. The <application> <variable-resolver> 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 delegatingvariableresolver  The original resolver of the underlying JSF implementation, then to the Spring root Webapplicationconte   Xt. This allows your to configure Spring Beans as managed properties of your JSF managed. For example, below the CatalogService Spring Bean was configured as a managed property of the Itemcontroller JSF managedbe AN:

Code Sample From:faces-context.xml

<application>
<variable-resolver>
Org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>item</managed-bean-name>
<managed-bean-class>
Sessionpagination. Itemcontroller
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>catalogService</property-name>
<value>#{catalogService}</value>
</managed-property>
</managed-bean>



The CatalogService, and its implementation Catalogdao, are 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 "/>

<bean name= "Itemcontroller" class= "Sessionpagination". Itemcontroller ">
<property name= "CatalogService" >
<ref bean= "CatalogService"/>
</property>
</bean>

</beans>

<property name= "CatalogService" > refers to the Itemcontroller method. The spring root webapplicationcontext would inject the CatalogService Spring Bean into the CatalogService property of the I Temcontroller JSF Managedbean:

Code Sample from: Itemcontroller. Java

public class Itemcontroller {

Private CatalogService CatalogService;

public void Setcatalogservice (CatalogService catalogservice) {
This.catalogservice = CatalogService;
}

For more information in using JSF with Spring, and the SPRING-JAVA/J2EE application Framework integrating with JavaServer Fa Ces.

Using the Java Persistence API (JPA) with Spring 2.0The 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 a entity manager to be injected. (Note this using the @PersistenceContext annotation is the same way a Entity Manager is injected to a EJB 3.0 session was An.)


Code Sample From:CatalogDAO.java

@Repository
@Transactional
public class Catalogdao implements CatalogService {

@PersistenceContext (unitname= "Petcatalogpu")
Private Entitymanager em;

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 This can return a list of results. The JPA Query interface provides support for pagination via the Setfirstresult () and Setmaxresults () Methods:q.setmaxresu LTS (int maxresult) sets the maximum number of results to retrieve. Q.setfirstresult (int startposition) sets the position of the "the" the "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 a entity:
Annotating the class with an @Entity annotation.
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 data  base table, they don ' t have to be annotated. The O/R relationships with address and Product are also annotated. For the more information on defining JPA entities the 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 Addre
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.