Primefaces 5 example

Here is an example on how to use jsf framework to develop a fully blown JavaEE application. when it comes to jsf all should know its a specification from sun and has been implemented by lot many vendors, some of them are “PrimeFaces”, “RichFaces”, “IceFaces”. The advantage of using JSF is the UI components are directly binded to Managed bean properties(value injection). In this example i want to show how to push data to database and retrieve from database to front end. This example is implemented in “Primefaces5.1”, “Maven”, “MySql”.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.jsf.primefaces</groupId>
	<artifactId>PrimeFacesTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>PrimeFacesTutorial</name>
	<description>PrimeFacesTutorial</description>

	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>

	<properties>
		<java.version>1.6</java.version>
		<servlet.version>3.0.1</servlet.version>
		<jsf.version>2.2.4</jsf.version>
		<primefaces.version>5.1</primefaces.version>
	</properties>

	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>${primefaces.version}</version>
		</dependency>
		<!-- JSP Library -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- JSTL Library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>webapp</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>primefaces-tutorial</finalName>
	</build>
</project>

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"
	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>PrimeFaces Web Application</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

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

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>login.xhtml</welcome-file>
	</welcome-file-list>

	<!-- 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>

	<!-- Map these files with JSF -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<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>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

</web-app>

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
	

</faces-config>

Once done with our configuration files let us write the page from which the operations are done.
login.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">

<h:head>
	<h:outputStylesheet name="css/custom-styles.css" />
</h:head>
<body>
	<h:form>
		<p:panelGrid columns="2">
			<p:outputLabel value="FirstName"></p:outputLabel>
			<p:inputText value="#{loginBean.firstName}"></p:inputText>

			<p:outputLabel value="LastName"></p:outputLabel>
			<p:inputText value="#{loginBean.lastName}"></p:inputText>

			<p:outputLabel value="Email"></p:outputLabel>
			<p:inputText value="#{loginBean.emailText}"></p:inputText>

			<p:outputLabel value="Password"></p:outputLabel>
			<p:password value="#{loginBean.password}"></p:password>

			<p:commandButton action="#{loginBean.saveValues()}" value="Submit"></p:commandButton>
		</p:panelGrid>

		<p:dataTable var="loginBean" value="#{loginBean.loginBeans}">
			<p:column headerText="First Name">
				<h:outputText value="#{loginBean.firstName}" />
			</p:column>

			<p:column headerText="Last Name">
				<h:outputText value="#{loginBean.lastName}" />
			</p:column>

			<p:column headerText="Email Id">
				<h:outputText value="#{loginBean.emailText}" />
			</p:column>

			<p:column headerText="Password">
				<h:outputText value="#{loginBean.password}" />
			</p:column>
		</p:dataTable>
	</h:form>

</body>
</html>

let us write a DTO in which we hold the data.

/**
 * 
 */
package com.spark.jsf.vo;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

/**
 * @author Sony
 *
 */
@ManagedBean(name="loginVO")
@SessionScoped
public class LoginBeanVO {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}
	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}
	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	/**
	 * @return the emailText
	 */
	public String getEmailText() {
		return emailText;
	}
	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((emailText == null) ? 0 : emailText.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((password == null) ? 0 : password.hashCode());
		return result;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LoginBeanVO other = (LoginBeanVO) obj;
		if (emailText == null) {
			if (other.emailText != null)
				return false;
		} else if (!emailText.equals(other.emailText))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (password == null) {
			if (other.password != null)
				return false;
		} else if (!password.equals(other.password))
			return false;
		return true;
	}
	
	
}

Here comes the major part of our code, its our backing bean which controls our jsf page. There are lot many concepts involved in the below code, we achieve dependency injection using @ManagedProperty annotation in the below code we have injected the dao and dto objects to backing bean using @ManagedProperty annotation , also we used ExternalContext object to redirect to the jsf page from managed bean.

/**
 * 
 */
package com.spark.jsf.managed.beans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.context.RequestContext;

import com.spark.jsf.dao.impl.LoginSaveDAOImpl;
import com.spark.jsf.vo.LoginBeanVO;
import com.spark.security.EncryptPassword;

