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.
connection
Create ‘contacts’ table, using the script, given below, in MySQL ‘test’ Database-
  1. CREATE TABLE IF NOT EXISTS `contacts` (
  2. `id` int(11) NOT NULL,
  3. `firstname` varchar(30) DEFAULT NULL,
  4. `lastname` varchar(30) DEFAULT NULL,
  5. `birthdate` date DEFAULT NULL,
  6. `cell_no` varchar(15) DEFAULT NULL,
  7. `country` varchar(20) DEFAULT NULL,
  8. `created` datetime NOT NULL,
  9. `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_INCREMENT=1;
Insert the records by executing the queries, given below-
  1. INSERT INTO `contacts` (`id`, `birthdate`, `cell_no`, `country`, `created`, `email_id`, `firstname`, `lastname`, `sex`, `website`) VALUES
  2. (1, '1980-05-06', '9834145667', 'USA', '2016-05-26 19:07:17', '[email protected]', 'Richard', 'Johnson', 'Male', 'www.richardinfo.com'),
  3. (2, '1982-05-05', '9839753298', 'USA', '2016-05-26 19:08:26', '[email protected]', 'Martha', 'Stewart', 'Female', 'www.martha.com'),
  4. (3, '1985-05-16', '9839753298', 'USA', '2016-05-26 19:09:29', '[email protected]', 'Clive', 'Sweetman', 'Male', 'www.clive.com');
Project Structure
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
  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.
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    3. <hibernate-configuration>
    4. <session-factory>
    5. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    6. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    7. <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull</property>
    8. <property name="hibernate.connection.username">root</property>
    9. <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.NoCacheProvider</property>
    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.
    Reverse Engineering File
    Right click on default package in the Source Package-new-choose Hibernate Reverse Engineering Wizard-click next-choose emp table-Add -click finish.
    CODE
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
    3. <hibernate-reverse-engineering>
    4. <schema-selection match-catalog="test"/>
    5. <table-filter match-name="contacts"/>
    6. </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.
    model
    Contacts.java Class File is given.
    1. package com.pojos.model;
    2. // Generated Feb 15, 2016 8:57:30 AM by Hibernate Tools 4.3.1
    3. import java.util.Date;
    4. import javax.persistence.Column;
    5. import javax.persistence.Entity;
    6. import javax.persistence.GeneratedValue;
    7. import static javax.persistence.GenerationType.IDENTITY;
    8. import javax.persistence.Id;
    9. import javax.persistence.Table;
    10. import javax.persistence.Temporal;
    11. import javax.persistence.TemporalType;
    12. /**
    13. * Contacts generated by hbm2java
    14. */
    15. @Entity
    16. @Table(name="contacts"
    17. ,catalog="test"
    18. )
    19. public class Contacts implements java.io.Serializable {
    20. private Integer id;
    21. private String firstname;
    22. private String lastname;
    23. private String sex;
    24. private String cellno;
    25. private String emailId;
    26. private String country;
    27. private String website;
    28. private Date birthdate;
    29. private Date created;
    30. public Contacts() {
    31. }
    32. public Contacts(Date created) {
    33. this.created = created;
    34. }
    35. public Contacts(String firstname, String lastname, String sex, String cellno, String emailId, String country, String website, Date birthdate, Date created) {
    36. this.firstname = firstname;
    37. this.lastname = lastname;
    38. this.sex = sex;
    39. this.cellno = cellno;
    40. this.emailId = emailId;
    41. this.country = country;
    42. this.website = website;
    43. this.birthdate = birthdate;
    44. this.created = created;
    45. }
    46. @Id @GeneratedValue(strategy=IDENTITY)
    47. @Column(name="id", unique=true, nullable=false)
    48. public Integer getId() {
    49. return this.id;
    50. }
    51. public void setId(Integer id) {
    52. this.id = id;
    53. }
    54. @Column(name="firstname", length=30)
    55. public String getFirstname() {
    56. return this.firstname;
    57. }
    58. public void setFirstname(String firstname) {
    59. this.firstname = firstname;
    60. }
    61. @Column(name="lastname", length=30)
    62. public String getLastname() {
    63. return this.lastname;
    64. }
    65. public void setLastname(String lastname) {
    66. this.lastname = lastname;
    67. }
    68. @Column(name="sex", length=10)
    69. public String getSex() {
    70. return this.sex;
    71. }
    72. public void setSex(String sex) {
    73. this.sex = sex;
    74. }
    75. @Column(name="cell_no", length=15)
    76. public String getCellno() {
    77. return cellno;
    78. }
    79. public void setCellno(String cellno) {
    80. this.cellno = cellno;
    81. }
    82. @Column(name="email_id", length=30)
    83. public String getEmailId() {
    84. return this.emailId;
    85. }
    86. public void setEmailId(String emailId) {
    87. this.emailId = emailId;
    88. }
    89. @Column(name="country", length=30)
    90. public String getCountry() {
    91. return this.country;
    92. }
    93. public void setCountry(String country) {
    94. this.country = country;
    95. }
    96. @Column(name="website", length=30)
    97. public String getWebsite() {
    98. return this.website;
    99. }
    100. public void setWebsite(String website) {
    101. this.website = website;
    102. }
    103. @Temporal(TemporalType.DATE)
    104. @Column(name="birthdate", length=10)
    105. public Date getBirthdate() {
    106. return this.birthdate;
    107. }
    108. public void setBirthdate(Date birthdate) {
    109. this.birthdate = birthdate;
    110. }
    111. @Temporal(TemporalType.TIMESTAMP)
    112. @Column(name="created", nullable=false, length=19)
    113. public Date getCreated() {
    114. return this.created;
    115. }
    116. public void setCreated(Date created) {
    117. this.created = created;
    118. }
    119. //This method writes the values of contact object with System.out.println(contact.toString()) code
    120. @Override
    121. public String toString() {
    122. return "Contact"
    123. + "\n\t Id: " + this.id
    124. + "\n\t FirstName: " + this.firstname
    125. + "\n\t LastName: " + this.lastname
    126. + "\n\t Sex: " + this.sex
    127. + "\n\t CellNo: " + this.cellno
    128. + "\n\t Country: " + this.country
    129. + "\n\t WebSite: " + this.website
    130. + "\n\t EmailId: " + this.emailId
    131. + "\n\t BirthDate: " + this.birthdate
    132. + "\n\t Date Created: " + this.created;
    133. }
    134. }
  4. Creating DataAccessObject (DAO) File
    Right-click on com. dao package-new-JavaClass. Give the class name as ContactDao and click Finish.
    1. package com.dao;
    2. import java.util.List;
    3. import java.util.ArrayList;
    4. import com.pojos.model.Contacts;
    5. import com.util.HibernateUtil;
    6. import org.hibernate.HibernateException;
    7. import org.hibernate.Session;
    8. import org.hibernate.Transaction;
    9. /**
    10. *
    11. * @author Raichand
    12. */
    13. public class ContactDao extends HibernateUtil{
    14. public void add(Contacts newcontact) {
    15. Session session = HibernateUtil.getSessionFactory().openSession();
    16. String fname = newcontact.getFirstname();
    17. System.out.println("FirstName=" + fname);
    18. //int newid = this.getNewContactId();
    19. // newcontact.setId(newid);
    20. //int contactid = newcontact.getId();
    21. //System.out.println("DaoContact id ;-" + contactid);
    22. System.out.println("From Dao:-" + newcontact);
    23. session.beginTransaction();
    24. //session.merge(newcontact);
    25. session.save(newcontact);
    26. session.getTransaction().commit();
    27. session.flush();
    28. session.close();
    29. }
    30. public void deleteContact(int id) {
    31. Session session = HibernateUtil.getSessionFactory().openSession();
    32. session.beginTransaction();
    33. try {
    34. Contacts contact = (Contacts) session.load(Contacts.class,id);
    35. if(null != contact) {
    36. session.delete(contact);
    37. }
    38. } catch (HibernateException e) {
    39. e.printStackTrace();
    40. session.getTransaction().rollback();
    41. }
    42. session.getTransaction().commit();
    43. session.flush();
    44. session.close();
    45. }
    46. public void update(Contacts contact) {
    47. Session session = HibernateUtil.getSessionFactory().openSession();
    48. session.beginTransaction();
    49. //Contacts contact = (Contacts) session.load(Contacts.class, id);
    50. try {
    51. if(contact != null) {
    52. session.saveOrUpdate(contact);
    53. }
    54. } catch (HibernateException e) {
    55. e.printStackTrace();
    56. session.getTransaction().rollback();
    57. }
    58. session.getTransaction().commit();
    59. session.flush();
    60. session.close();
    61. }
    62. public int getNewContactId() {
    63. Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    64. Transaction trans = session.beginTransaction();
    65. String query = "SELECT max(c.id) FROM Contacts c";
    66. List list = session.createQuery(query).list();
    67. int maxId = ((Integer) list.get(0));
    68. trans.commit();
    69. session.close();
    70. return (maxId+1);
    71. }
    72. public List<Contacts> list(){
    73. Session session = HibernateUtil.getSessionFactory().openSession();
    74. List<Contacts> DaoAllContacts = null;
    75. session.beginTransaction();
    76. try {
    77. DaoAllContacts = session.createCriteria(Contacts.class).list();
    78. //DaoAllContacts = (List<Contacts>)session.createQuery("from Contacts").list();
    79. int count =DaoAllContacts.size();
    80. System.out.println("No of Record From Dao: " + count);
    81. } catch (HibernateException e) {
    82. e.printStackTrace();
    83. session.getTransaction().rollback();
    84. }
    85. session.getTransaction().commit();
    86. session.flush();
    87. session.close();
    88. return DaoAllContacts;
    89. }
    90. }
  5. HibernateUtil.java File
    Right-click on com.util folder-new-javaclass-Class name. Give the name as HibernateUtil and click Finish.
    1. package com.util;
    2. import org.hibernate.SessionFactory;
    3. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    4. import org.hibernate.cfg.Configuration;
    5. import org.hibernate.service.ServiceRegistry;
    6. /**
    7. *
    8. * @author Raichand
    9. */
    10. public class HibernateUtil {
    11. private static SessionFactory sessionFactory;
    12. private static ServiceRegistry serviceRegistry;
    13. private static SessionFactory createSessionFactory() {
    14. try {
    15. // Create the SessionFactory from hibernate.cfg.xml
    16. Configuration configuration = new Configuration();
    17. configuration.configure("hibernate.cfg.xml");
    18. System.out.println("Hibernate Annotation Configuration loaded");
    19. serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    20. System.out.println("Hibernate Annotation serviceRegistry created");
    21. sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    22. return sessionFactory;
    23. }
    24. catch (Throwable ex) {
    25. // Make sure you log the exception, as it might be swallowed
    26. System.err.println("Initial SessionFactory creation failed." + ex);
    27. throw new ExceptionInInitializerError(ex);
    28. }
    29. }
    30. public static SessionFactory getSessionFactory() {
    31. if(sessionFactory == null) sessionFactory = createSessionFactory();
    32. return sessionFactory;
    33. }
    34. }
  6. web.xml (Automatically generated, followed by copying and pasting the code, given below)-
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <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">
    3. <filter>
    4. <filter-name>struts2</filter-name>
    5. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    6. </filter>
    7. <filter-mapping>
    8. <filter-name>struts2</filter-name>
    9. <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.
    1. package com.struts.actions;
    2. import java.util.Date;
    3. import java.util.ArrayList;
    4. import java.util.List;
    5. import com.opensymphony.xwork2.ActionSupport;
    6. import com.dao.ContactDao;
    7. import com.pojos.model.Contacts;
    8. import java.text.ParseException;
    9. import java.text.SimpleDateFormat;
    10. import java.util.Locale;
    11. /**
    12. *
    13. * @author Raichand
    14. */
    15. public class ContactAction extends ActionSupport {
    16. private static final long serialVersionUID = 9149826260758390091L;
    17. private Contacts contact= new Contacts();
    18. private List<Contacts> ContactList= new ArrayList<Contacts>();
    19. private int id;
    20. private String birthdate;
    21. private Date date = new Date();
    22. private ContactDao dao;
    23. private Integer[] Checkbox;//stores id of selected(checked) records for deletion.
    24. public ContactAction() {
    25. dao= new ContactDao();
    26. }
    27. @Override
    28. public String execute() {
    29. this.ContactList = dao.list();
    30. int count = ContactList.size();
    31. System.out.println("contactList Size"+ count);
    32. //System.out.println("execute called");
    33. return SUCCESS;
    34. }
    35. public String add() throws ParseException {
    36. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
    37. Date dob = sdf.parse(getBirthdate());
    38. contact.setCreated(date);
    39. contact.setBirthdate(dob);
    40. System.out.println(birthdate);
    41. System.out.println(contact);
    42. try {
    43. dao.add(contact);
    44. } catch (Exception e) {
    45. e.printStackTrace();
    46. }
    47. this.ContactList = dao.list();
    48. return SUCCESS;
    49. }
    50. public String update() throws ParseException{
    51. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    52. Date dob = sdf.parse(getBirthdate());
    53. contact.setBirthdate(dob);
    54. contact.setCreated(date);
    55. System.out.println(getContact());
    56. try {
    57. dao.update(contact);
    58. } catch (Exception e) {
    59. e.printStackTrace();
    60. }
    61. this.ContactList = dao.list();
    62. return SUCCESS;
    63. }
    64. public String removeContact() throws ParseException {
    65. try {
    66. System.out.println("No of Selected Record:-" + Checkbox.length);
    67. for (int i=0;i<Checkbox.length; i++){
    68. System.out.println("Selected RecordId:-" + Checkbox[i]);
    69. dao.deleteContact((Checkbox[i]));
    70. }
    71. } catch (Exception e) {
    72. e.printStackTrace();
    73. }
    74. this.ContactList = dao.list();
    75. return SUCCESS;
    76. }
    77. public String deleteContact() {
    78. System.out.println("id value="+contact.getId());
    79. int id = contact.getId();
    80. try {
    81. dao.deleteContact(id);
    82. } catch (Exception e) {
    83. e.printStackTrace();
    84. }
    85. this.ContactList = dao.list();
    86. return SUCCESS;
    87. }
    88. public Contacts getContact() {
    89. return contact;
    90. }
    91. public void setContact(Contacts contact) {
    92. this.contact = contact;
    93. }
    94. public List<Contacts> getContactList() {
    95. return ContactList;
    96. }
    97. public void setContactList(List<Contacts> ContactList) {
    98. this.ContactList = ContactList;
    99. }
    100. public int getId() {
    101. return id;
    102. }
    103. public void setId(int id) {
    104. this.id = id;
    105. }
    106. public String getBirthdate() {
    107. return birthdate;
    108. }
    109. public void setBirthdate(String birthdate) {
    110. this.birthdate = birthdate;
    111. }
    112. public Integer[] getCheckbox() {
    113. return Checkbox;
    114. }
    115. public void setCheckbox(Integer[] Checkbox) {
    116. this.Checkbox = Checkbox;
    117. }
    118. }
  8. struts.xml File
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE struts PUBLIC
    3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    4. "http://struts.apache.org/dtds/struts-2.0.dtd">
    5. <struts>
    6. <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    7. <constant name="struts.devMode" value="false" />
    8. <!-- Configuration for the default package. -->
    9. <package name="default" extends="struts-default">
    10. <default-action-ref name ="index"></default-action-ref>
    11. <action name="index" class="com.struts.actions.ContactAction">
    12. <result name="success">CRUD.jsp</result>
    13. </action>
    14. <!--execute() method is default method which gets called when no method is specified-->
    15. <!-- execute() method is default method which gets called when we call /index action from browser.
    16. It fetches the all the records and display in CRUD.jsp.-->
    17. <action name="add"
    18. class="com.struts.actions.ContactAction" method="add">
    19. <result name="success" type="chain">index</result>
    20. <result name="input" type="chain">index</result>
    21. </action>
    22. <action name="deleteContact"
    23. class="com.struts.actions.ContactAction" method="deleteContact">
    24. <result name="success" type="chain">index</result>
    25. </action>
    26. <action name="removeContact"
    27. class="com.struts.actions.ContactAction" method="removeContact">
    28. <result name="success" type="chain">index</result>
    29. </action>
    30. <action name="update"
    31. class="com.struts.actions.ContactAction" method="update">
    32. <result name="success" type="chain">index</result>
    33. </action>
    34. <action name="editLink"
    35. class="com.struts.actions.ContactAction">
    36. <result name="success">update.jsp</result>
    37. </action>
    38. <action name="listContacts" method="listContacts"
    39. class="com.struts.actions.ContactAction" >
    40. <result name="success">index.jsp</result>
    41. </action>
    42. </package>
    43. </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
    1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
    2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    3. <head>
    4. <title></title>
    5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    6. <!--This one opens CRUD.jsp page with all records in database when application starts-->
    7. <script type="text/javascript">
    8. window.location = "execute";
    9. </script>
    10. </head>
  10. Creating CRUD.jsp File
    1. <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" language="java"%>
    2. <%@ taglib prefix="s" uri="/struts-tags" %>
    3. <%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
    4. <%@taglib prefix="display" uri="http://displaytag.sf.net" %>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Contact List</title>
    8. <sj:head></sj:head>
    9. </head>
    10. <h1>Contact Manager</h1>
    11. <s:actionerror/>
    12. <s:form action="add" method="post" style="align:
    13. center">
    14. <s:textfield name="contact.firstname" label="Firstname"/>
    15. <s:textfield name="contact.lastname" label="Lastname"/>
    16. <s:radio name="contact.sex" label="Gender"
    17. list="{'Male','Female'}" />
    18. <s:textfield name="contact.emailId" label="Email"/>
    19. <s:select name="contact.country" list="{'India','USA','UK'}"
    20. headerKey="" headerValue="Select"
    21. label="Select a country" />
    22. <s:textfield name="contact.cellNo" label="Cell No."/>
    23. <s:textfield name="contact.website" label="Homepage"/>
    24. <sj:datepicker id="5" name="birthdate" label="Date of Birth" yearRange="-90:" changeMonth="true" changeYear="true" displayFormat= "yy-mm-dd" showButtonPanel="true"/>
    25. <s:submit value="Add Contact" align="center"/>
    26. </s:form>
    27. <%
    28. int count = 0;
    29. %>
    30. <s:form action="removeContact">
    31. <s:submit type="button" value="DeleteSelected" align="left"
    32. onClick="return confirm('Do you want to delete these contacts?');"/>
    33. <display:table id="row" class="dataTable" export="true" name="contactList" size="auto" pagesize="5" cellpadding="5px;"
    34. cellspacing="5px;" style="margin-left:25px;margin-top:20px;width:120%" requestURI="">
    35. <display:setProperty name="paging.banner.placement" value="bottom" />
    36. <display:column title="Select">
    37. <s:checkbox id="check" name="Checkbox" fieldValue="%{#attr.row.id}" theme="simple" value="#{attr.row.check}"/>
    38. </display:column>
    39. <display:column property="id" class="hidden" headerClass="hidden" media="none" title="ID" paramId="id" />
    40. <display:column property="firstname" title="First Name" sortable="true"/>
    41. <display:column property="lastname" title="Last Name"/>
    42. <display:column property="sex" class="hidden" headerClass="hidden" media="none" title="Gender"/>
    43. <display:column property="emailId" title="Email"/>
    44. <display:column property="country" title="Country"/>
    45. <display:column property="cellNo" title="Cell No"/>
    46. <display:column property="website" title="HomePage"/>
    47. <display:column property="birthdate" class="hidden" headerClass="hidden" media="none" format="{0,date,dd-MMM-yyyy}" title="BirthDate"/>
    48. <display:setProperty name="export.excel.filename" value="ContactDetails.xls" />
    49. <display:setProperty name="export.pdf.filename" value="ContactDetails.pdf" />
    50. <display:setProperty name="export.csv.filename" value="ContactDetails.csv" />
    51. <s:url id="editUrl" action="editLink">
    52. <s:param name="id" value="%{#attr.row.id}"/>
    53. <s:param name="firstname" value="%{#attr.row.firstname}"/>
    54. <s:param name="lastname" value="%{#attr.row.lastname}"/>
    55. <s:param name="sex" value="%{#attr.row.sex}"/>
    56. <s:param name="emailId" value="%{#attr.row.emailId}"/>
    57. <s:param name="country" value="%{#attr.row.country}"/>
    58. <s:param name="cellNo" value="%{#attr.row.cellNo}"/>
    59. <s:param name="website" value="%{#attr.row.website}"/>
    60. <s:param name="birthdate" value="%{#attr.row.birthdate}"/>
    61. </s:url>
    62. <display:column title="Action">
    63. <s:a href="%{editUrl}">Display&Edit</s:a>
    64. </display:column>
    65. <s:url id="delContact" action="deleteContact">
    66. <s:param name="contact.id" value="%{#attr.row.id}" />
    67. </s:url>
    68. <display:column title="Action">
    69. <s:a href="%{delContact}" onclick="return confirm('Are you sure you want to delete this record')">Delete</s:a>
    70. </display:column>
    71. </display:table>
    72. </s:form>
  11. Update.jsp file code
    1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
    2. <%@ taglib prefix="s" uri="/struts-tags" %>
    3. <%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
    4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    5. <html>
    6. <head>
    7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8. <title>Contact Detail & Update</title>
    9. <script type="text/javascript">
    10. function goBack(){
    11. <!--This one opens CRUD.jsp page with all records in database when back button is clicked-->
    12. window.open("/Struts2HibernateCRUD/index.jsp","_self");
    13. }
    14. </script>
    15. <sj:head></sj:head>
    16. </head>
    17. <body>
    18. <h1> Contact Detail & Update</h1>
    19. <s:form action="update" method="post" >
    20. <s:textfield name="contact.firstname" label="Firstname" value="%{#parameters.firstname}"/>
    21. <s:textfield name="contact.lastname" label="Lastname" value="%{#parameters.lastname}"/>
    22. <s:radio name="contact.sex" label="Gender" list="{'Male','Female'}" value="%{#parameters.sex}" />
    23. <s:textfield name="contact.emailId" label="Email" value="%{#parameters.emailId}" />
    24. <s:select name="contact.country" list="{'India','USA','UK'}"
    25. headerKey="" headerValue="Select" label="Select a country" value="%{#parameters.country}" />
    26. <s:textfield name="contact.cellNo" label="Cell No" value="%{#parameters.cellNo}" />
    27. <s:textfield name="contact.website" label="Homepage" value="%{#parameters.website}"/>
    28. <sj:datepicker id="5" name="birthdate" label="Date of Birth" changeMonth="true" changeYear="true" displayFormat= "yy-mm-dd" showButtonPanel="true"/>
    29. <s:hidden name="contact.id" value="%{#parameters.id}" label="Primary Key" />
    30. <table >
    31. <tr>
    32. <td colspan="2">
    33. <s:submit value="Update Contact" theme="simple" />
    34. <input type="button" value="Back" onclick="goBack()"/>
    35. </td>
    36. </tr>
    37. </table>
    38. </s:form>
    39. </body>
    40. </html>
CRUD.jsp
CRUD.jsp
Update.jsp
Update.jsp
Modify the displayed record and click update contact.
Delete.jsp
 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.
Display