Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java Struts2 and Hibernate4 CRUD With MySQL With Pagination, Sorting and Export Option Using Netbeans

Uploaded by

basman mail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Struts2 and Hibernate4 CRUD With MySQL With Pagination, Sorting and Export Option Using Netbeans

Uploaded by

basman mail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option

And Export Option Using Netbeans

Java Struts2 And Hibernate4 CRUD With MySQL


With Pagination, Sorting And Export Option Using
Netbeans
Raichand Ray Sep 26, 2019 52k 2 1

Struts2HibernateCRUD.rar

Introduction
This simple Application helps to Create, Read, Update and Delete (CRUD) Application, operating
on the ‘contacts’ table in the ‘test’ database in MySQL Database Server. It is a hibernate-
annotation based Application. There is an option to delete more than one record in a Webpage at
once.

Softwares used are-

1. JDK8u25
2. Netbeans 8.02
3. MySQL 5.*(or XAMPP)
4. MySQL Connector 5.*
5. Hibernate 4.3.** (Bundled with Netbeans)
6. Display Tag Library(For pagination, sorting and export)

Steps are-

1. Install JDK8 or Jdk7, if not installed.


2. Install Netbeans and associated ApacheTomcat Server.
3. Install MySQL Database server or XAMPP(for easy MySQL management).create ‘test’
database.

After installing Netbeans, click the Services tab on the left. Expand the Database node. Expand
the Drivers node. Right-click MySQL(Connector/Jdriver) and then connect. Put the test as the
database, as shown below. Put the password, if you have given the password at the time of
installation of MySQL database Server. For XAMPP, no password was given, followed by the test
connection. If successful, click Finish button.

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 1/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

Create ‘contacts’ table, using the script, given below, in MySQL ‘test’ Database-

