This simple
application is a Create, Retrieve, Update and Delete application operating on
an ‘User’ table in ‘test’ database in MySQL Database Server. It is a JPA(Java Persistence
API) and Hibernate-Annotation based application.
To integrate Login and Maven please follow the article at below mentioned URL
http://mrbool.com/java-web-creating-a-login-screen-with-jpa-jsf-primefaces-and-mysql/34397
Softwares
Used
1.JDK8u25
2.Netbeans
8.02
3.MySQL
5.*(or XAMPP)
4.MySQL
Connector 5.*
5.Hibernate
4.3.** and Primefaces 5.0(Bundled with Netbeans)
Steps
1.Install
JDK8 or Jdk7 if not installed
2.Install
Netbeans and associated ApacheTomcat Server
3.Install MySQL Database server or XAMPP(For easy
management of MySQL ) .
After
Installing Netbeans click the services tab on the left.Expand Database node.
Expand Drivers node. Right click MySQL(Connector/Jdriver) then connect. Put
test as the database. As shown below. Put password if you have given password
at the time of installation of MySQL database server. For
XAMPP no password is required. Then test connection. If successful click
finish button.
Create user
table by running below SQL in ‘test’ database
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL
auto_increment,
`RecordNo`
varchar(20) DEFAULT NULL,
`Name` varchar(50)
DEFAULT NULL,
`Age` int(11)
DEFAULT NULL,
`Sex` varchar(20)
DEFAULT NULL,
`Dob` date DEFAULT
NULL,
`Remark` varchar(50)
DEFAULT NULL
PRIMARY KEY
(`id`)
)
ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Insert these
Records below by executing below insert statement
INSERT INTO
`user` (`id`, `RecordNo`, `Name`, `Age`, `Sex`, `Dob`, `Remark`) VALUES
(1, '1',
'Raichand', 48, 'Male', '2014-06-16', 'Good Person'),
(2, '2',
'Ramesh', 45, 'Male', '2013-03-18', 'Good Person'),
(3, '3',
'smita', 47, 'Female', '1996-01-09', 'Jolly Lady'),
(4, '4',
'Sarita', 37, 'Female', '1998-01-07', 'good beautiful lady'),
(7, '7',
'Rashmi', 23, 'Male', '2016-01-25', 'good person'),
(9, '9',
'Deepak', 21, 'Male', '2016-01-26', 'good person'),
(10, '10',
'Jyoti Rath', 21, 'Male', '2016-01-26', 'good person'),
(11, '11', 'Sruti
Rath', 21, 'Male', '2016-01-26', 'good person'),
(13, '13',
'Pradipta Prusty', 34, 'Male', '2016-01-18', 'good person'),
(14, '14',
'sunita misra', 21, 'Female', '2016-01-27', 'good lady'),
(15, '15',
'sibananda mitra', 32, 'Male', '2016-01-25', 'good person'),
(16, '16',
'smita rath', 23, 'Female', '2016-01-20', 'good lady'),
(17, '17',
'Smita satpathy', 21, 'Female', '2016-01-26', 'good lady'),
(18, '18',
'N.C Das', 32, 'Male', '2016-01-26', 'Good Person'),
(26, '19',
'sarita subudhi', 43, 'Female', '2016-01-26', 'good lady'),
(27, '27',
'Ravi Mohanty', 44, 'Male', '2016-01-26', 'good person'),
(28, '28',
'Sita', 23, 'Female', '2016-02-23', 'good lady');
Creating Project UserCRUD_Annotation
File-àNew
ProjectàCategories-àChoose JavaWeb--àChoose WebApplicationàClick Next-àGive Project Name Primefaces_JPAHibernateMySQL_USER_CRUDàClick NextàClick NextàChoose Framework First
Hibernate then Java Server Faces--àClick
Component Tab-àChoose
PrimefacesàClick
Finish
Download mysql-
connector-java-bin.jar add to libraries folder by right clickingàAdd JAR/Folderà select it.
Project Structure
Creating Packages and Classes
Right click Source
Package folder and create four packages
1.
com.controller.bean-->This would contain JSF Managed Bean Class UsererBean.java
2.com.dao-àThis would contain DAO(Data Access
Object) class UsererDao.java
3.com.model.pojo-àThis would contain entity(POJO) class User.java.POJO Stands for Plain Old Java Objects
Following
Files would be created using Netbeans
1. hibernate.cfg,xml File-àAutomatically generated and would be
deleted after used to create User.java File
2. Reverse
Engineering File-àhibernate.reveng.xmlà Automatically generated and would be
deleted after used to create User.java File
3.Entity(POJO)
File-àUser.java(POJO stands for Plain Old Java Objects)
4.JSF Managed Bean File-àUserBean.java
5.DataAccessObject(DAO) File-àUserDao.java
6.Persistence.xml File
7.Index.xhtml(Automatically
generated)àAdds
new user and displays all users information
8.Search.xhtmlàSearch a user then edit or
delete it
9.UserCrud.xhtmlàIt is an independent file to
be run independently by selecting it in TOC and running it by Run(From Menu)àRun File
10.web.xml(Automatically
generated)
Download mysql-
connector-java-bin.jar add to libraries folder by right clickingàAdd JAR/Folderà select it.
COPY
AND PASTE CODE OF THE FILE GIVEN BELOW
WHOSE CODE IS NOT GENERATED
1.Hibernate.cfg.xml File(Automatically generated,Deleted after
creation of User.java class using it)
As
XAMPP is used so there is no password in
the file only username is given that
is root in Hibernate.cfg.xml File.
Code:-
<?xml
version="1.0" encoding="UTF-8"?>
<!DOCTYPE
hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull</property>
<property
name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">
</property>
<property
name="hibernate.connection.pool_size">10</property>
<property
name="show_sql">true</property>
<property
name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property
name="hibernate.hbm2ddl.auto">update</property>
<mapping
class="com.model.pojo.User"/>
</session-factory>
</hibernate-configuration>
2. Creating Reverse Engineering File-àhibernate.reveng.xml(It is deleted after used to create User.java class)
.
Right Click default package in the Source Package-ànewàchoose Hibernate Reverse
Engineering Wizardàclick
nextàchoose user tableàAdd àclick finish.
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC
"-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="test"/>
<table-filter
match-name="user"/>
</hibernate-reverse-engineering>
3. Creating
Hibernate Entity (pojo) File:-user.java
Important:To create this file MySQL
database test most be connected through Netbeans.
Right click
com.model package--ànew-àHibernate Mappling Files and pojos from databaseàDonot select mapping file &
select EJB3.0 Pattern àClick Finish
User.java CODE:(Please Compare this
with generated code and modify if required)
package
com.model.pojo;
// Generated
May 23, 2016 12:30:14 PM by Hibernate Tools 4.3.1
import
java.util.Date;
import
javax.persistence.Column;
import
javax.persistence.Entity;
import
javax.persistence.GeneratedValue;
import
static javax.persistence.GenerationType.IDENTITY;
import
javax.persistence.Id;
import
javax.persistence.Table;
import
javax.persistence.Temporal;
import
javax.persistence.TemporalType;
/**
* User generated by hbm2java
*/
@Entity
@Table(name="user"
,catalog="test"
)
public class
User implements java.io.Serializable {
private Integer id;
private String recordNo;
private String name;
private Integer age;
private String sex;
private Date dob;
private String remark;
public User() {
}
public User(String recordNo, String name,
Integer age, String sex, Date dob, String remark) {
this.recordNo = recordNo;
this.name = name;
this.age = age;
this.sex = sex;
this.dob = dob;
this.remark = remark;
}
@Id
@GeneratedValue(strategy=IDENTITY)
@Column(name="id", unique=true,
nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="RecordNo",
length=20)
public String getRecordNo() {
return this.recordNo;
}
public void setRecordNo(String recordNo) {
this.recordNo = recordNo;
}
@Column(name="Name", length=50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="Age")
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
@Column(name="Sex", length=20)
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Temporal(TemporalType.DATE)
@Column(name="Dob", length=10)
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Column(name="Remark", length=50)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
//This method writes the values of contact
object with System.out.println(user.toString()) code
@Override
public String toString() {
return "user"
+ "\n\t RecordNo: " +
this.recordNo
+ "\n\t EmployeeName: " +
this.name
+ "\n\t Age: " + this.age
+ "\n\t Sex: " + this.sex
+ "\n\t Date of Birth: " +
this.dob
+ "\n\t Remark: " + this.remark;
}
}
4. Creating
JSF Managed Bean File
UserBean.java File
Right
click com.controller package--ànew-àotheràJava ServerFacesàJSF Managed BeanàGive class name UsererBean-à click finish.
UserBean.java File CODE:
package
com.controller.bean;
import
javax.faces.bean.ManagedBean;
import
javax.faces.bean.ViewScoped;
import
java.util.List;
import
com.dao.UserDAO;
import
com.model.pojo.User;
import
java.io.Serializable;
import
javax.persistence.EntityNotFoundException;
import
java.util.Iterator;
import
org.primefaces.event.RowEditEvent;
import
javax.faces.context.FacesContext;
import
javax.faces.application.FacesMessage;
import
org.primefaces.context.RequestContext;
/**
*
* @author Raichand
*/
@ManagedBean(name
= "userBean")
@ViewScoped
public class
UserBean implements Serializable {
private List<User> usersList;
private List<User> searchList;
private List<User>
searchByRecordNoList;
private List<User>
selectedUsers;
UserDAO userDao = new UserDAO();
User user = new User();
User newuser = new User();
public List<User> getUsers()
{
usersList = userDao.getAllUsers();
int count = usersList.size();
return usersList;
}
public void addUser(){
String Remark = newuser.getRemark();
Integer userId=0;
userId= userDao.getNewUserId();
newuser.setId(userId);
String Id =
Integer.toString(newuser.getId());
System.out.println("New User
Id:-"+ Id);
newuser.setRecordNo(Integer.toString(userId));
userDao.add(newuser);
System.out.println("User
successfully saved.");
FacesMessage message= new
FacesMessage(FacesMessage.SEVERITY_INFO, "Save
Information","User successfully saved.");
RequestContext.getCurrentInstance().showMessageInDialog(message);
newuser = new User();
}
public void changeUser(User user) {
this.user= user;
}
public void UpdateUser(User user){
String Name =
user.getName();
// FacesMessage message1= new
FacesMessage(FacesMessage.SEVERITY_INFO, "Name",Name);
//
RequestContext.getCurrentInstance().showMessageInDialog(message1);
userDao.update(user);
System.out.println("User
Info successfully saved.");
FacesMessage message= new
FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information","User
updated successfully .");
RequestContext.getCurrentInstance().showMessageInDialog(message);
user = new User();
}
public void deleteSingleUser(User
user){
userDao.delete(user);
FacesMessage message= new
FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Record
deleted successfully");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public void deleteUser(){
int Size =
selectedUsers.size();
System.out.println("No of
Selected User For Deletion:-"+ Integer.toString(Size));
for (Iterator iterator =
selectedUsers.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
try
{
userDao.delete(user);
}
catch(EntityNotFoundException
e)
{
System.out.println("User
does not exist.");
}
}
FacesMessage message= new
FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Record
deleted successfully");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public void searchbyRecordno(){
searchByRecordNoList=userDao.SearchByRecordNo(user.getRecordNo());
int count =
searchByRecordNoList.size();
FacesMessage message = new
FacesMessage(FacesMessage.SEVERITY_INFO, "Number of Record
Selected:", Integer.toString(count));
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public User getNewuser() {
return newuser;
}
public void setNewuser(User newuser) {
this.newuser = newuser;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User>
usersList) {
this.usersList = usersList;
}
public List<User> getSearchList() {
return searchList;
}
public void setSearchList(List<User>
searchList) {
this.searchList = searchList;
}
public List<User>
getSearchByRecordNoList() {
return searchByRecordNoList;
}
public void
setSearchByRecordNoList(List<User> searchByRecordNoList) {
this.searchByRecordNoList =
searchByRecordNoList;
}
public List<User> getSelectedUsers()
{
return selectedUsers;
}
public void
setSelectedUsers(List<User> selectedUsers) {
this.selectedUsers = selectedUsers;
}
public void onRowEdit(RowEditEvent event)
{
FacesMessage msg = new
FacesMessage(" Edited Record No", ((User)
event.getObject()).getRecordNo());
FacesContext.getCurrentInstance().addMessage(null, msg);
User editeduser = (User) event.getObject();
userDao.update(editeduser);
}
public void onCancel(RowEditEvent event)
{
FacesMessage msg = new
FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
usersList.remove((User)
event.getObject());
}
}
5. Creating DataAccessObject (DAO) File
UserDAO.java File
Right click
com.dao package-ànew-àJavaClassàGive class name UserDAO-à click Finish.
UserDAO.java File CODE:
package
com.dao;
import
java.util.List;
import
java.util.ArrayList;
import
javax.persistence.EntityManager;
import
javax.persistence.EntityManagerFactory;
import
javax.persistence.NoResultException;
import
javax.persistence.Persistence;
import
javax.persistence.TypedQuery;
import
javax.persistence.EntityTransaction;
import
com.model.pojo.User;
import
javax.faces.application.FacesMessage;
import
org.primefaces.context.RequestContext;
/**
*
* @author Raichand
*/
public class
UserDAO {
private User user;
private User newuser;
private List<User> DaoAllUsers;
private List<User> DaoSearchUserList;
private EntityManagerFactory emf =
Persistence.createEntityManagerFactory("Users");
private EntityManager em =
emf.createEntityManager();
public List<User> getAllUsers(){
try{
em.getTransaction().begin();
DaoAllUsers =
em.createQuery("FROM User").getResultList();
em.getTransaction().commit();
int count =DaoAllUsers.size();
System.out.println("No of
Record From Dao: " + count);
}
catch(Exception e){
em.getTransaction().rollback();
e.printStackTrace();
}
return DaoAllUsers;
}
public Integer getNewUserId (){
Integer maxId = 0;
String jpql =
"select max(U.id) from User U";
try{
em.getTransaction().begin();
maxId =
(Integer)em.createQuery(jpql).getSingleResult();
System.out.println("Maximum User Id From Dao is-:"
+Integer.toString(maxId));
em.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
return maxId+1;
}
public List SearchByRecordNo(String RecordNo) {
try{
em.getTransaction().begin();
DaoSearchUserList =
em.createQuery("SELECT u FROM User u WHERE u.recordNo = :recordno",
User.class)
.setParameter("recordno", RecordNo)
.setMaxResults(10)
.getResultList();
em.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
finally {
return DaoSearchUserList;
}
}
public
List findWithName(String name) {
try{
em.getTransaction().begin();
DaoSearchUserList =
em.createQuery("SELECT u FROM User u Where u.name LIKE :userName")
.setParameter("userName", name)
.setMaxResults(10)
.getResultList();
em.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
finally {
return DaoSearchUserList;
}
}
public void
add(User user){
try{
// begin a transaction
em.getTransaction().begin();
String name = user.getName();
System.out.println("User
Name:" + name);
em.persist(user);
em.getTransaction().commit();
System.out.println("New User
saved, EmpNo: " + user.getName());
}catch (Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
}
public void delete(User user) {
try {
em.getTransaction().begin();
String UserName =
(user.getName());
em.remove(user);
em.getTransaction().commit();
System.out.println("User deleted, User: " +UserName);
} catch (Exception e) {
em.getTransaction().rollback();
e.printStackTrace();
}
}
public void update(User user){
try{
// begin a transaction
em.getTransaction().begin();
String name = user.getName();
System.out.println("User
Name:" + name);
em.merge(user);
em.getTransaction().commit();
System.out.println(" User
updated successfully, UserName: " + user.getName());
}catch (Exception e){
em.getTransaction().rollback();
e.printStackTrace();
}
}
public User getUserbyUserId(int id) {
try{
// begin a transaction
em.getTransaction().begin();
String name = user.getName();
System.out.println("User
Name:" + name);
user =
(User)em.find(User.class,id);
em.getTransaction().commit();
System.out.println("User
found, UserName: " +
user.getName());
}catch (RuntimeException e){
em.getTransaction().rollback();
e.printStackTrace();
}finally{
return user;
}
}
}
6. Creating Persistence.xml File
Rightclick
on project name in project exploreràNewàPersistenceUnità
Give Name
‘Users’-->NextàFinish
If
PersistenceUnit is not visible then NewàOthersàPersistenceàGive Name ‘Users’àNextàFinish
Choose Persistence Library
as Hibernate(JPA2.1) and Database Connection to ‘test’ database as shown in
below Figure.
Persistence.xml
<?xml version="1.0"
encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Users"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property
name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull"/>
<property
name="javax.persistence.jdbc.user" value="root"/>
<property
name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property
name="javax.persistence.jdbc.password" value=""/>
<property
name="hibernate.cache.provider_class"
value="org.hibernate.cache.NoCacheProvider"/>
<property
name="javax.persistence.schema-generation.database.action" value=""/>
</properties>
</persistence-unit>
</persistence>
7.
Creating index.xhtml File
index.xhtml code:
<?xml version='1.0'
encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>User CRUD</title>
</h:head>
<h:body>
<center><h1>User Management</h1></center>
<p:dialog
id="userDetail1" widgetVar="$userDetail1"
header="Add User"
hideEffect="explode" appendTo="@(body)"
resizable="false"
draggable="false"
closeOnEscape="true">
<h:form>
<p:panelGrid
columns="2">
<h:outputLabel
for="username" value="User Name: *" />
<p:inputText
id="username"
value="#{userBean.newuser.name}"
label="User
Name" placeholder="User
Name" />
<h:outputLabel
for="userage" value="User Age"/>
<p:inputText id="userage" label="User
Age" value="#{userBean.newuser.age}" placeholder="age"/>
<h:outputLabel
for="sex" value="Choose Sex"/>
<p:selectOneMenu
id="sex" label="Choose Sex"
value="#{userBean.newuser.sex}" effect="fold">
<f:selectItem
itemLabel="Select One" itemValue="" />
<f:selectItem
itemLabel="Male" itemValue="Male"/>
<f:selectItem
itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
<p:outputLabel
for="dob" value="User Date of Birth"/>
<p:calendar
id="dob" value="#{userBean.newuser.dob}"
label="DatePosted:"
required="true"
pattern="dd/MM/yyyy" effect="slideDown"
requiredMessage="Please Enter Date of Birth!"
navigator="true"
showButtonPanel="true" yearRange="c-60:c+60"
placeholder="Date of Birth" />
<p:outputLabel
for="remark" value="Remark"/>
<p:inputTextarea
id="remark" label="Remark" value="#{userBean.newuser.remark}"
placeholder="Remark"/>
<p:commandButton
value="add"
process="@form" id="AddButtonId"
ajax="true" icon="ui-icon-plus"
update=":form1:userTable"
actionListener="#{userBean.addUser()}"
oncomplete="PF('$userDetail1').hide()"/>
<p:commandButton
id="cancelAddButtonId"
value="Cancel"
onclick="handleComplete(xhr, status, args)"/>
</p:panelGrid>
</h:form>
</p:dialog>
<h:outputScript>
/* <![CDATA[ */
function handleComplete(xhr, status, args) {
if(args && args.validName) {
$userDetail1.hide();
}
}
/* ]]> */
</h:outputScript>
<p:dialog id="userDetail2"
widgetVar="$userDetail2"
header="Update
User"
hideEffect="explode" appendTo="@(body)"
resizable="false"
draggable="false"
closeOnEscape="true">
<h:form>
<h:inputHidden
value="#{userBean.user.id}"/>
<p:panelGrid
columns="2">
<h:outputLabel
for="recordno" value="Record No: *" />
<p:inputText
id="recordno"
value="#{userBean.user.recordNo}"
label="Record No"
placeholder="Record No" />
<h:outputLabel
for="username" value="User Name: *" />
<p:inputText
id="username"
value="#{userBean.user.name}"
label="User Name"
placeholder="User Name" />
<h:outputLabel
for="userage" value="User Age"/>
<p:inputText id="userage" label="User
Age" value="#{userBean.user.age}"
placeholder="age"/>
<h:outputLabel
for="sex" value="Choose Sex"/>
<p:selectOneMenu
id="sex" label="Choose Sex"
value="#{userBean.user.sex}" effect="fold">
<f:selectItem
itemLabel="Select One" itemValue="" />
<f:selectItem
itemLabel="Male" itemValue="Male"/>
<f:selectItem
itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
<p:outputLabel for="dob"
value="User Date of Birth"/>
<p:calendar
id="dob" value="#{userBean.user.dob}"
label="DatePosted:"
required="true"
pattern="dd/MM/yyyy" effect="slideDown"
requiredMessage="Please Enter Date of Birth!"
navigator="true"
showButtonPanel="true" yearRange="c-60:c+60"
placeholder="Date of Birth" />
<p:outputLabel
for="remark" value="Remark"/>
<p:inputTextarea
id="remark" label="Remark"
value="#{userBean.user.remark}" placeholder="Remark"/>
<p:commandButton
value="Update" ajax="true" icon="ui-icon-disk"
update=":form1:userTable"
actionListener="#{userBean.UpdateUser(userBean.user)}"
onclick="handleComplete(xhr, status, args)"/>
<p:commandButton
value="Cancel"
id="cancelButtonId"
onclick="handleComplete(xhr,
status, args)"/>
</p:panelGrid>
</h:form>
</p:dialog>
<h:outputScript
id="handleCompleteScript" target="body">
/* <![CDATA[ */
function handleComplete(xhr, status,
args) {
if(args && args.validName) {
$userDetail2.hide();
}
}
/* ]]> */
</h:outputScript>
<h:form id="form1">
<center><h3>Users</h3></center>
<p:toolbar>
<p:toolbarGroup align="left">
<p:commandButton icon="ui-icon-plusthick" type="button"
id="addUserBtn" value="Add User"
update=":userDetail1" ajax="true"
onclick="PF('$userDetail1').show()"/>
<p:commandButton value="Delete"
icon="ui-icon-trash"
type="button" onclick="PF('confirmDialog').show()"
/>
</p:toolbarGroup>
</p:toolbar>
<p:confirmDialog message="Are you sure you want to delete these records?Records once deleted can not be retrieved."
<p:confirmDialog message="Are you sure you want to delete these records?Records once deleted can not be retrieved."
header="Deleting" severity="alert"
widgetVar="confirmDialog">
<p:commandButton
value="Yes Sure" update=":form1:userTable" action="#{userBean.deleteUser()}"
oncomplete="PF('confirmDialog').hide()"/>
<p:commandButton value="Not Yet"
onclick="PF('confirmDialog').hide();" type="button" />
</p:confirmDialog>
<p:spacer height="5px"></p:spacer>
<p:remoteCommand
name="updateTable" update="userTable" />
<p:dataTable value="#{userBean.users}"
var="user" editable="true" rowKey="#{user.id}"
selection="#{userBean.selectedUsers}" paginator="true" rows="5"
id="userTable">
<p:column selectionMode="multiple"
headerText="Select" style="width:6%" />
<p:column
headerText="Record No" style="text-align: left;">
<h:outputText
value="#{user.recordNo}"/>
</p:column>
<p:column
filterBy="#{user.name}"
filterOptions=""
filterMatchMode="startsWith" headerText="Name">
<h:outputText
value="#{user.name}"/>
</p:column>
<p:column
sortBy="#{user.age}" headerText="Age" >
<h:outputText
value="#{user.age}"/>
</p:column>
<p:column
headerText="Sex">
<h:outputText
value="#{user.sex}"/>
</p:column>
<p:column
headerText="Date of Birth" >
<h:outputText
value="#{user.dob}">
<f:convertDateTime
type="date" pattern="dd-MMM-yyyy"/>
</h:outputText>
</p:column>
<p:column
headerText="Remark" >
<h:outputText
value="#{user.remark}"/>
</p:column>
<p:column headerText="Edit"
style="text-align: center">
<p:commandButton
icon="ui-icon-pencil" id="editUserBtn"
value="Edit" ajax="true"
actionListener="#{userBean.changeUser(user)}"
update=":userDetail2"
oncomplete="PF('$userDetail2').show()"/>
</p:column>
<p:rowExpansion>
<h:outputText
value="#{user.remark}" styleClass="rowExpansion"/>
</p:rowExpansion>
</p:dataTable>
</h:form>
</h:body>
</html>
8. Search.xhtml code:
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h2><center>Search User
For Edit And Delete</center></h2>
</h:head>
<h:body>
<h:form>
,<p:commandButton action="add?faces-redirect=true"
value="Back" icon="ui-icon-arrowthick-1-w" />
</h:form>
<h:form id="form">
<p:growl id="messages"
showDetail="true"/>
<h:panelGrid columns="2"
style="margin-bottom:10px" cellpadding="5">
<p:outputLabel
value="Please Select Record Number:"/>
<p:selectOneMenu
value="#{userBean.user.recordNo}"
editable="true" label="Please Select Record Number:"
filter="true" id="ulist2">
<f:selectItem
itemLabel="Select One" itemValue="" />
<f:selectItems
value="#{userBean.users}" var="user"
itemLabel="#{user.recordNo}"
itemValue="#{user}"/>
</p:selectOneMenu>
</h:panelGrid>
<p:commandButton
value="Search" update=":form:userTable"
type="Submit" icon="ui-icon-search"
action="#{userBean.searchbyRecordno()}"/>
<br/>
<p:spacer> </p:spacer>
<p:dataTable
var="user" id="userTable" editable="true"
value="#{userBean.searchByRecordNoList}">
<f:facet
name="header">
Row Editing
</f:facet>
<p:ajax event="rowEdit"
listener="#{userBean.onRowEdit}" update=":form:messages"
/>
<p:ajax
event="rowEditCancel" listener="#{userBean.onCancel}"
update=":form:messages" />
<p:column headerText="RecordNo">
<p:cellEditor>
<f:facet
name="output"><h:outputText value="#{user.recordNo}"
/></f:facet>
<f:facet
name="input"><p:inputText id="modelInput"
value="#{user.recordNo}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column
headerText=" Name" >
<p:cellEditor>
<f:facet
name="output"><h:outputText value="#{user.name}"
/></f:facet>
<f:facet
name="input"><p:inputText
value="#{user.name}"
style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column
headerText="Age">
<p:cellEditor>
<f:facet
name="output"><h:outputText value="#{user.age}"
/></f:facet>
<f:facet
name="input"><p:inputText
value="#{user.age}"
style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Date of
Birth">
<p:cellEditor>
<f:facet
name="output">
<h:outputText value="#{user.dob}">
<f:convertDateTime
type="date" pattern="dd-MMM-yyyy"/>
</h:outputText>
</f:facet>
<f:facet
name="input"><p:calendar id="dob"
value="#{user.dob}"
style="width:100%" label="DatePosted:"
required="true" pattern="dd/MM/yyyy" effect="slideDown"
requiredMessage="Please Enter Date of Birth!"
navigator="true" showButtonPanel="true"
yearRange="c-60:c+60" /></f:facet>
</p:cellEditor>
</p:column>
<p:column
headerText="Sex" width="100" >
<p:cellEditor >
<f:facet
name="output"><h:outputText value="#{user.sex}"
/></f:facet>
<f:facet
name="input">
<p:selectOneMenu
value="#{user.sex}"
id="ulist11">
<f:selectItem
itemLabel="Select One" itemValue="" />
<f:selectItem
itemLabel="Male" itemValue="Male"/>
<f:selectItem
itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column
headerText="Remark">
<p:cellEditor >
<f:facet name="output"><h:outputText value="#{user.remark}"
/></f:facet>
<f:facet
name="input"><p:inputText
value="#{user.remark}"
style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column
headerText="Edit"
style="width:100px">
<p:rowEditor />
</p:column>
<p:column
headerText="Delete" >
<p:commandButton
value="Delete" icon="ui-icon-trash"
update="form:userTable" type="button"
onclick="PF('confirmDialog').show()" />
<p:confirmDialog message="Are you
sure you want to delete this record?Record once deleted can not be retrieved."
header="Deleting"
severity="alert" widgetVar="confirmDialog">
<p:commandButton value="Yes Sure"
action="#{userBean.deleteUser(user)}"
oncomplete="PF('confirmDialog').hide()"/>
<p:commandButton value="Not Yet"
onclick="PF('confirmDialog').hide();" type="button" />
</p:confirmDialog>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
9.add.xhtml
Under the
webpages folder welcome.xhtml file is automatically generated.
Right click
welcome.xhtml file-àRefactor-àrenameàGivename addàclick finish
It is a single page CRUD
Project. It is an independent file. It can be ran by selecting it in Project
Explorerà File(From Menu Bar)àRun File
add.xhtml Code:-
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h2><center>All User
Information</center></h2>
</h:head>
<h:body>
<h:form>
<p:commandButton
action="Search?faces-redirect=true"
icon="ui-icon-search"
value="Search" />
</h:form>
<p:spacer> </p:spacer>
<h:form id="form1">
<p:dataTable id="dataTable" var="user"
paginator="true" rows="5"
value="#{userBean.users}">
<p:column
headerText="RecordNo">
<h:outputText
value="#{user.recordNo}"/>
</p:column>
<p:column
headerText="Name" >
<h:outputText
value="#{user.name}"/>
</p:column>
<p:column
sortBy="#{user.age}" headerText="Age" >
<h:outputText
value="#{user.age}"/>
</p:column>
<p:column
headerText="Sex">
<h:outputText
value="#{user.sex}"/>
</p:column>
<p:column
headerText="Date of Birth" >
<h:outputText
value="#{user.dob}">
<f:convertDateTime
type="date" pattern="dd-MMM-yyyy"/>
</h:outputText>
</p:column>
<p:column
headerText="Remark" >
<h:outputText
value="#{user.remark}"/>
</p:column>
</p:dataTable>
</h:form>
<h:panelGroup
>
<h3>Add User
Information</h3>
<h:form>
<p>User Name:
<p:inputText value="#{userBean.newuser.name}" /></p>
<p>User Age:
<p:inputText value="#{userBean.newuser.age}" />Enter Number
Only</p>
<h:panelGrid columns="2"
style="margin-bottom:10px" cellpadding="5">
<p>Choose Sex:</p>
<p:selectOneMenu
label="Sex:" value="#{userBean.newuser.sex}"
id="ulist2">
<f:selectItem
itemLabel="Select One" itemValue="" />
<f:selectItem
itemLabel="Male" itemValue="Male"/>
<f:selectItem
itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
</h:panelGrid>
<p>User Date of Birth: <p:calendar
id="dop" value="#{userBean.newuser.dob}"
label="DatePosted:"
required="true"
pattern="dd/MMM/yyyy" effect="slideDown"
requiredMessage="Please Enter Date of Posting!"
navigator="true"
showButtonPanel="true" yearRange="c-60:c+60" />
</p> <p>Remark:
<p:inputTextarea value="#{userBean.newuser.remark}"
/></p>
<p><p:commandButton
icon="ui-icon-plusthick" update=":form1:dataTable" type="submit" value="add"
action="#{userBean.addUser()}" /></p>
</h:form>
</h:panelGroup>
</h:body>
</html>
10. web.xml (Automatically
generated to be modified if required)
CODE:
<?xml
version="1.0" encoding="UTF-8"?>
<web-app
version="3.1" 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-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Select the project in project window and run the project
Index.xhtml
page
add.xhtml page
Select add.xhtml page in Project Explorerà File From MenuàRun File
Search.xhtml
Page
Search.xhtml
Page before deleting Record
To integrate Login and Maven please follow the article at below mentioned
URL
http://mrbool.com/java-web-creating-a-login-screen-with-jpa-jsf-primefaces-and-mysql/34397