/**
 * @author Sony
 *
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	private List<LoginBeanVO> loginBeans = new ArrayList<LoginBeanVO>();

	@ManagedProperty(value = "#{loginVO}")
	private LoginBeanVO loginBeanVO;

	@ManagedProperty(value = "#{loginSaveDao}")
	private LoginSaveDAOImpl loginSaveDAOImpl;

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the emailText
	 */
	public String getEmailText() {
		return emailText;
	}

	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the loginSaveDAOImpl
	 */
	public LoginSaveDAOImpl getLoginSaveDAOImpl() {
		return loginSaveDAOImpl;
	}

	/**
	 * @param loginSaveDAOImpl
	 *            the loginSaveDAOImpl to set
	 */
	public void setLoginSaveDAOImpl(LoginSaveDAOImpl loginSaveDAOImpl) {
		this.loginSaveDAOImpl = loginSaveDAOImpl;
	}

	/**
	 * @return the loginBeanVO
	 */
	public LoginBeanVO getLoginBeanVO() {
		return loginBeanVO;
	}

	/**
	 * @param loginBeanVO
	 *            the loginBeanVO to set
	 */
	public void setLoginBeanVO(LoginBeanVO loginBeanVO) {
		this.loginBeanVO = loginBeanVO;
	}

	/**
	 * @return the loginBeans
	 */
	public List<LoginBeanVO> getLoginBeans() {
		return loginBeans;
	}

	/**
	 * @param loginBeans the loginBeans to set
	 */
	public void setLoginBeans(List<LoginBeanVO> loginBeans) {
		this.loginBeans = loginBeans;
	}
	
	@PostConstruct
	public void getLoginDetails(){
		
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

	public void saveValues() {

		loginBeanVO.setFirstName(firstName);
		loginBeanVO.setLastName(lastName);
		loginBeanVO.setEmailText(emailText);
		EncryptPassword encryptPassword = new EncryptPassword("");
		String encryptedPassword = encryptPassword.encrypt(password);

		loginBeanVO.setPassword(encryptedPassword);
		boolean status = loginSaveDAOImpl.saveCredentialsToDatabase(loginBeanVO);
		
		if(status){
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "User details saved successfully !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
			populateLoginBeanList();
			ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		    try {
				ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Failed to Save user, might be user with same email id already exist !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
		}
		
	}
	
	public void populateLoginBeanList(){
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

}

here our dao layer logic.

/**
 * 
 */
package com.spark.jsf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import com.spark.jsf.db.DBUtil;
import com.spark.jsf.vo.LoginBeanVO;

/**
 * @author Sony
 *
 */
@ManagedBean(name= "loginSaveDao")
@SessionScoped
public class LoginSaveDAOImpl {

	List<LoginBeanVO> loginBeanVOs;
	
	public boolean saveCredentialsToDatabase(LoginBeanVO loginBeanVO) {
		boolean status = false;
		System.out.println(loginBeanVO.getFirstName() + "  "
				+ loginBeanVO.getLastName() + "  " + loginBeanVO.getPassword());
		Connection connection = DBUtil.getDBConnection();
		System.out.println("Got the connection object: " + connection);
		String sql = "insert into login(first_name,last_name,email_id,password) values(?,?,?,?)";
		if (!checkUserWithEmailExist(connection, loginBeanVO.getEmailText())) {
			try {
				PreparedStatement preparedStatement = connection
						.prepareStatement(sql);
				preparedStatement.setString(1, loginBeanVO.getFirstName());
				preparedStatement.setString(2, loginBeanVO.getLastName());
				preparedStatement.setString(3, loginBeanVO.getEmailText());
				preparedStatement.setString(4, loginBeanVO.getPassword());
				preparedStatement.execute();
				System.out.println("--------------- Values Saved to Database ---------------");
				status = true;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out
					.println("------------ user already exist with the same email id ---------------");
			status = false;
		}
		return status;
	}

	private boolean checkUserWithEmailExist(Connection connection,
			String emailText) {
		String sql = "select * from login where email_id = ?";
		boolean userExist = false;
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, emailText);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				userExist = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userExist;
	}
	
	public List<LoginBeanVO> getLoginBeans(){
		loginBeanVOs = new ArrayList<LoginBeanVO>();
		String sql = "select * from login";
		Connection connection = DBUtil.getDBConnection();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				LoginBeanVO beanVO = new LoginBeanVO();
				beanVO.setFirstName(resultSet.getString("first_name"));
				beanVO.setLastName((resultSet.getString("last_name")));
				beanVO.setEmailText((resultSet.getString("email_id")));
				beanVO.setPassword((resultSet.getString("password")));
				loginBeanVOs.add(beanVO);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return loginBeanVOs;
	}
}

The speciality of this example is that i have implemented the PBEWithMD5AndDES algorith for encrypting and decrypting the passwords for security purpose.
SecurityUtils.java

/**
 * 
 */
package com.spark.security;

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 * @author Sony
 *
 */
public class SecurityUtils {

	public static Cipher dCipher, eCipher;
	public SecurityUtils(String helperString) {
		//b-bit salt
		byte[] salt = {(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
                (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03};
		
		// iteration count
		int iterationCount = 19;
		try {
			// generating a temporary key, Encryptinng with DES using a pass key
			
			KeySpec keySpec = new PBEKeySpec(helperString.toCharArray(), salt, iterationCount);
			SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			
			eCipher = Cipher.getInstance(secretKey.getAlgorithm());
			dCipher = Cipher.getInstance(secretKey.getAlgorithm());
			
			AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterationCount);
			
			eCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
			dCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

EncryptPassword.java

/**
 * 
 */
package com.spark.security;

import java.io.UnsupportedEncodingException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

/**
 * @author Sony
 *
 */
public class EncryptPassword extends SecurityUtils{

	public EncryptPassword(String helperString) {
		super(helperString);
	}
	
	public String encrypt(String password){
		 try {
             // Encode the string into bytes using utf-8
             byte[] utf8 = password.getBytes("UTF8");
             // Encrypt
             byte[] enc = eCipher.doFinal(utf8);
             // Encode bytes to base64 to get a string
             return new sun.misc.BASE64Encoder().encode(enc);

      } catch (BadPaddingException e) {
    	  e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
    	  e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
    	  e.printStackTrace();
      }
      return null;
	}
}

DecryptPassword.java

/**
 * 
 */
package com.spark.security;

/**
 * @author Sony
 *
 */
public class DecryptPassword extends SecurityUtils {

	public DecryptPassword(String helperString) {
		super(helperString);
	}

	public String decrypt(String encryptedPassword) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder()
					.decodeBuffer(encryptedPassword);
			// Decrypt
			byte[] utf8 = dCipher.doFinal(dec);
			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}

Let us have a helper class which will create a connection object and return DAO layer.

/**
 * 
 */
package com.spark.jsf.db;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author Sony
 *
 */
public class DBUtil {

	private static Connection connection = null;
	
	private DBUtil(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getDBConnection(){
		if(connection == null){
			return new DBUtil().getConnection();
		}else{
			return connection;
		}
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection the connection to set
	 */
	public  void setConnection(Connection connection) {
		this.connection = connection;
	}
	
}

finally the output is as below.

ui

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s