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

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. /** 
    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, String cellno, String emailId, String country, String website, Date birthdate, Date created) {  
    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() {  
    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.out.println(contact.toString()) code  
    127.     @Override  
    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.
    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.  * 
    12.  * @author Raichand 
    13.  */  
    14. public class ContactDao extends HibernateUtil{  
    15.         
    16.     public void add(Contacts newcontact) {  
    17.         Session session = HibernateUtil.getSessionFactory().openSession();  
    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().openSession();  
    36.         session.beginTransaction();  
    37.           try {  
    38.         Contacts contact = (Contacts) session.load(Contacts.class,id);  
    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().openSession();  
    54.         session.beginTransaction();  
    55.       //Contacts contact = (Contacts) session.load(Contacts.class, id);  
    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().getCurrentSession();  
    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().openSession();  
    85.           List<Contacts> DaoAllContacts = null;         
    86.         session.beginTransaction();       
    87.         try {                         
    88.              
    89.                DaoAllContacts = session.createCriteria(Contacts.class).list();  
    90.                //DaoAllContacts = (List<Contacts>)session.createQuery("from Contacts").list();  
    91.                 int count =DaoAllContacts.size();  
    92.               System.out.println("No of Record From Dao: " + count);                
    93.         } catch (HibernateException e) {  
    94.             e.printStackTrace();  
    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.
    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.  * 
    9.  * @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 loaded");               
    21.             serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();  
    22.             System.out.println("Hibernate Annotation serviceRegistry created");               
    23.             sessionFactory = configuration.buildSessionFactory(serviceRegistry);               
    24.             return sessionFactory;  
    25.         }  
    26.         catch (Throwable ex) {  
    27.             // Make sure you log the exception, as it might be swallowed  
    28.             System.err.println("Initial SessionFactory creation failed." + ex);  
    29.             throw new ExceptionInInitializerError(ex);  
    30.         }    
    31. }  
    32.        public static SessionFactory getSessionFactory() {  
    33.         if(sessionFactory == null) sessionFactory = createSessionFactory();  
    34.         return sessionFactory;  
    35.     }  
    36.   }  
  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.  * 
    14.  * @author Raichand 
    15.  */  
    16. public class ContactAction extends ActionSupport   {  
    17.      private static final long serialVersionUID = 9149826260758390091L;  
    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) records for deletion.  
    26.       
    27.     public ContactAction() {  
    28.          dao= new ContactDao();  
    29.     }  
    30.     
    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.               
    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.     }  
    143.     public void setCheckbox(Integer[] Checkbox) {  
    144.         this.Checkbox = Checkbox;  
    145.     }   
    146. }  
  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.   
    6. <struts>  
    7.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
    8.     <constant name="struts.devMode" value="false" />  
    9.     <!-- 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.ContactAction">   
    13.              
    14.             <result name="success">CRUD.jsp</result>  
    15.         </action>   
    16.         <!--execute()  method is default method which  gets called when no method is specified-->  
    17.              <!-- execute()  method is default method which  gets called when we call /index action from browser.  
    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="deleteContact">  
    27.             <result name="success" type="chain">index</result>  
    28.               
    29.         </action>  
    30.          <action name="removeContact"  
    31.             class="com.struts.actions.ContactAction" method="removeContact">  
    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" >   
    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
    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.   
    4. <head>  
    5.     <title></title>  
    6.          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    7.         <!--This one opens CRUD.jsp page with all records in database when application starts-->  
    8.         <script type="text/javascript">  
    9.               
    10.            window.location = "execute";  
    11.         </script>  
    12.     </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.   
    6.   
    7.     <head>  
    8.          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    9.          <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"/>  
    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" yearRange="-90:" changeMonth="true" changeYear="true" displayFormat= "yy-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="contactList"   size="auto"   pagesize="5" cellpadding="5px;"  
    43.                 cellspacing="5px;" style="margin-left:25px;margin-top:20px;width:120%" requestURI="">  
    44.     <display:setProperty  name="paging.banner.placement" value="bottom"  />  
    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"  media="none"  title="ID" paramId="id" />  
    49. <display:column property="firstname" title="First Name" sortable="true"/>      
    50. <display:column property="lastname" title="Last Name"/>  
    51. <display:column property="sex" class="hidden" headerClass="hidden"  media="none" title="Gender"/>  
    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="hidden"  media="none" format="{0,date,dd-MMM-yyyy}"  title="BirthDate"/>  
    57. <display:setProperty name="export.excel.filename" value="ContactDetails.xls" />  
    58. <display:setProperty name="export.pdf.filename" value="ContactDetails.pdf" />  
    59. <display:setProperty  name="export.csv.filename" value="ContactDetails.csv" />  
    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>  
    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 delete this record')">Delete</s:a>  
    83. </display:column>  
    84.  </display:table>  
    85.  </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.   
    5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    6. <html>  
    7.       
    8.     <head>  
    9.         <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 button is clicked-->  
    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" value="%{#parameters.firstname}"/>  
    31.             <s:textfield name="contact.lastname" label="Lastname" value="%{#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'}"   
    35.               headerKey="" headerValue="Select" label="Select a country" value="%{#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" changeMonth="true" changeYear="true" displayFormat= "yy-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
 
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