In this article you will learn how to create a JSP CRUD application with Pagination, Sorting and export option using NetBeans IDE and MySQL 5. This simple application is a Create, Read, Update and Delete application operating on an ‘emp’ table in ‘test’ database in MySQL Database Server.
Software Used
- JDK 8u25
- NetBeans IDE 8.02
- MySQL 5.*(or XAMPP)
- MySQL Connector 5.*
- Hibernate 4.3.** (Bundled with NetBeans)
- Display Tag Library(For pagination ,sorting and export)
Steps:
- Install JDK8 or JDK7 if not installed.
- Install NetBeans and associated ApacheTomcat Server.
- Install MySQL Database server or XAMPP (for easy MySQL management).
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 ‘Emp’ Table using below script in MySQL TEST Database,
- CREATE TABLE `Emp` (
-
- `empno` int(10) unsigned NOT NULL auto_increment,
-
- `ename` varchar(45) NOT NULL,
-
- `sal` int(15) NOT NULL,
-
- `dob` date NOT NULL,
-
- PRIMARY KEY (`empno`)
-
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Project Structure:
Creating Project JSPHibernate4EmployeeCRUD
File, New Project, Categories, Choose JavaWeb, then choose WebApplication, Click Next and Give Project Name JSPHibernate4EmployeeCRUD, then click Next and choose Framework Hibernate, then click Finish
Download and add the following libraries(JAR) one by one by right clicking the libraries folder in project window then-Add JAR/Folder.
- MySQL-Connector.java-5.1.35-bin.jar
- displaytag-1.2.jar
- displaytag-export-poi-1.2.jar
- displaytag-portlet-1.2.jar
- commons-beanutilis-1.8.0.jar
- commons-collections-3.1.jar
- commons-lang-2.4.jar
Creating Packages and Classes
Right click SourcePackages folder and create three packages,
- com.dao- This would contain DAO (Data Access Object) class empDao.java.
- com.model.pojo- This would contain entity class Emp.java.
- com.util- This will contain HibernateUtil.java class
Following Files would be created using Netbeans,
- hibernate.cfg.xml File-Automatically generated.
- Reverse Engineering File-hibernate.reveng.xml.
- Entity(POJO) File-Emp.java(POJO stands for Plain Old Java Objects).
- DataAccessObject(DAO) File-àempDao.java.
- HibernateUtil.java File.
- web.xml (Automatically generated)
- index.jsp (Add employee record and displays all employee records)
- deleteEmp.jsp (Displays employee record before deleting)
- updateEmp.jsp (Displays employee record for updating)
1.hibernate.cfg.xml
It is generated automatically when connected to test database of MySQL.
By Netbeans Services Tab àDatabasesàGet connected to test database.
COPY AND PASTE CODE OF THE FILE GIVEN BELOW WHOSE CODE IS NOT GENERATED
2. Creating Reverse Engineering File-àhibernate.reveng.xml
Right Click default package in the Source Package, new, choose Hibernate Reverse Engineering Wizard, click next, then choose emp table, Add, then click finish.
Code
- <?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="emp" />
-
- </hibernate-reverse-engineering>
3. Creating Annotation Based Entity (pojo) Class File Emp.java
Emp.java Class File
Important:To create this file MySQL database test must be connected through NetBeans.
Right click com.model package--new-Hibernate Mappling Files and pojos from database, then click Finish
Connect to database, then the following window opens . Check EJB3.0 annotation box, uncheck Hibernate XML Mapping check box. Choose package com.model.pojo.
Emp.java Class File
4. Creating DataAccessObject (DAO) File
empDao.java File
Right click com.dao package, new, JavaClass, Give class name empDao, then click Finish.
empDao.java File CODE:
5.HibernateUtil.java File
Right click com.util folder, new, javaclass, Class name, then give name HibernateUtil, then click Finish.
HibernateUtil.java CODE:
- import org.hibernate.SessionFactory;
-
- import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
-
- import org.hibernate.cfg.Configuration;
-
- import org.hibernate.service.ServiceRegistry;
-
- public class HibernateUtil
-
- {
-
- private static SessionFactory sessionFactory = buildSessionFactory();
-
- private static SessionFactory buildSessionFactory()
-
- {
-
- try
-
- {
-
- if (sessionFactory == null) {
-
-
-
- Configuration configuration = new Configuration().configure();
-
- ServiceRegistry serviceRegistry
-
- = new StandardServiceRegistryBuilder()
-
- .applySettings(configuration.getProperties()).build();
-
-
-
- sessionFactory = configuration.buildSessionFactory(serviceRegistry);
-
- }
-
- return sessionFactory;
-
- } catch (Throwable ex)
-
- {
-
- System.err.println("Initial SessionFactory creation failed." + ex);
-
- throw new ExceptionInInitializerError(ex);
-
- }
-
- }
-
- public static SessionFactory getSessionFactory()
-
- {
-
- return sessionFactory;
-
- }
-
- public static void closeSession()
-
- {
- getSessionFactory().close();
-
- }
-
- }
6. web.xml (Automatically generated)
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:
-
- <session-config>
-
- <session-timeout>
-
- 30
-
- </session-timeout>
-
- </session-config>
-
- <welcome-file-list>
-
- <welcome-file>index.jsp</welcome-file>
-
- </welcome-file-list>
-
- </web-app>
6. Creating index.jsp File
Right click WebPages folderàNewàJspàGive name index.jsp then click Finish.
Similarly create deleteEmp.jsp and updateEmp.jsp files.
Index.jsp
7.index.jsp code:
- <%@page contentType="text/html" pageEncoding="UTF-8"%>
-
- <%@page import="java.util.ArrayList"%>
-
- <%@page import="com.model.pojo.Emp"%>
-
- <%@page import ="java.util.Date"%>
-
- <%@page import = "java.text.SimpleDateFormat"%>
-
- <%@page import="com.dao.empDao"%>
-
- <%@page import="java.util.List"%>
-
- <jsp:useBean id="emp" class="com.model.pojo.Emp">
-
- </jsp:useBean>
-
- <jsp:setProperty property="*" name="emp" />
-
- <%@ taglib prefix="display" uri="http://displaytag.sf.net"%>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
- <html>
-
- <head>
-
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
-
- <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
-
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
-
- <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
-
- <script type="text/javascript">
- $(document).ready(function() {
-
- $("#datepicker").datepicker({
-
- showButtonPanel: true,
-
- showOn: "button",
-
- buttonText: "Select date",
-
- dateFormat: 'yy-mm-dd',
-
- changeMonth: true,
-
- changeYear: true,
-
- yearRange: "-90:"
-
-
- });
-
- });
- </script>
-
- <title>Display tag Pagination and Sorting Example in JSP</title>
-
- </head>
-
-
- <%
-
-
- empDao dao = new empDao();
-
- List empList = dao.getAllEmployee();
-
- request.setAttribute("empList", empList);
-
- int count = dao.getAllEmployee().size();
-
- System.out.println("No of Record: " + count);
-
- String name=request.getParameter("ename");
-
- String sd = request.getParameter("sd");
-
- System.out.println(sd);
-
- System.out.println(name);
-
- if(name != null)
-
- {
-
-
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-
- Date dob = sdf.parse(sd);
-
- emp.setDob(dob);
-
- dao.add(emp);
-
- empList = dao.getAllEmployee();
-
- request.setAttribute("empList", empList);
-
- }
-
- %>
-
-
- <body>
-
- <form name="f1" action="index.jsp" method="post">
-
- <table width="471" border="1">
-
-
- <tr>
-
- <th>Employee Name </th>
-
- <td><input name="ename" type="text"></td>
-
- </tr>
-
- <tr>
-
- <th>Salary </th>
-
- <td><input name="sal" type="text"></td>
-
- </tr>
-
- <tr>
-
- <th>Date of Birth</th>
-
- <td><input name="sd" type="text" id="datepicker"></td>
-
- </tr>
-
- <tr>
-
- <th colspan="2"><input type="submit" onclick=u pdate(EmpTable) name="s1" value="Add">
-
- </th>
-
- </tr>
-
- </table>
-
- </form>
-
-
- <display:table id="EmpTable" name="empList" class="dataTable" export="true" pagesize="10" cellpadding="5px;" uid="row" cellspacing="5px;" style="margin-left:50px;margin-top:20px;" requestURI="">
-
- <display:column property="ename" title="Name" sortable="true" />
-
- <display:column property="sal" title="Salary" />
-
- <display:column property="dob" format="{0,date,dd-MMM-yyyy}" title="BirthDate" />
-
- <display:column property="empno" format="Edit" href="updateEmp.jsp" paramId="empno" paramProperty="empno" title="Action" />
-
- <display:column property="empno" format="Delete" href="deleteEmp.jsp" paramId="empno" paramProperty="empno" title="Action" />
-
- <display:setProperty name="export.excel.filename" value="EmployeeDetails.xls" />
-
- <display:setProperty name="export.pdf.filename" value="EmployeeDetails.pdf" />
-
- <display:setProperty name="export.csv.filename" value="EmployeeDetails.csv" />
-
- </display:table>
-
- </body>
-
- </html>
8.DeleteEmp.jsp file code:
9.UpdateEmp.jsp file code:
index.jsp
Update.jsp
Modify the displayed record and click update.
Delete.jsp
Click Delete button to delete record after viewing it.