SlideShare a Scribd company logo
1 of 21
Download to read offline
Simple Demo:
Spring + Hibernate + JSF, Primefaces Intergration
(Step by Step)
Tool:
- IDE: STS 3.3.0.RELEASE (or Eclipse Kepler with Maven and STS plug-in)
- Server: Apache Tomcat v7.0
- Database: PostgresQSL 9.1, pgAdmin 1.14.0
Used Technologies:
- Spring framework 3.2.3.RELEASE
- Hibernate 4.1.0.Final
- Myfaces 2.1.12 (JSF Implementation)
- Primefaces 3.5
Step 1. Maven
New → Maven Project → Next
Select an Archetype, on Filter: enter “web”, chose “maven-web-archetype” for a
simple Java web application.
Click Next
Click Finish
Test: Run the project!
Step 2. JSF
1. Add dependencies on pom.xml file
<properties>
<myfaces-version>2.1.12</myfaces-version>
</properties>
…
<dependencies>
<!-- MyFaces -->
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>${myfaces-version}</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-impl</artifactId>
<version>${myfaces-version}</version>
</dependency>
<dependencies>
2. Configure web configuration on web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!-- welcome page -->
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
3. Create welcome file index.xhtml
New → Other
And,...
Delete the file index.jsp (redundant)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets" >
<h:head>
<title>My Team</title>
</h:head>
<h:body>
<h2>My Team</h2>
<hr/>
<h:outputText value="Hello JSF"/>
</h:body>
</html>
Test: Run the project!
Step 3. JSF and Primefaces
Add dependency on pom.xml file
<properties>
...
<primefaces-version>3.5</primefaces-version>
</properties>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
…
<!-- Primefaces →
<dependencies>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>${primefaces-version}</version>
</dependency>
</dependencies>
Update index.xhtml file
Add namespace
xmlns:p="http://primefaces.org/ui" as property of “html tag”
Use “p:editor tag” inside “h:body tag”
<p:editor value="Hello Primefaces"/>
Test: Run the project!
Right-click on project New → Folder, create folder “src/main/java”
Create three classes in the “src/main/java” folder, here:
package: com.ant.myteam.model
Employee.java
package com.ant.myteam.model;
import java.io.Serializable;
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private Long empId;
private String firstName;
private String lastName;
private String gender;
private String company;
private String team;
private String phone;
private String job;
private String imagePath;
private String email;
private Department department;
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
Deparment.java
package com.ant.myteam.model;
import java.io.Serializable;
import java.util.List;
public class Department implements Serializable{
private static final long serialVersionUID = 1L;
private Long deptId;
private String depName;
private List<Employee> employees;
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
package: com.ant.myteam.managedbean
EmployeeBean.java
package com.ant.myteam.managedbean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import com.ant.myteam.model.Department;
import com.ant.myteam.model.Employee;
@ManagedBean(name ="empBean")
public class EmployeeBean implements Serializable{
private static final long serialVersionUID = 1L;
private Employee employee=new Employee();
public Employee getEmployee() {
employee.setEmpId(1L);
employee.setDepartment(new Department());
employee.setFirstName("Ant");
employee.setLastName("Team");
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
Update index.html
<h3>Hello</h3>
<h:outputText value="#{empBean.employee.firstName} #{empBean.employee.lastName}"/>
Test: Run the project!
Step 4. JSF and Spring
Add Spring framework dependencies
<properties>
...
<org.springframework-version>3.2.3.RELEASE</org.springframework-version>
</properties>
<dependencies>
<!-- Spring Framework-->
<!-- Support for JSF -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework-version}</version>
</dependency>
</dependencies>
Spring configuration on web.xml
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
Create WEB_INF/face-config.xml file
<?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_2_0.xsd"
version="2.0">
<!-- JSF and Spring are integrated -->
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
Create package “com.ant.myteam.service” and two files in this package
EmployeeService.java
package com.ant.myteam.service;
import com.ant.myteam.model.Employee;
public interface EmployeeService {
public Employee findEmployeeById(long empId);
}
EmployeeServiceImp.java
package com.ant.myteam.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.ant.myteam.model.Employee;
@Service
public class EmployeeServiceImpl implements EmployeeService,Serializable {
private static final long serialVersionUID = 1L;
private List<Employee> empList=new ArrayList<Employee>();
public EmployeeServiceImpl(){
Employee emp1 = new Employee();
emp1.setEmpId(1L);
emp1.setFirstName("Huong");
emp1.setLastName("Nguyen");
Employee emp2 = new Employee();
emp2.setEmpId(2L);
emp2.setFirstName("Khang");
emp2.setLastName("Le");
empList.add(emp1);
empList.add(emp2);
}
public Employee findEmployeeById(long empId) {
for(Employee emp: empList){
if(emp.getEmpId()==empId){
return emp;
}
}
return null;
}
}
EmployeeBean.java
package com.ant.myteam.managedbean;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ant.myteam.model.Employee;
import com.ant.myteam.service.EmployeeService;
@Component("empBean")
public class EmployeeBean implements Serializable{
private static final long serialVersionUID = 1L;
private Employee employee=new Employee();
@Autowired
private EmployeeService empService;
public Employee getEmployee() {
employee= empService.findEmployeeById(1L);
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
Create WEB-INF/applicationContext.xml file
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Enable autowire -->
<context:annotation-config />
<!-- Enable component scanning -->
<context:component-scan base-package="com.ant.myteam" />
</beans>
Test: Run the project!
Step 5. JSF, Spring and Hibernate
Add dependencies
JDBCs and Hibernate API
<properties>
...
<hibernate-version>4.1.0.Final</hibernate-version>
</propertise>
<!-- PostgreSQL JDBC Driver -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- Apache DBCP Library (manage connection to data source) -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
Spring ORM framework support for integrated with Hibernate
<!-- Integration with Hibernate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
Configure in applicationContext.xml, add these lines
<!-- Data Source Declaration -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-
method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/myteam"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<!-- Session Factory Declaration -->
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="com.ant.myteam.model" />
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">myteam</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Transaction Manager is defined -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
modify model classes:
Employee.java
package com.ant.myteam.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "Employee")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long empId;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
private String gender;
private String company;
private String team;
private String phone;
private String job;
private String imagePath;
private String email;
@ManyToOne
@JoinColumn(name = "deptId")
private Department department;
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
Department.java
package com.ant.myteam.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Department")
public class Department implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long deptId;
@Column(nullable = false)
private String depName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "deptId")
private List<Employee> employees;
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
}
create package: “com.ant.myteam.dao” with two files
EmployeeDao.java
package com.ant.myteam.dao;
import com.ant.myteam.model.Employee;
public interface EmployeeDao {
public boolean addEmployee(Employee emp);
public Employee findEmployeeById(long empId);
}
EmployeeDaoImpl.java
package com.ant.myteam.dao;
import java.io.Serializable;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ant.myteam.model.Employee;
@Repository
@Transactional
public class EmployeeDaoImpl implements EmployeeDao, Serializable{
private static final long serialVersionUID = 1L;
@Autowired
private SessionFactory sessionFactory;
public boolean addEmployee(Employee emp) {
try {
sessionFactory.getCurrentSession().save(emp);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public Employee findEmployeeById(long empId) {
Employee result = new Employee();
try {
result=(Employee)
sessionFactory.getCurrentSession().get(Employee.class, empId);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Modify EmployeeServiceImpl.java
package com.ant.myteam.service;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ant.myteam.dao.EmployeeDao;
import com.ant.myteam.model.Employee;
@Service
public class EmployeeServiceImpl implements EmployeeService,Serializable {
private static final long serialVersionUID = 1L;
@Autowired
private EmployeeDao empDao;
public Employee findEmployeeById(long empId) {
return empDao.findEmployeeById(empId);
}
public boolean addEmployee(Employee emp) {
return empDao.addEmployee(emp);
}
}
Modify EmployeeBean.java
package com.ant.myteam.managedbean;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ant.myteam.model.Employee;
import com.ant.myteam.service.EmployeeService;
@Component("empBean")
public class EmployeeBean implements Serializable{
private static final long serialVersionUID = 1L;
private Employee employee=new Employee();
@Autowired
private EmployeeService empService;
private Employee emp1;
private Employee emp2;
public EmployeeBean(){
emp1 = new Employee();
emp1.setFirstName("Huong");
emp1.setLastName("Nguyen");
emp2 = new Employee();
emp2.setFirstName("Khang");
emp2.setLastName("Le");
}
public void addEmployee(){
empService.addEmployee(emp1);
empService.addEmployee(emp2);
employee= empService.findEmployeeById(emp1.getEmpId());
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
index.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>My Team</title>
</h:head>
<h:body>
<h2>My Team</h2>
<hr/>
<h:outputText value="Hello JSF"/>
<p:editor value="Hello Primefaces"/>
<h:form id="empForm">
<p:commandButton value="Add default"
action="#{empBean.addEmployee}" update="empForm"/>
<h3>Hello</h3>
<h:outputText id="employeeId"
value="#{empBean.employee.firstName} #{empBean.employee.lastName}"/>
</h:form>
</h:body>
</html>
create database and schemas with name “myteam”
Test: Run the project!
Spring hibernate jsf_primefaces_intergration

More Related Content

What's hot

1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example usingIevgenii Katsan
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best PracticesEdorian
 
New Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian BergmannNew Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian Bergmanndpc
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Eheinovex GmbH
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsStephen Chin
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationBTI360
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher Bartling
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 

What's hot (20)

1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
PhpUnit Best Practices
PhpUnit Best PracticesPhpUnit Best Practices
PhpUnit Best Practices
 
New Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian BergmannNew Features PHPUnit 3.3 - Sebastian Bergmann
New Features PHPUnit 3.3 - Sebastian Bergmann
 
7.Spring DI_2
7.Spring DI_27.Spring DI_2
7.Spring DI_2
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
6.Spring DI_1
6.Spring DI_16.Spring DI_1
6.Spring DI_1
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise Applications
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 

Viewers also liked

Dan ochsner final project
Dan ochsner final projectDan ochsner final project
Dan ochsner final projectdanochsner
 
위기의지방자치 인구분포
위기의지방자치 인구분포위기의지방자치 인구분포
위기의지방자치 인구분포ohsoontak
 
Location of smartphone usage in malaysia in 2013
Location of smartphone usage in malaysia in 2013Location of smartphone usage in malaysia in 2013
Location of smartphone usage in malaysia in 2013nat harleyy
 
Who is dan ochsner (assignment 3a)
Who is dan ochsner (assignment 3a)Who is dan ochsner (assignment 3a)
Who is dan ochsner (assignment 3a)danochsner
 
Dan ochsner united way
Dan ochsner  united wayDan ochsner  united way
Dan ochsner united waydanochsner
 
Single-Page Lab - ASNApalooza 2014
Single-Page Lab - ASNApalooza 2014Single-Page Lab - ASNApalooza 2014
Single-Page Lab - ASNApalooza 2014John Nickell
 
EC102 Syllabus SY14-15
EC102 Syllabus SY14-15EC102 Syllabus SY14-15
EC102 Syllabus SY14-15rlancechua
 

Viewers also liked (8)

Dan ochsner final project
Dan ochsner final projectDan ochsner final project
Dan ochsner final project
 
위기의지방자치 인구분포
위기의지방자치 인구분포위기의지방자치 인구분포
위기의지방자치 인구분포
 
Location of smartphone usage in malaysia in 2013
Location of smartphone usage in malaysia in 2013Location of smartphone usage in malaysia in 2013
Location of smartphone usage in malaysia in 2013
 
Who is dan ochsner (assignment 3a)
Who is dan ochsner (assignment 3a)Who is dan ochsner (assignment 3a)
Who is dan ochsner (assignment 3a)
 
Dan ochsner united way
Dan ochsner  united wayDan ochsner  united way
Dan ochsner united way
 
eteleb
etelebeteleb
eteleb
 
Single-Page Lab - ASNApalooza 2014
Single-Page Lab - ASNApalooza 2014Single-Page Lab - ASNApalooza 2014
Single-Page Lab - ASNApalooza 2014
 
EC102 Syllabus SY14-15
EC102 Syllabus SY14-15EC102 Syllabus SY14-15
EC102 Syllabus SY14-15
 

Similar to Spring hibernate jsf_primefaces_intergration

名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
2. Create a Java class called EmployeeMain within the same project Pr.docx
 2. Create a Java class called EmployeeMain within the same project Pr.docx 2. Create a Java class called EmployeeMain within the same project Pr.docx
2. Create a Java class called EmployeeMain within the same project Pr.docxajoy21
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Jim Shingler
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)ENDelt260
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Four Ways to add Features to Ext JS
Four Ways to add Features to Ext JSFour Ways to add Features to Ext JS
Four Ways to add Features to Ext JSShea Frederick
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Michael Plöd
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 

Similar to Spring hibernate jsf_primefaces_intergration (20)

Manual tecnic sergi_subirats
Manual tecnic sergi_subiratsManual tecnic sergi_subirats
Manual tecnic sergi_subirats
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
My java file
My java fileMy java file
My java file
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
2. Create a Java class called EmployeeMain within the same project Pr.docx
 2. Create a Java class called EmployeeMain within the same project Pr.docx 2. Create a Java class called EmployeeMain within the same project Pr.docx
2. Create a Java class called EmployeeMain within the same project Pr.docx
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
3 j unit
3 j unit3 j unit
3 j unit
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Four Ways to add Features to Ext JS
Four Ways to add Features to Ext JSFour Ways to add Features to Ext JS
Four Ways to add Features to Ext JS
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 

Recently uploaded

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 

Recently uploaded (20)

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 

Spring hibernate jsf_primefaces_intergration

  • 1. Simple Demo: Spring + Hibernate + JSF, Primefaces Intergration (Step by Step) Tool: - IDE: STS 3.3.0.RELEASE (or Eclipse Kepler with Maven and STS plug-in) - Server: Apache Tomcat v7.0 - Database: PostgresQSL 9.1, pgAdmin 1.14.0 Used Technologies: - Spring framework 3.2.3.RELEASE - Hibernate 4.1.0.Final - Myfaces 2.1.12 (JSF Implementation) - Primefaces 3.5 Step 1. Maven New → Maven Project → Next Select an Archetype, on Filter: enter “web”, chose “maven-web-archetype” for a simple Java web application. Click Next
  • 2. Click Finish Test: Run the project! Step 2. JSF
  • 3. 1. Add dependencies on pom.xml file <properties> <myfaces-version>2.1.12</myfaces-version> </properties> … <dependencies> <!-- MyFaces --> <dependency> <groupId>org.apache.myfaces.core</groupId> <artifactId>myfaces-api</artifactId> <version>${myfaces-version}</version> </dependency> <dependency> <groupId>org.apache.myfaces.core</groupId> <artifactId>myfaces-impl</artifactId> <version>${myfaces-version}</version> </dependency> <dependencies> 2. Configure web configuration on web.xml file <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <!-- welcome page --> <welcome-file-list> <welcome-file>index.xhtml</welcome-file> </welcome-file-list> </web-app> 3. Create welcome file index.xhtml New → Other
  • 4. And,... Delete the file index.jsp (redundant)
  • 5. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" > <h:head> <title>My Team</title> </h:head> <h:body> <h2>My Team</h2> <hr/> <h:outputText value="Hello JSF"/> </h:body> </html> Test: Run the project!
  • 6. Step 3. JSF and Primefaces Add dependency on pom.xml file <properties> ... <primefaces-version>3.5</primefaces-version> </properties> <repositories> <repository> <id>prime-repo</id> <name>PrimeFaces Maven Repository</name> <url>http://repository.primefaces.org</url> <layout>default</layout> </repository> </repositories> … <!-- Primefaces → <dependencies> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>${primefaces-version}</version> </dependency> </dependencies> Update index.xhtml file Add namespace xmlns:p="http://primefaces.org/ui" as property of “html tag” Use “p:editor tag” inside “h:body tag” <p:editor value="Hello Primefaces"/> Test: Run the project!
  • 7. Right-click on project New → Folder, create folder “src/main/java” Create three classes in the “src/main/java” folder, here: package: com.ant.myteam.model Employee.java package com.ant.myteam.model; import java.io.Serializable; public class Employee implements Serializable{ private static final long serialVersionUID = 1L; private Long empId; private String firstName; private String lastName; private String gender; private String company; private String team; private String phone; private String job; private String imagePath; private String email; private Department department; public Long getEmpId() { return empId; } public void setEmpId(Long empId) { this.empId = empId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team;
  • 8. } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } Deparment.java package com.ant.myteam.model; import java.io.Serializable; import java.util.List; public class Department implements Serializable{ private static final long serialVersionUID = 1L; private Long deptId; private String depName; private List<Employee> employees; public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } public String getDepName() { return depName; } public void setDepName(String depName) {
  • 9. this.depName = depName; } public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } } package: com.ant.myteam.managedbean EmployeeBean.java package com.ant.myteam.managedbean; import java.io.Serializable; import javax.faces.bean.ManagedBean; import com.ant.myteam.model.Department; import com.ant.myteam.model.Employee; @ManagedBean(name ="empBean") public class EmployeeBean implements Serializable{ private static final long serialVersionUID = 1L; private Employee employee=new Employee(); public Employee getEmployee() { employee.setEmpId(1L); employee.setDepartment(new Department()); employee.setFirstName("Ant"); employee.setLastName("Team"); return employee; } public void setEmployee(Employee employee) { this.employee = employee; } } Update index.html <h3>Hello</h3> <h:outputText value="#{empBean.employee.firstName} #{empBean.employee.lastName}"/> Test: Run the project!
  • 10. Step 4. JSF and Spring Add Spring framework dependencies <properties> ... <org.springframework-version>3.2.3.RELEASE</org.springframework-version> </properties> <dependencies> <!-- Spring Framework--> <!-- Support for JSF --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework-version}</version> </dependency> </dependencies> Spring configuration on web.xml <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> Create WEB_INF/face-config.xml file <?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee"
  • 11. 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_2_0.xsd" version="2.0"> <!-- JSF and Spring are integrated --> <application> <el-resolver> org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application> </faces-config> Create package “com.ant.myteam.service” and two files in this package EmployeeService.java package com.ant.myteam.service; import com.ant.myteam.model.Employee; public interface EmployeeService { public Employee findEmployeeById(long empId); } EmployeeServiceImp.java package com.ant.myteam.service; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.ant.myteam.model.Employee; @Service public class EmployeeServiceImpl implements EmployeeService,Serializable { private static final long serialVersionUID = 1L; private List<Employee> empList=new ArrayList<Employee>(); public EmployeeServiceImpl(){ Employee emp1 = new Employee(); emp1.setEmpId(1L); emp1.setFirstName("Huong"); emp1.setLastName("Nguyen"); Employee emp2 = new Employee(); emp2.setEmpId(2L); emp2.setFirstName("Khang"); emp2.setLastName("Le"); empList.add(emp1); empList.add(emp2); } public Employee findEmployeeById(long empId) { for(Employee emp: empList){ if(emp.getEmpId()==empId){ return emp;
  • 12. } } return null; } } EmployeeBean.java package com.ant.myteam.managedbean; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.ant.myteam.model.Employee; import com.ant.myteam.service.EmployeeService; @Component("empBean") public class EmployeeBean implements Serializable{ private static final long serialVersionUID = 1L; private Employee employee=new Employee(); @Autowired private EmployeeService empService; public Employee getEmployee() { employee= empService.findEmployeeById(1L); return employee; } public void setEmployee(Employee employee) { this.employee = employee; } } Create WEB-INF/applicationContext.xml file <?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  • 13. <!-- Enable autowire --> <context:annotation-config /> <!-- Enable component scanning --> <context:component-scan base-package="com.ant.myteam" /> </beans> Test: Run the project! Step 5. JSF, Spring and Hibernate Add dependencies JDBCs and Hibernate API <properties> ... <hibernate-version>4.1.0.Final</hibernate-version> </propertise> <!-- PostgreSQL JDBC Driver --> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> <!-- Apache DBCP Library (manage connection to data source) --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId>
  • 14. <version>${hibernate-version}</version> </dependency> Spring ORM framework support for integrated with Hibernate <!-- Integration with Hibernate --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> </dependency> Configure in applicationContext.xml, add these lines <!-- Data Source Declaration --> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy- method="close"> <property name="driverClassName" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql://localhost:5432/myteam"/> <property name="username" value="postgres"/> <property name="password" value="postgres"/> </bean> <!-- Session Factory Declaration --> <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="packagesToScan" value="com.ant.myteam.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.enable_lazy_load_no_trans">true</prop> <prop key="hibernate.default_schema">myteam</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean> <!-- Enable the configuration of transactional behavior based on annotations --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- Transaction Manager is defined --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> modify model classes: Employee.java package com.ant.myteam.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table;
  • 15. @Entity @Table(name = "Employee") public class Employee implements Serializable{ private static final long serialVersionUID = 1L; @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long empId; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; private String gender; private String company; private String team; private String phone; private String job; private String imagePath; private String email; @ManyToOne @JoinColumn(name = "deptId") private Department department; public Long getEmpId() { return empId; } public void setEmpId(Long empId) { this.empId = empId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public String getPhone() {
  • 16. return phone; } public void setPhone(String phone) { this.phone = phone; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } Department.java package com.ant.myteam.model; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "Department") public class Department implements Serializable{ private static final long serialVersionUID = 1L; @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long deptId; @Column(nullable = false) private String depName;
  • 17. @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "deptId") private List<Employee> employees; public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } public String getDepName() { return depName; } public void setDepName(String depName) { this.depName = depName; } } create package: “com.ant.myteam.dao” with two files EmployeeDao.java package com.ant.myteam.dao; import com.ant.myteam.model.Employee; public interface EmployeeDao { public boolean addEmployee(Employee emp); public Employee findEmployeeById(long empId); } EmployeeDaoImpl.java package com.ant.myteam.dao; import java.io.Serializable; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.ant.myteam.model.Employee; @Repository @Transactional public class EmployeeDaoImpl implements EmployeeDao, Serializable{ private static final long serialVersionUID = 1L; @Autowired private SessionFactory sessionFactory;
  • 18. public boolean addEmployee(Employee emp) { try { sessionFactory.getCurrentSession().save(emp); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public Employee findEmployeeById(long empId) { Employee result = new Employee(); try { result=(Employee) sessionFactory.getCurrentSession().get(Employee.class, empId); return result; } catch (Exception e) { e.printStackTrace(); } return result; } } Modify EmployeeServiceImpl.java package com.ant.myteam.service; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ant.myteam.dao.EmployeeDao; import com.ant.myteam.model.Employee; @Service public class EmployeeServiceImpl implements EmployeeService,Serializable { private static final long serialVersionUID = 1L; @Autowired private EmployeeDao empDao; public Employee findEmployeeById(long empId) { return empDao.findEmployeeById(empId); } public boolean addEmployee(Employee emp) { return empDao.addEmployee(emp); } } Modify EmployeeBean.java package com.ant.myteam.managedbean; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired;
  • 19. import org.springframework.stereotype.Component; import com.ant.myteam.model.Employee; import com.ant.myteam.service.EmployeeService; @Component("empBean") public class EmployeeBean implements Serializable{ private static final long serialVersionUID = 1L; private Employee employee=new Employee(); @Autowired private EmployeeService empService; private Employee emp1; private Employee emp2; public EmployeeBean(){ emp1 = new Employee(); emp1.setFirstName("Huong"); emp1.setLastName("Nguyen"); emp2 = new Employee(); emp2.setFirstName("Khang"); emp2.setLastName("Le"); } public void addEmployee(){ empService.addEmployee(emp1); empService.addEmployee(emp2); employee= empService.findEmployeeById(emp1.getEmpId()); } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } } index.xhtml <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:head> <title>My Team</title> </h:head> <h:body> <h2>My Team</h2> <hr/> <h:outputText value="Hello JSF"/> <p:editor value="Hello Primefaces"/> <h:form id="empForm"> <p:commandButton value="Add default" action="#{empBean.addEmployee}" update="empForm"/> <h3>Hello</h3>