Wednesday, July 10, 2013

JSF, JSF 2.0 Overview

This blog is for the beginners of JSF to get an overview of the concepts.

In this blog, I am going to touch the following concepts.


1. What is JSF
2. JSF Terminology
3. JSF life cycle
4. Facelets - Included in JSF 2.0
5. Custom components
6. Ajax
7. Component libraries
8. Examples
9. Advantages
10. References 

What is JSF
JavaServer Faces (JSF) is a Java specification for building component-based user interfaces for 
web applications.
It's a standard Java EE web framework.
Well-designed and easy-to-use component-based webframework.
JSF is based on well established MVC design pattern.
There are as far two (major) JSF implementations, namely Oracle Mojarra and Apache MyFaces.

JSF Terminology
The following terminology is used in JSF
1. UI Components 
2. Renderer 
3. Validator 
4. Backing Beans 
5. Converter 
6. Events and Listeners 
7. Messages 
8. Navigation

*Backing Beans
Backing Beans are specialized JavaBeans that collect values from UI Components and implement the event
listeners. Backing Beans control and define the interaction between the UI and the model.
    Ex: *WIP*

JSF life cycle
There are 6 phases in JSF application lifecycle.
1) Restore view
2) Apply request values
3) Process validations
4) Update model values
5) Invoke application
6) Render response
*WIP*

JSF life cycle

Facelets
Facelets is a view technology for JSF.
Support for code reuse through templating and composite components.
Faster compilation time.
High performance rendering.

Custom components
In JSF, a component is a group of interacting classes that together provide a reusable piece of web-based
user interface code. 
A component is made up of three classes that work closely together.
1) Renderer - which creates the client-side representation of the component and takes any input
     from the client and transforms it into something the component can understand
2) UIComponent subclass - This class is responsible for the data and behavior of the component on
     the server side.
3) JSP custom action – The main functions of this class are to allow for configuration of the
    component in a JSP and to attach a particular renderer to the component.




Ajax
By using ajax support you can update JSF elements (h:outputText, h:inputText, h:selectOneMenu, etc.) from
client side itself. You don’t have to write JavaScript
f:ajax tag is used in JSF.

Component libraries
JSF component libraries just adds extra features on top of the basic implementation, They are like
skinnability, ajaxability, enhanceability.
There are lot of JSF component libraries

Advantages
1. JSF is based on well established Model-View-Controller (MVC) design pattern. 
2. Applications developed using JSF frameworks are well designed and easy to maintain then any other
    applications developed in JSP and Servlets.
3. JSF provides standard, reusable components for creating user interfaces for web applications.
4. JSF provides many tag libraries for accessing and manipulating the components.
5. JSF is a specification and vendors can develop the implementations for JSF.

References
JSR-000127 JavaServerTM Faces (Final Release) - http://jcp.org/aboutJava/communityprocess/final/jsr127/



Thursday, September 13, 2012

JSF 2.0, Primefaces 3.3, Spring 3.1 and Hibernate 4.0 Integration step by step


This blog is mainly for the beginners who wants to setup JSF 2.0, Primefaces 3.3, Spring 3.1 and Hibernate 4.0 environment in eclipse.

Frameworks and versions used in this sample project.
Java - 1.6.0
JSF 2.0  - Mojarra 2.1.5 implementation
Primefaces - 3.3.1
Spring  - 3.1
Hibernate - 4.0
Application Server - JBoss 7.1
ojdbc5.jar - to connect to Oracle database
mysql-connector-java-5.1.3-rc-bin.jar - to connect to MySQL.

The sample project which I am going to demonstrate will fetch all the records from the Employee table and displays them in a primefaces table.

Step1

Create a test database in MySQL or Oracle. The following script is to create a table named Employee in MySQL test database.