01. CREATE TABLE IF NOT EXISTS `contacts` (


02. `id` int(11) NOT NULL,
03. `firstname` varchar(30) DEFAULT NULL,
04. `lastname` varchar(30) DEFAULT NULL,
05. `birthdate` date DEFAULT NULL,
06. `cell_no` varchar(15) DEFAULT NULL,
07. `country` varchar(20) DEFAULT NULL,
08. `created` datetime NOT NULL,
09. `email_id` varchar(30) DEFAULT NULL,
10. `sex` varchar(10) DEFAULT NULL,
11. `website` varchar(30) DEFAULT NULL
12. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
13. ALTER TABLE `contacts` ADD PRIMARY KEY (`id`);
14. ALTER TABLE `contacts` ADD UNIQUE(`email_id`);
15. ALTER TABLE `contacts` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO

Insert the records by executing the queries, given below-

01. INSERT INTO `contacts` (`id`, `birthdate`, `cell_no`, `country`, `creat


02. (1, '1980-05-06', '9834145667', 'USA', '2016-05-
26 19:07:17', 'richard@yahoo.com', 'Richard', 'Johnson', 'Male', 'www.r
03. (2, '1982-05-05', '9839753298', 'USA', '2016-05-
26 19:08:26', 'martha@yahoo.com', 'Martha', 'Stewart', 'Female', 'www.m
04. (3, '1985-05-16', '9839753298', 'USA', '2016-05-
26 19:09:29', 'clive@gmail.com', 'Clive', 'Sweetman', 'Male', 'www.cliv

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 2/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

Project Structure

Creating Project Struts2HibernateCRUD

File-New Project-Categories-Choose JavaWeb--Choose WebApplication-Click Next-Give Project


Name Strutr2HibernateCRUD-> Click Next-Click Next-Choose Framework Hibernate --Click
Finish.

Download and add the following libraries(JAR) one by one by right-clicking the libraries folder in
project Window, followed by Add JAR/Folder. Most of the files are provided for the download.

1. MySQL-Connector.java-5.1.35-bin.jar
2. Struts2-jquery-plugin-2.3.1.jar
3. displaytag-1.2.jar
4. displaytag-export-poi-1.2.jar
5. displaytag-portlet-1.2.jar
6. commons-beanutilis-1.8.0.jar
7. commons-collections-3.1.jar
8. commons-lang3-3.4.jar
9. commons-digester-2.0.jar
10. commons-lang-2.4.jar
11. commons-logging-1.1.3.jar
12. commons-logging-api-1.1.jar
13. xwork-core-2.3.24.1.jar
14. struts2-core-2.3.24.1.ja
15. struts2-convention-plugin-2.3.24.1.jar

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 3/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

16. ognl-3.0.6.jar
17. freemaker-2.3.22.jar
18. commons-lang3-3.2.jar
19. commons-io-2.2.jar
20. commons-fileupload-1.3.1.jar
21. asm-tree-3.3.jar
22. asm-commons-3.3.jar
23. asm-3.3.jar

Creating Packages and Classes

Rightclick SourcePackages folder and create four packages, which are-

1. com.dao-This would contain DAO(Data Access Object) class ContactDao.java.


2. com.pojos.model-This would contain an entity class Contacts.java.
3. com.struts.actions-This would contain struts action class ContactAction.java.
4. com.util-This would contain HibernateUtil.java class.

Following files would be created, using Netbeans-

1. hibernate.cfg.xml File-Automatically generated.


2. Reverse Engineering File-hibernate.reveng.xml
3. Entity(POJO) File-Contacts.java(POJO stands for Plain Old Java Objects)
4. DataAccessObject(DAO) File-ContactDao.java
5. HibernateUtil.java File
6. web.xml(Automatically generated)
7. Struts2 Action File-ContactAction.java
8. Struts2 XMLFile-struts.xml
9. index.jsp(opens CRUD.jsp page by executing execute method in action class
ContactAction.java).
10. CRUD.jsp(Add contact record and displays all contacts records).
11. delete.jsp(Displays contact record before deleting).
12. update.jsp(Displays contact record for updating).

1. hibernate.cfg.xml

It contains the database connection credentials

It is generated automatically when connected to test the database of MySQL through


Netbeans by Netbeans Services Tab -Databases-Get connected to test the database.

Here, XAMPP is used without the password, so there is no password. Otherwise, the
password for connecting to the database is required.

01. <?xml version="1.0" encoding="UTF-8"?>


02. <!DOCTYPE hibernate-
configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0/

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 4/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

configuration-3.0.dtd">
03. <hibernate-configuration>
04. <session-factory>
05. <property name="hibernate.dialect">org.hibernate.dialect.MySQLD
06. <property name="hibernate.connection.driver_class">com.mysql.jd
07. <property name="hibernate.connection.url">jdbc:mysql://localhos
zeroDateTimeBehavior=convertToNull</property>
08. <property name="hibernate.connection.username">root</property>
09. <property name="connection.password"></property>
10. <property name="connection.pool_size">10</property>
11. <!-- Enable Hibernate's automatic session context management -
->
12. <property name="current_session_context_class">thread</property
13. <property name="cache.provider_class">org.hibernate.cache.NoCac
14. <!-- Display all generated SQL to stdout -->
15. <property name="show_sql">true</property>
16. <property name="hbm2ddl.auto">update</property>
17. <!-- Mapping with model class containing annotations -->
18. <mapping class="com.pojos.model.Contacts"/>
19. </session-factory>
20. </hibernate-configuration>

Copy and paste the code of the file given below, whose code is not generated.

2. Create Reverse Engineering File-hibernate.reveng.xml.

Right click on default package in the Source Package-new-choose Hibernate Reverse


Engineering Wizard-click next-choose emp table-Add -click finish.

CODE

01. <?xml version="1.0" encoding="UTF-8"?>

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 5/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

02. <!DOCTYPE hibernate-reverse-


engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD
reverse-engineering-3.0.dtd">
03. <hibernate-reverse-engineering>
04. <schema-selection match-catalog="test"/>
05. <table-filter match-name="contacts"/>
06. </hibernate-reverse-engineering>

3. Create Annotation Based Entity (pojo) Class File Contacts.java.

Contacts.java Class File

Important: To create this file, MySQL database tests most to be connected through
Netbeans. Right-click com.model package--new-Hibernate Mapping Files and POJOs from
the database-click Finish.

Connect to the database. The Window, given below, opens. Check EJB3.0 annotation box.
Uncheck Hibernate XML Mapping checkbox. Choose package com.pojos.model.

Contacts.java Class File is given.

01. package com.pojos.model;


02. // Generated Feb 15, 2016 8:57:30 AM by Hibernate Tools 4.3.1
03. import java.util.Date;
04. import javax.persistence.Column;
05. import javax.persistence.Entity;
06. import javax.persistence.GeneratedValue;
07. import static javax.persistence.GenerationType.IDENTITY;
08. import javax.persistence.Id;
09. import javax.persistence.Table;
10. import javax.persistence.Temporal;
11. import javax.persistence.TemporalType;
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 6/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

12.
13. /**
14. * Contacts generated by hbm2java
15. */
16. @Entity
17. @Table(name="contacts"
18. ,catalog="test"
19. )
20. public class Contacts implements java.io.Serializable {
21. private Integer id;
22. private String firstname;
23. private String lastname;
24. private String sex;
25. private String cellno;
26. private String emailId;
27. private String country;
28. private String website;
29. private Date birthdate;
30. private Date created;
31.
32. public Contacts() {
33. }
34.
35. public Contacts(Date created) {
36. this.created = created;
37. }
38. public Contacts(String firstname, String lastname, String sex,
39. this.firstname = firstname;
40. this.lastname = lastname;
41. this.sex = sex;
42. this.cellno = cellno;
43. this.emailId = emailId;
44. this.country = country;
45. this.website = website;
46. this.birthdate = birthdate;
47. this.created = created;
48. }
49.
50. @Id @GeneratedValue(strategy=IDENTITY)
51. @Column(name="id", unique=true, nullable=false)
52. public Integer getId() {
53. return this.id;
54. }
55.
56. public void setId(Integer id) {
57. this.id = id;
58. }
59.
60.
61. @Column(name="firstname", length=30)
62. public String getFirstname() {
63. return this.firstname;
64. }
65. public void setFirstname(String firstname) {
66. this.firstname = firstname;
67. }
68. @Column(name="lastname", length=30)
69. public String getLastname() {
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 7/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

70. return this.lastname;


71. }
72. public void setLastname(String lastname) {
73. this.lastname = lastname;
74. }
75. @Column(name="sex", length=10)
76. public String getSex() {
77. return this.sex;
78. }
79. public void setSex(String sex) {
80. this.sex = sex;
81. }
82. @Column(name="cell_no", length=15)
83. public String getCellno() {
84. return cellno;
85. }
86. public void setCellno(String cellno) {
87. this.cellno = cellno;
88. }
89. @Column(name="email_id", length=30)
90. public String getEmailId() {
91. return this.emailId;
92. }
93. public void setEmailId(String emailId) {
94. this.emailId = emailId;
95. }
96. @Column(name="country", length=30)
97. public String getCountry() {
98. return this.country;
99. }
100. public void setCountry(String country) {
101. this.country = country;
102. }
103. @Column(name="website", length=30)
104. public String getWebsite() {
105. return this.website;
106. }
107. public void setWebsite(String website) {
108. this.website = website;
109. }
110. @Temporal(TemporalType.DATE)
111. @Column(name="birthdate", length=10)
112. public Date getBirthdate() {
113. return this.birthdate;
114. }
115. public void setBirthdate(Date birthdate) {
116. this.birthdate = birthdate;
117. }
118. @Temporal(TemporalType.TIMESTAMP)
119. @Column(name="created", nullable=false, length=19)
120. public Date getCreated() {
121. return this.created;
122. }
123. public void setCreated(Date created) {
124. this.created = created;
125. }
126. //This method writes the values of contact object with System.o
127. @Override
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 8/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

128. public String toString() {


129. return "Contact"
130. + "\n\t Id: " + this.id
131. + "\n\t FirstName: " + this.firstname
132. + "\n\t LastName: " + this.lastname
133. + "\n\t Sex: " + this.sex
134. + "\n\t CellNo: " + this.cellno
135. + "\n\t Country: " + this.country
136. + "\n\t WebSite: " + this.website
137. + "\n\t EmailId: " + this.emailId
138. + "\n\t BirthDate: " + this.birthdate
139. + "\n\t Date Created: " + this.created;
140. }
141. }

4. Creating DataAccessObject (DAO) File

Right-click on com. dao package-new-JavaClass. Give the class name as ContactDao and
click Finish.

01. package com.dao;


02. import java.util.List;
03. import java.util.ArrayList;
04. import com.pojos.model.Contacts;
05. import com.util.HibernateUtil;
06. import org.hibernate.HibernateException;
07. import org.hibernate.Session;
08. import org.hibernate.Transaction;
09.
10. /**
11. *
12. * @author Raichand
13. */
14. public class ContactDao extends HibernateUtil{
15.
16. public void add(Contacts newcontact) {
17. Session session = HibernateUtil.getSessionFactory().openSes
18. String fname = newcontact.getFirstname();
19. System.out.println("FirstName=" + fname);
20. //int newid = this.getNewContactId();
21. // newcontact.setId(newid);
22. //int contactid = newcontact.getId();
23. //System.out.println("DaoContact id ;-" + contactid);
24. System.out.println("From Dao:-" + newcontact);
25. session.beginTransaction();
26. //session.merge(newcontact);
27. session.save(newcontact);
28. session.getTransaction().commit();
29. session.flush();
30. session.close();
31.
32. }
33.
34. public void deleteContact(int id) {
35. Session session = HibernateUtil.getSessionFactory().openSes
36. session.beginTransaction();
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 9/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

37. try {
38. Contacts contact = (Contacts) session.load(Contacts.class,i
39. if(null != contact) {
40. session.delete(contact);
41. }
42. } catch (HibernateException e) {
43. e.printStackTrace();
44. session.getTransaction().rollback();
45. }
46. session.getTransaction().commit();
47.
48. session.flush();
49. session.close();
50. }
51.
52. public void update(Contacts contact) {
53. Session session = HibernateUtil.getSessionFactory().openSes
54. session.beginTransaction();
55. //Contacts contact = (Contacts) session.load(Contacts.class,
56. try {
57. if(contact != null) {
58. session.saveOrUpdate(contact);
59. }
60.
61. } catch (HibernateException e) {
62. e.printStackTrace();
63. session.getTransaction().rollback();
64. }
65. session.getTransaction().commit();
66. session.flush();
67. session.close();
68. }
69.
70. public int getNewContactId() {
71. Session session = HibernateUtil.getSessionFactory().ge
72. Transaction trans = session.beginTransaction();
73. String query = "SELECT max(c.id) FROM Contacts c";
74. List list = session.createQuery(query).list();
75. int maxId = ((Integer) list.get(0));
76.
77. trans.commit();
78. session.close();
79. return (maxId+1);
80. }
81.
82.
83. public List<Contacts> list(){
84. Session session = HibernateUtil.getSessionFactory().openSessio
85. List<Contacts> DaoAllContacts = null;
86. session.beginTransaction();
87. try {
88.
89. DaoAllContacts = session.createCriteria(Contacts.cla
90. //DaoAllContacts = (List<Contacts>)session.createQue
91. int count =DaoAllContacts.size();
92. System.out.println("No of Record From Dao: " + count)
93. } catch (HibernateException e) {
94. e.printStackTrace();
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 10/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

95. session.getTransaction().rollback();
96. }
97. session.getTransaction().commit();
98. session.flush();
99. session.close();
100. return DaoAllContacts;
101.
102. }
103.
104. }

5. HibernateUtil.java File

Right-click on com.util folder-new-javaclass-Class name. Give the name as HibernateUtil


and click Finish.

01. package com.util;


02. import org.hibernate.SessionFactory;
03. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
04. import org.hibernate.cfg.Configuration;
05. import org.hibernate.service.ServiceRegistry;
06.
07. /**
08. *
09. * @author Raichand
10. */
11.
12. public class HibernateUtil {
13. private static SessionFactory sessionFactory;
14. private static ServiceRegistry serviceRegistry;
15. private static SessionFactory createSessionFactory() {
16. try {
17. // Create the SessionFactory from hibernate.cfg.xml
18. Configuration configuration = new Configuration();
19. configuration.configure("hibernate.cfg.xml");
20. System.out.println("Hibernate Annotation Configuration
21. serviceRegistry = new StandardServiceRegistryBuilder().
22. System.out.println("Hibernate Annotation serviceRegistr
23. sessionFactory = configuration.buildSessionFactory(serv
24. return sessionFactory;
25. }
26. catch (Throwable ex) {
27. // Make sure you log the exception, as it might be swal
28. System.err.println("Initial SessionFactory creation fai
29. throw new ExceptionInInitializerError(ex);
30. }
31. }
32. public static SessionFactory getSessionFactory() {
33. if(sessionFactory == null) sessionFactory = createSessionFa
34. return sessionFactory;
35. }
36. }

6. web.xml (Automatically generated, followed by copying and pasting the code, given below)-

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 11/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

01. <?xml version="1.0" encoding="UTF-8"?>


02. <web-
app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:
instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee ht
app_3_1.xsd">
03. <filter>
04. <filter-name>struts2</filter-name>
05. <filter-
class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecu
class>
06. </filter>
07. <filter-mapping>
08. <filter-name>struts2</filter-name>
09. <url-pattern>/*</url-pattern>
10. </filter-mapping>
11. <welcome-file-list>
12. <welcome-file>index.jsp</welcome-file>
13. </welcome-file-list>
14. </web-app>

7. Creating Struts2 action File ContactAction.Java File

Right-click com.struts.actions folder-New-StrutsAction. Give the name ContactAction.java


and click Finish.

01. package com.struts.actions;


02. import java.util.Date;
03. import java.util.ArrayList;
04. import java.util.List;
05. import com.opensymphony.xwork2.ActionSupport;
06. import com.dao.ContactDao;
07. import com.pojos.model.Contacts;
08. import java.text.ParseException;
09. import java.text.SimpleDateFormat;
10. import java.util.Locale;
11.
12. /**
13. *
14. * @author Raichand
15. */
16. public class ContactAction extends ActionSupport {
17. private static final long serialVersionUID = 91498262607583900
18. private Contacts contact= new Contacts();
19. private List<Contacts> ContactList= new ArrayList<Contacts>
();
20.
21. private int id;
22. private String birthdate;
23. private Date date = new Date();
24. private ContactDao dao;
25. private Integer[] Checkbox;//stores id of selected(checked) rec
26.
27. public ContactAction() {
28. dao= new ContactDao();
29. }
30.
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 12/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

31.
32. @Override
33. public String execute() {
34. this.ContactList = dao.list();
35.
36. int count = ContactList.size();
37. System.out.println("contactList Size"+ count);
38. //System.out.println("execute called");
39. return SUCCESS;
40. }
41. public String add() throws ParseException {
42. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-
dd",Locale.ENGLISH);
43. Date dob = sdf.parse(getBirthdate());
44. contact.setCreated(date);
45. contact.setBirthdate(dob);
46. System.out.println(birthdate);
47.
48. System.out.println(contact);
49. try {
50.
51. dao.add(contact);
52.
53. } catch (Exception e) {
54. e.printStackTrace();
55. }
56. this.ContactList = dao.list();
57. return SUCCESS;
58. }
59.
60. public String update() throws ParseException{
61. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-
dd");
62. Date dob = sdf.parse(getBirthdate());
63. contact.setBirthdate(dob);
64. contact.setCreated(date);
65. System.out.println(getContact());
66. try {
67.
68. dao.update(contact);
69. } catch (Exception e) {
70. e.printStackTrace();
71. }
72. this.ContactList = dao.list();
73. return SUCCESS;
74. }
75.
76. public String removeContact() throws ParseException {
77.
78. try {
79.
80. System.out.println("No of Selected Record:-
" + Checkbox.length);
81. for (int i=0;i<Checkbox.length; i++){
82. System.out.println("Selected RecordId:-
" + Checkbox[i]);
83. dao.deleteContact((Checkbox[i]));
84.
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 13/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

85. }
86.
87.
88. } catch (Exception e) {
89. e.printStackTrace();
90. }
91. this.ContactList = dao.list();
92. return SUCCESS;
93. }
94.
95.
96. public String deleteContact() {
97.
98. System.out.println("id value="+contact.getId());
99. int id = contact.getId();
100. try {
101.
102. dao.deleteContact(id);
103. } catch (Exception e) {
104. e.printStackTrace();
105. }
106. this.ContactList = dao.list();
107. return SUCCESS;
108. }
109.
110. public Contacts getContact() {
111. return contact;
112. }
113.
114. public void setContact(Contacts contact) {
115. this.contact = contact;
116. }
117.
118. public List<Contacts> getContactList() {
119. return ContactList;
120. }
121. public void setContactList(List<Contacts> ContactList) {
122. this.ContactList = ContactList;
123. }
124.
125. public int getId() {
126. return id;
127. }
128.
129. public void setId(int id) {
130. this.id = id;
131. }
132.
133. public String getBirthdate() {
134. return birthdate;
135. }
136.
137. public void setBirthdate(String birthdate) {
138. this.birthdate = birthdate;
139. }
140. public Integer[] getCheckbox() {
141. return Checkbox;
142. }
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 14/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

143. public void setCheckbox(Integer[] Checkbox) {


144. this.Checkbox = Checkbox;
145. }
146. }

8. struts.xml File

01. <?xml version="1.0" encoding="UTF-8"?>


02. <!DOCTYPE struts PUBLIC
03. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
04. "http://struts.apache.org/dtds/struts-2.0.dtd">
05.
06. <struts>
07. <constant name="struts.enable.DynamicMethodInvocation" value="f
08. <constant name="struts.devMode" value="false" />
09. <!-- Configuration for the default package. -->
10. <package name="default" extends="struts-default">
11. <default-action-ref name ="index"></default-action-ref>
12. <action name="index" class="com.struts.actions.ContactActio
13.
14. <result name="success">CRUD.jsp</result>
15. </action>
16. <!--
execute() method is default method which gets called when no meth
->
17. <!-
- execute() method is default method which gets called when we ca
18. It fetches the all the records and display in
CRUD.jsp.-->
19. <action name="add"
20. class="com.struts.actions.ContactAction" method="add">
21. <result name="success" type="chain">index</result>
22. <result name="input" type="chain">index</result>
23. </action>
24.
25. <action name="deleteContact"
26. class="com.struts.actions.ContactAction" method="delete
27. <result name="success" type="chain">index</result>
28.
29. </action>
30. <action name="removeContact"
31. class="com.struts.actions.ContactAction" method="remove
32. <result name="success" type="chain">index</result>
33.
34. </action>
35. <action name="update"
36. class="com.struts.actions.ContactAction" method="update
37. <result name="success" type="chain">index</result>
38.
39. </action>
40.
41. <action name="editLink"
42. class="com.struts.actions.ContactAction">
43. <result name="success">update.jsp</result>
44. </action>
45. <action name="listContacts" method="listContacts"
46. class="com.struts.actions.ContactAction" >
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 15/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

47. <result name="success">index.jsp</result>


48. </action>
49. </package>
50. </struts>

9. Creating index.jsp File

Right-click on WebPages folder-New-JSP-Give name index.jsp and click Finish. Similarly,


create delete.jsp and update.jsp files.

index.jsp code

01. <%@page contentType="text/html" pageEncoding="UTF-8"%>


02. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "htt
03.
04. <head>
05. <title></title>
06. <meta http-equiv="Content-
Type" content="text/html; charset=UTF-8">
07. <!--
This one opens CRUD.jsp page with all records in database when appl
->
08. <script type="text/javascript">
09.
10. window.location = "execute";
11. </script>
12. </head>

10. Creating CRUD.jsp File

01. <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-


8" language="java"%>
02. <%@ taglib prefix="s" uri="/struts-tags" %>
03. <%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
04. <%@taglib prefix="display" uri="http://displaytag.sf.net" %>
05.
06.
07. <head>
08. <meta http-equiv="Content-
Type" content="text/html; charset=UTF-8">
09. <title>Contact List</title>
10.
11. <sj:head></sj:head>
12.
13. </head>
14.
15. <h1>Contact Manager</h1>
16.
17. <s:actionerror/>
18. <s:form action="add" method="post" style="align:
19. center">
20. <s:textfield name="contact.firstname" label="Firstname"/>
21. <s:textfield name="contact.lastname" label="Lastname"/>

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 16/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

22. <s:radio name="contact.sex" label="Gender"


23. list="{'Male','Female'}" />
24. <s:textfield name="contact.emailId" label="Email"/>
25. <s:select name="contact.country" list="
{'India','USA','UK'}"
26. headerKey="" headerValue="Select"
27. label="Select a country" />
28. <s:textfield name="contact.cellNo" label="Cell No."/>
29. <s:textfield name="contact.website" label="Homepage"/>
30. <sj:datepicker id="5" name="birthdate" label="Date of Birth" ye
mm-dd" showButtonPanel="true"/>
31. <s:submit value="Add Contact" align="center"/>
32. </s:form>
33.
34. <%
35. int count = 0;
36.
37.
38. %>
39. <s:form action="removeContact">
40. <s:submit type="button" value="DeleteSelected" align="left"
41. onClick="return confirm('Do you want to delete these contacts?');
42. <display:table id="row" class="dataTable" export="true" name="cont
43. cellspacing="5px;" style="margin-left:25px;margin-
top:20px;width:120%" requestURI="">
44. <display:setProperty name="paging.banner.placement" value="bot
45. <display:column title="Select">
46. <s:checkbox id="check" name="Checkbox" fieldValue="%
{#attr.row.id}" theme="simple" value="#{attr.row.check}"/>
47. </display:column>
48. <display:column property="id" class="hidden" headerClass="hidden"
49. <display:column property="firstname" title="First Name" sortable="t
50. <display:column property="lastname" title="Last Name"/>
51. <display:column property="sex" class="hidden" headerClass="hidden"
52. <display:column property="emailId" title="Email"/>
53. <display:column property="country" title="Country"/>
54. <display:column property="cellNo" title="Cell No"/>
55. <display:column property="website" title="HomePage"/>
56. <display:column property="birthdate" class="hidden" headerClass="hi
{0,date,dd-MMM-yyyy}" title="BirthDate"/>
57. <display:setProperty name="export.excel.filename" value="ContactDet
58. <display:setProperty name="export.pdf.filename" value="ContactDetai
59. <display:setProperty name="export.csv.filename" value="ContactDeta
60.
61. <s:url id="editUrl" action="editLink">
62. <s:param name="id" value="%{#attr.row.id}"/>
63. <s:param name="firstname" value="%{#attr.row.firstname}"/>
64. <s:param name="lastname" value="%{#attr.row.lastname}"/>
65. <s:param name="sex" value="%{#attr.row.sex}"/>
66. <s:param name="emailId" value="%{#attr.row.emailId}"/>
67. <s:param name="country" value="%{#attr.row.country}"/>
68. <s:param name="cellNo" value="%{#attr.row.cellNo}"/>
69. <s:param name="website" value="%{#attr.row.website}"/>
70. <s:param name="birthdate" value="%{#attr.row.birthdate}"/>
71. </s:url>
72.
73. <display:column title="Action">
74. <s:a href="%{editUrl}">Display&Edit</s:a>
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 17/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

75. </display:column>
76.
77.
78. <s:url id="delContact" action="deleteContact">
79. <s:param name="contact.id" value="%{#attr.row.id}" />
80. </s:url>
81. <display:column title="Action">
82. <s:a href="%
{delContact}" onclick="return confirm('Are you sure you want to del
83. </display:column>
84. </display:table>
85. </s:form>

11. Update.jsp file code

01. <%@page contentType="text/html" pageEncoding="UTF-8"%>


02. <%@ taglib prefix="s" uri="/struts-tags" %>
03. <%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
04.
05. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "htt
06. <html>
07.
08. <head>
09. <meta http-equiv="Content-
Type" content="text/html; charset=UTF-8">
10. <title>Contact Detail & Update</title>
11.
12. <script type="text/javascript">
13.
14. function goBack(){
15.
16. <!--
This one opens CRUD.jsp page with all records in database when back
->
17. window.open("/Struts2HibernateCRUD/index.jsp","_self")
18.
19. }
20.
21. </script>
22. <sj:head></sj:head>
23.
24. </head>
25. <body>
26. <h1> Contact Detail & Update</h1>
27.
28. <s:form action="update" method="post" >
29.
30. <s:textfield name="contact.firstname" label="Firstname"
{#parameters.firstname}"/>
31. <s:textfield name="contact.lastname" label="Lastname" v
{#parameters.lastname}"/>
32. <s:radio name="contact.sex" label="Gender" list="
{'Male','Female'}" value="%{#parameters.sex}" />
33. <s:textfield name="contact.emailId" label="Email" value
{#parameters.emailId}" />
34. <s:select name="contact.country" list="
{'India','USA','UK'}"
https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 18/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

35. headerKey="" headerValue="Select" label="Select a cou


{#parameters.country}" />
36. <s:textfield name="contact.cellNo" label="Cell No" value="%
{#parameters.cellNo}" />
37. <s:textfield name="contact.website" label="Homepage" value="%
{#parameters.website}"/>
38. <sj:datepicker id="5" name="birthdate" label="Date of Birth" c
mm-dd" showButtonPanel="true"/>
39. <s:hidden name="contact.id" value="%
{#parameters.id}" label="Primary Key" />
40. <table >
41. <tr>
42. <td colspan="2">
43. <s:submit value="Update Contact" theme="simple" />
44. <input type="button" value="Back" onclick="goBack()"
45.
46. </td>
47. </tr>
48. </table>
49. </s:form>
50.
51. </body>
52. </html>

CRUD.jsp

Update.jsp

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 19/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

Modify the displayed record and click update contact.

Delete.jsp

Click Delete link to delete the corresponding record. Select the record for deletion by selecting
corresponding checkboxes and hit DeleteSelected button. Few columns are hidden and can be
seen by clicking Display&Update Link.

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 20/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

Export Option Hibernate4 CURD Java Struts2 MySQL Netbeans Pagination

Sorting

RECOMMENDED FREE EBOOK

Solutions Manual to Objects First with Java – A Practical


Introduction using BlueJ

Download Now!

SIMILAR ARTICLES

Profiling Java Application on NetBeans IDE

JSP and Hibernate CRUD application With Pagination, Sorting and export option using NetBeans IDE And
MySQL 5

Describing GUI Building on NetBeans IDE

Accessing Database Using Java and MySQL: Part 5

Primefaces5, Spring4, Hibernate4, CRUD Using Netbeans 8.02 And MySQL5 Database Server

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 21/22
11/30/23, 9:46 AM Java Struts2 And Hibernate4 CRUD With MySQL With Pagination, Sorting And Export Option Using Netbeans

Raichand Ray
https://www.c-sharpcorner.com/members/raichand-ray

970 590.4k

View All Comments


2

Type your comment here and press Enter Key (Minimum 10 characters)

olahraga
Ikuti‌‌o lahraga‌‌nnasional
asional‌‌
yang‌tidak
‌tidak‌resmi
‌resmi‌di
‌di‌‌
Singapura,yaitu‌yaitu‌‌
Kulineran.‌

Carousel‌‌Buffet‌‌Restaurant‌

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners

C# Tutorials Common Interview Questions Stories Consultants Ideas Certifications

Web3 Universe Build with JavaScript Let's React DB Talks Jumpstart Blockchain interviews.help
©2023 C# Corner. All contents are copyright of their authors.

https://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/ 22/22

You might also like