CREATE TABLE CONTACTS
(
id INT PRIMARY KEY AUTO_INCREMENT,
firstname VARCHAR(30),
lastname VARCHAR(30),
cell_no VARCHAR(15),
email_id VARCHAR(30),
website VARCHAR(150),
birthdate DATE,
created TIMESTAMP DEFAULT NOW()
);
Code language: SQL (Structured Query Language) (sql)
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Contact Manager - Struts2 Hibernate Example</title>
</head>
<body>
<h1>Contact Manager</h1>
<s:actionerror/>
<s:form action="add" method="post">
<s:textfield name="contact.firstName" label="Firstname"/>
<s:textfield name="contact.lastName" label="Lastname"/>
<s:textfield name="contact.emailId" label="Email"/>
<s:textfield name="contact.cellNo" label="Cell No."/>
<s:textfield name="contact.website" label="Homepage"/>
<s:textfield name="contact.birthDate" label="Birthdate"/>
<s:submit value="Add Contact" align="center"/>
</s:form>
<h2>Contacts</h2>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Cell No.</th>
<th>Birthdate</th>
<th>Homepage</th>
<th>Delete</th>
</tr>
<s:iterator value="contactList" var="contact">
<tr>
<td><s:property value="lastName"/>, <s:property value="firstName"/> </td>
<td><s:property value="emailId"/></td>
<td><s:property value="cellNo"/></td>
<td><s:property value="birthDate"/></td>
<td><a href="<s:property value="website"/>">link</a></td>
<td><a href="delete?id=<s:property value="id"/>">delete</a></td>
</tr>
</s:iterator>
</table>
</body>
</html>
Code language: HTML, XML (xml)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/ContactManager
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="net.viralpatel.contact.model.Contact" />
</session-factory>
</hibernate-configuration>
Code language: HTML, XML (xml)
HibernateUtil.java – This is the Util file that we use to create connection with hibernate. Create HibernateUtil.java under package net.viralpatel.contact.util and copy following content into it. package net.viralpatel.contact.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Code language: Java (java)
Contact.java – This is the persistence entity class that will map to Contacts table in MySQL. Create Contact.java under net.viralpatel.contact.model package and copy following content into it. package net.viralpatel.contact.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Contacts")
public class Contact implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long id;
private String firstName;
private String lastName;
private String emailId;
private String cellNo;
private Date birthDate;
private String website;
private Date created;
@Id
@GeneratedValue
@Column(name="id")
public Long getId() {
return id;
}
@Column(name="firstname")
public String getFirstName() {
return firstName;
}
@Column(name="lastname")
public String getLastName() {
return lastName;
}
@Column(name="email_id")
public String getEmailId() {
return emailId;
}
@Column(name="cell_no")
public String getCellNo() {
return cellNo;
}
@Column(name="birthdate")
public Date getBirthDate() {
return birthDate;
}
@Column(name="website")
public String getWebsite() {
return website;
}
@Column(name="created")
public Date getCreated() {
return created;
}
public void setId(Long id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public void setCellNo(String cellNo) {
this.cellNo = cellNo;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setCreated(Date created) {
this.created = created;
}
public void setWebsite(String website) {
this.website = website;
}
}
Code language: Java (java)
Note how we have mapped Contact class with Contacts table using Java persistence API annotations. package net.viralpatel.contact.controller;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import net.viralpatel.contact.model.Contact;
import net.viralpatel.contact.util.HibernateUtil;
public class ContactManager extends HibernateUtil {
public Contact add(Contact contact) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(contact);
session.getTransaction().commit();
return contact;
}
public Contact delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Contact contact = (Contact) session.load(Contact.class, id);
if(null != contact) {
session.delete(contact);
}
session.getTransaction().commit();
return contact;
}
public List<Contact> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Contact> contacts = null;
try {
contacts = (List<Contact>)session.createQuery("from Contact").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return contacts;
}
}
Code language: Java (java)
Note that how we have created different methods in controller class to add/delete/list the contacts. Also the ContactManager class is extending HibernateUtil class thus allowing it to access sessionFactory object. <filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Code language: HTML, XML (xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="add"
class="net.viralpatel.contact.view.ContactAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="delete"
class="net.viralpatel.contact.view.ContactAction" method="delete">
<result name="success" type="chain">index</result>
</action>
<action name="index"
class="net.viralpatel.contact.view.ContactAction">
<result name="success">index.jsp</result>
</action>
</package>
</struts>
Code language: HTML, XML (xml)
Related: Create Struts Application in Eclipse Create Struts2 Application in Eclipse package net.viralpatel.contact.view;
import java.util.List;
import net.viralpatel.contact.controller.ContactManager;
import net.viralpatel.contact.model.Contact;
import com.opensymphony.xwork2.ActionSupport;
public class ContactAction extends ActionSupport {
private static final long serialVersionUID = 9149826260758390091L;
private Contact contact;
private List<Contact> contactList;
private Long id;
private ContactManager contactManager;
public ContactAction() {
contactManager = new ContactManager();
}
public String execute() {
this.contactList = contactManager.list();
System.out.println("execute called");
return SUCCESS;
}
public String add() {
System.out.println(getContact());
try {
contactManager.add(getContact());
} catch (Exception e) {
e.printStackTrace();
}
this.contactList = contactManager.list();
return SUCCESS;
}
public String delete() {
contactManager.delete(getId());
return SUCCESS;
}
public Contact getContact() {
return contact;
}
public List<Contact> getContactList() {
return contactList;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public void setContactList(List<Contact> contactsList) {
this.contactList = contactsList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Code language: Java (java)
ContactAction
class contains different methods that gets called by Struts2. The execute() method is the default method which gets called when we call /index action from browser. It fetches the list of contacts and display it in index.jsp. Similarly, when a new contact is added, add() method is called. If you check the action mapping entry in struts.xml
for add()
method, the <result> is mapped with /index
action and the type is chain. This is because we want to display the list of contact once we add a new one. Hence we have done Action chaining and called /index
action after /add
action. Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
First of all, thanks for the struts2 tutorials.
All the other examples worked well but in this one I seem to get two identical inserts every time I post the form. What might cause this? I'll try to dig into it this evening, but just in case I can't figure it out...
I have the same problem with two identical inserts.
@Antti, @GelbeTT: Have you tried to download the source code at the end of article. I think there is some prob with configuration.
hi viral patel,
Thanks for your tutorials. and i have one question. can you please tell me how can you load the hibernate.cfg.xml file in the HibernateUtil.java. we have to give the path to that file or it gets automatically. thanks for your help.
Hi Rajasekhar,
The hibernate.cfg.xml file will be automatically loaded by Hibernate. It must be present in classpath. This is why we have added this file in /resources folder which is a source folder.
Once the project is compiled, the hibernate.cfg.xml file will be available in WEB-INF/classes folder of webapp.
thankyou viral.
Hello Viral,
nice job, I enjoy your tutorials. Pretty straight forward. Thank you and keep on like this.
I have some inputs that can save hours to some like me:
1° The database created in MySQL must have the same name as specified in hibernate.cfg.xml at line 12(in your example ContactManager). Initially I put the table in other database (you said "in any database") and obviously the program didn't find it.
2° Concerning the double "add" to database, it's because theres a first "add": ---linkController.add(getContact());--- in ContactAction.java line 35, the add() method
and there's another one at line 24, in the execute() method.
I just commented the second one and is working just fine.
3° At the first access of the page, the table was not populated with data, even if in the DB it exist. I saw you tried to force the execution of "index.action" (which is in fact the execute() method of ContactAction class) by not declaring any parameter in web.xml
For some reason it doesn't work and I wonder if is fault of my configuration?
For me, the solution was to:
a) rename the index.jsp --> display.jsp
b)in struts.xml redirect the action "index" towards this new page
c)create a new index.html pretty empty with in the header
d) eventually indicate in web.xml the index.html
ok, hoping that this will help somenone
@dani: Thanks for the suggestions. I appreciate your effort to share your inputs. This will be definitely helpful for others. I will also try to modify the post and include your suggestions.
Thanks again.
3° At the first access of the page, the table was not populated with data, even if in the DB it exist.
How you solved this problem. I am also having same requirement. Please suggest.
Hi Sidd, How are you accessing the page first time?
http://localhost://index.jsp
or
http://localhost://index
If you are accessing it with 2nd URL, it will populate the data in table.
Thanks for your reply and yes when i am typing the URL "http://localhost:8080/ContactManager/index" data is getting populated. but it is showing "Nothing found to display" on the Top.
and when i am trying with URL "http://localhost:8080/ContactManager/" no data gets populated and the message "Nothing found to display" on the Top is coming any Guess.
Thanks
Sidd
Oh Sorry, I wrongly added the display tag in my JSP. When I remove that the message is gone.
Thanks.
One thing more Cant we populate the data by just hitting URL "http://localhost:8080/ContactManager/" if yes do i need to make some changes in my configuration.
i mean suppose that i have uploaded my site and user is hitting "www.contactmanager.com" then is it possible to get data populated.
Thanks in advance.
well, my previous comment didn't save the HTML tag so there are 2 lines that should look like this:
c)create a new index.html pretty empty with (META HTTP-EQUIV="Refresh" CONTENT="0;URL=index.action" ) in the header
and
d)eventually indicate in web.xml the (welcome-file) index.html (/welcome-file)
obviously all with brackets instead of parenthesis;
I tried the tutorial twice, did everything as you said, but I got: status 404 The requested resource (/Borra/) is not available. If you have any sugestions I would apreciate them. Tnks.
I got 404 The requested resource (/Borra/) is not available.
what can I do?
tnks
Hi Viral, Thanks for the KISS ( keep it short & sweet ) tutorial.
1. do i have to download each jar files separately or is there any RAR file that contains all the required jar files ? Is there any specific RAR file available by the apache org to make the struts2 appl compatible with Hibernate ?