CREATE TABLE `employee` (
  `EmpID` int(11) NOT NULL,
  `EmpName` varchar(200) DEFAULT NULL,
  `Email` varchar(300) DEFAULT NULL,
  PRIMARY KEY (`EmpID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$


Step2

Create the Employee entity class i.e Employee.java


package com.springHibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Employee")
public class Employee {
@Id
@Column(name="EmpID")
private int empID;

@Column(name="EmpName")
private String empName;

@Column(name="Email")
private String email;

public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {
this.empID = empID;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}


Step 3

Implementing Dao(Data access object) layer.

EmpDao.java


package com.springHibernate.dao;
import java.util.List;
import com.springHibernate.model.Employee;

public interface EmpDao {

public List getAllEmployees();

}

EmpDaoImpl.java


package com.springHibernate.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.springHibernate.model.Employee;

@Repository("empDaoImpl")
public class EmpDaoImpl implements EmpDao{

@Autowired
private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

@SuppressWarnings("unchecked")
@Override
public List getAllEmployees() {
return sessionFactory.getCurrentSession().createQuery("from Employee").list();
}


}

Step 4

Implementing Service layer.



EmpService.java


package com.springHibernate.service;

import java.util.List;

import com.springHibernate.model.Employee;

public interface EmpService {

public List getAllEmployees();

}

EmpServiceImpl.java

package com.springHibernate.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.springHibernate.dao.EmpDao;
import com.springHibernate.model.Employee;


@Service("empServiceImpl")
public class EmpServiceImpl implements EmpService {
@Autowired
EmpDao empDao;
public EmpDao getEmpDao() {
return empDao;
}

public void setEmpDao(EmpDao empDao) {
this.empDao = empDao;
}

@Transactional(readOnly = true)
public List getAllEmployees() {
return empDao.getAllEmployees();
}


Step 5

Implementing view layer. which involves creating index.xhtml and corresponding JSF managedBean.


index.xhtml




<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
  <h:head>
    <link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css" />
    <style type="text/css"> .ui-panel { font-size: 85% !important; font-family: calibri !important; align: "center" !important; } </style>
  </h:head>
  <h:body>
    <p:panel header="ASSET 3000" style="width: 350;">
      <h:form prependId="false">
        <p:dataTable id="basic" var="emp" value="#{employeeBean.empList}">
          <p:column id="nameHeader">
            <f:facet name="header"> Employee Name </f:facet>
            <h:outputText value="#{emp.empName}" />
          </p:column>
          <p:column>
            <f:facet name="header"> Emp Number </f:facet>
            <h:outputText value="#{emp.empID}" />
          </p:column>
          <p:column>
            <f:facet name="header"> Email </f:facet>
            <h:outputText value="#{emp.email}" />
          </p:column>
        </p:dataTable>
      </h:form>
    </p:panel>
  </h:body>
</html>

EmployeeBean.java -- JSF managedBean.



package com.springHibernate.managedBeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedProperty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.springHibernate.model.Employee;
import com.springHibernate.service.EmpService;

@Component
@Scope("request")
public class EmployeeBean {

@Autowired
EmpService empService;

private List empList;

private int empID;
private String empName;
private String email;

public EmpService getEmpService() {
return empService;
}

public void setEmpService(EmpService empService) {
this.empService = empService;
}

public List getEmpList() {
empList = new ArrayList();
empList.addAll(getEmpService().getAllEmployees());
return empList;
}

public void setEmpList(List empList) {
this.empList = empList;
}

public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {
this.empID = empID;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}

Step 6


Finally, the configuration files.


web.xml




<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringHibernate</display-name>
  <context-param>
    <param-name>javax.faces.CONFIG_FILES</param-name>
    <param-value>/WEB-INF/faces-config.xml</param-value>
  </context-param>
  <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>
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>
  <welcome-file-list>
    <welcome-file>/pages/index.xhtml</welcome-file>
  </welcome-file-list>
  <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>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>





application-context.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: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">
  <context:component-scan base-package="com.springHibernate" />
  <context:annotation-config />
  <bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="ASSET" />
  </bean>
  <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="DataSource" />
    <property name="annotatedClasses">
      <list>
        <value>com.springHibernate.model.Employee</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
  </bean>
  <tx:annotation-driven transaction-manager="txManager" />
  <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="SessionFactory" />
  </bean>
</beans>



faces-config.xml



<?xml version="1.0"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" 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">
  <application>
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
  </application>
</faces-config>






Project folder structure in eclipse