Introduction
MVC architecture has become the default choice for developing web applications. It has become a tradition to develop web applications using multi-tier architecture and hence involving one or more Frameworks. A Framework ensures faster development cycle and guarantees the usage of proven design patterns and architecture. There are various Frameworks available for each layer; be it presentation tier, business tier or persistence tier.
The architects can decide upon the choice of the frameworks for different tier based on the requirement. This article is to demonstrate how to integrate the presentation tier using JSF with the persistence tier using JPA. JSF and JPA are two popular frameworks used to develop Java EE applications.
also read:
Problem Statement
In this article, a scenario of generating report on employee details is considered and has been explained with the corresponding code. The module will display the details of the particular employee chosen from a drop down list box. The application starts with a home page (Home.jsp) which has a hyperlink to the report page (EmloyeeHome.jsp). The EmployeeHome.jsp has a drop down with the employee numbers populated dynamically from the database through JPA. Upon selecting a particular employee number the details of the employee will be displayed in the same page.
Raising the application
Step1:
- Create a dynamic web application in a workspace in Eclipse
- For using JPA, add the required project facet.
- Right click on the project and select properties -> Project Facets. Select the checkbox for Java Persistence and click on the “further configuration available…”
- By clicking the link “further configuration available…” “JPA Facet” window will be displayed. Click on “OK” button and come to “Project Facet window”. Click on “OK” button in “Project Facet” window. This will complete the configuration required in Eclipse IDE
Step2:
- The classes12.jar, hibernate-entitymanager.jar, javaee.jar, jboss-faces.jar, jsf-api.jar, jsf-impl.jar, standard.jar, jstl.jar, toplink-essentials.jar, toplink-essentials-agen.jar archive files should be added on to the project to enable JPA and JSF framework in the application. Copy these jar files into the lib folder (Project -> WebContent -> WEB-INF -> lib)
Step3:
- Create a Home.jsp with a hyperlink to EmployeeHome.jsp
- Sample code (Home.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Home page</title> </head> <body> <f:view> <h2> <center> <h:outputLabel>Welcome to the Home Page</h:outputLabel> </center> <h:outputLink value="EmployeeHome.jsp">Employee Details</h:outputLink> </h2> </f:view> </body> </html>
Sample Screen Shot
- When the Employee Details hyperlink is clicked, Employee Home page is displayed.
- Create EmployeeHome.jsp
- Sample Code (EmployeeHome.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Employee Details</title> </head> <body> <f:view> <h2> <center>Welcome to Employee Home Page</center> </h2> <br><br> <h:form> <h2> Select an Employee Number from the drop down: </h2> <br><br> <h:selectOneMenu id="selEmpNo" alueChangeListener="#{employee.employeeReport}" onchange="submit()"> <f:selectItem itemLabel="select" /> <f:selectItems value="#{employee.empNoList}" id="emp"/> </h:selectOneMenu> </h:form> <br><br> <h2> <h:outputText value="Employee Name: "></h:outputText> <h:outputText value="#{employee.empName}"/> <br><br> <h:outputText value="Employee Number: "/> <h:outputText value="#{employee.empNo}"/> <br><br> <h:outputText value="Name of the IBU: "/> <h:outputText value="#{employee.ibu}"/> <br><br> <h:outputText value="Designation: "/> <h:outputText value="#{employee.designation}"/> </h2> </f:view> </body> </html>
Sample Screen shot
Note: In EmployeeHome.jsp, <f:selectItems> is used to dynamically populate the drop down with employee number from the corresponding managed bean. When a particular employee number is selected from the drop down, the corresponding employee details should be displayed. In order to implement this functionality, implement ValueChangeEventListener in the corresponding managed bean and bound the UI component to it. The employeeReport(ValueChangeEvent event) of the EmployeeBean managed bean is the value change even listener in this implementation. Since value change event will not submit the request, some mechanism (E.g., JavaScript function) is required to submit the request after selecting the employee number from the drop down. (In EmployeeHome.jsp, “submit() is assigned to “onChange” attribute of <h:selectOneMenu> tag. Hence no need to write any explicit java script function to submit the form.)
Step5:
- Create a package “employee” under the project
- Create a bean EmployeeBean which is a managed bean (the configuration of the managed bean is available in faces-congig.xml file which is given latter). The attributes of this bean is bound to various UI Components used in EmployeeHome.jsp
- Sample Code (EmployeeBean.java)
package employee; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; public class EmployeeBean { private String empName; private String ibu; private String designation; private int empNo; //This is used to dynamically populate the drop down with employee numbers List<SelectItem>empNoList; public EmployeeBean(){ this.empNoList = new ArrayList<SelectItem>(); /*Populating Employee Number in the drop down - Dynamic */ List<EmployeeEntity>empList = new EmployeeService().getEmployeeList(); Iterator<EmployeeEntity>iterator = empList.iterator(); while(iterator.hasNext()){ EmployeeEntity employee = iterator.next(); SelectItem item = new SelectItem(employee.getEmpNo()); empNoList.add(item); } } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getIbu() { return ibu; } public void setIbu(String ibu) { this.ibu = ibu; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public int getEmpNo() { return empNo; } public void setEmpNo(int empNo) { this.empNo = empNo; } public List<SelectItem> getEmpNoList() { return empNoList; } public void setEmpNoList(List<SelectItem> empNoList) { this.empNoList = empNoList; } public List<EmployeeEntity> getEmpList() { return empList; } public void setEmpList(List<EmployeeEntity> empList) { this.empList = empList; } /*Eventlistener - for fetching an employee record based on the selection of employee number from the drop down*/ public void employeeReport(ValueChangeEvent event){ int empNo = Integer.parseInt((String)event.getNewValue()); EmployeeEntity employee = new EmployeeService().getEmployee(empNo); this.empNo = employee.getEmpNo(); this.empName = employee.getEmpName(); this.ibu = employee.getIbu(); this.designation = employee.getDesignation(); } }
Note: After selecting the employee number from the drop down, to fetch the data from the table, a service class called “EmployeeService” (code is given later) is used which makes use of JPA to fetch the required record from the table.
Step6:
- Inside the package “employee”, create an entity class called “EmployeeEntity.java” which is mapped to an “employee” table
- Sample Code (EmployeeEntity.java)
package employe; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="employee") public class EmployeeEntity { @Id private int empNo; private String empName; private String ibu; private String designation; public int getEmpNo() { return empNo; } public void setEmpNo(int empNo) { this.empNo = empNo; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getIbu() { return ibu; } public void setIbu(String ibu) { this.ibu = ibu; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } }
Step7:
- Inside the package “employee”, create a class called “EmployeeService.java”. This class will interact with the database to fetch the required details
- Sample Code (EmployeeService.java)
package employee; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; public class EmployeeService { public List<EmployeeEntity> getEmployeeList(){ List<EmployeeEntity> empList = new ArrayList<EmployeeEntity>(); EntityManager em = null; try{ EntityManagerFactory emf = Persistence.createEntityManagerFactory("Employee- Details"); em = emf.createEntityManager(); EntityTransaction et = em.getTransaction(); et.begin(); Query query = em.createQuery("select e from EmployeeEntitye"); empList = query.getResultList(); } catch(Exception e){ //log the exception } return empList; } public EmployeeEntity getEmployee(int empNo){ EmployeeEntity employee = new EmployeeEntity(); EntityManager em = null; try{ EntityManagerFactory emf = Persistence.createEntityManagerFactory("Employee- Details"); em = emf.createEntityManager(); EntityTransaction et = em.getTransaction(); employee = em.find(myPackage.EmployeeEntity.class, empNo); } catch(Exception e){ //log the exception } finally{ if( em != null){ em.clear(); } } return employee; } }
Step8:
- Create “persistence.xml” file and keep it inside META-INF folder
- Sample Code (persistence.xml)
<?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="Employee-Details"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class>.EmployeeEntity</class> <properties> <property name="toplink.jdbc.url" value=" jdbc:oracle:thin:@localhost:1521:nr"/> <property name="toplink.jdbc.user" value="scott"/> <property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="toplink.jdbc.password" value="tiger"/> <property name="toplink.ddl-generation" value="update-tables"/> </properties> </persistence-unit> </persistence>
Note: Persistence.xml file is configured for Oracle database. You have to configure according to the database which you want to use and give the values accordingly.
Step9:
- Create “faces-congig.xml” file which contains information about navigation rule and managed bean. Place the file inside WEB-INF
folder - Sample Code (faces-config.xml)
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd" version="1.2"> <navigation-rule> <from-view-id>/Home.jsp</from-view-id> </navigation-rule> <managed-bean> <managed-bean-name>employee</managed-bean-name> <managed-bean-class>employee.EmployeeBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config>
Conclusion
This article demonstrates how to integrate JSF and JPA while developing a web application. Apart from this, the article also illustrates how to use drop down (dynamic) in a JSF enabled JSP and how to make use of value change event listener.
Acknowledgement
I would like to thank my manager Mr. Rajagopalan P, Principal, Education and Research Department, Infosys for the guidance and continuous support. I would like to thank Mr. Satheesha B N, Associate Vice-President, Education and Research Department, Infosys for motivating me to write this article. I would like to thank Mrs. Yuvarani, Lead, Education and Research Department, Infosys for giving valuable suggestions.