Create Struts2 Hibernate Example in Eclipse

March 27, 2011 at 1:43 pm Leave a comment

This is a demo Contact Manager application that we will create using Struts2 and Hibernate framework. In this article we will see how we can use Hibernate to perform Insert / Delete operations in Struts2 framework.

Our Goal

Our goal will be to demonstrate the use of Struts2 with Hibernate framework and to create a demo application “Contact Manager”. The basic requirement of the Contact Manager app will be:

  1. Add new contact in the contact list.
  2. Display all contacts from contact list.
  3. Delete a contact from contact list.

Once we will build the application it will look like:

Getting Started

For our Contact Manager example, we will use MySQL database. Create a table contacts in any MySQL database. This is very preliminary example and thus we have minimum columns to represent a contact. Feel free to extend this example and create a more complex application.

	firstname 	VARCHAR(30),
	lastname	VARCHAR(30),
	cell_no		VARCHAR(15),
	email_id	VARCHAR(30),
	website		VARCHAR(150),
	birthdate	DATE,

Creating Project in Eclipse

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.
struts dynamic web project

After selecting Dynamic Web Project, press Next.
dynamic web project

Write the name of the project. For example ContactManager. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

We will need a source folder called resources. Right click on Project in project explorer and select New -> Source Folder and create a folder with name resources.

Also we will create Java packages for our application. As we will use Struts2, we will follow MVC architecture. Create 4 packages in the sources.

We created 4 new packages. The will hold the Java class that will act as controller and will fetch the data from database and pass it to view. package will hold the Hibernate persistent model class. will contain the struts2 action class. And finally will have some hibernate related util file that will be see shortly.

Required JAR Files

Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.

Create JSP for Contact Manager

We will need only one JSP file for this tutorial. The JSP will include a form to add new contact as well as will list the contacts at the end. Create a JSP file index.jsp in WebContent folder and copy following content into it.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
	<title>Contact Manager - Struts2 Hibernate Example</title>

<h1>Contact Manager</h1>

<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="" label="Homepage"/>
	<s:textfield name="contact.birthDate" label="Birthdate"/>
	<s:submit value="Add Contact" align="center"/>

	<th>Cell No.</th>
<s:iterator value="contactList" var="contact">
		<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>

Adding Hibernate Support

For adding hibernate support, we will add following source code in Contact Manager application.
hibernate.cfg.xml – This is the Hibernate configuration file. This file will contain configurations such as database connection information, persistence class info etc. Create hibernate.cfg.xml under resourcesfolder and copy following content into it.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

		<property name="connection.driver_class">
		<property name="connection.url">
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.pool_size">1</property>
		<property name="dialect">
		<property name="current_session_context_class">thread</property>
		<property name="cache.provider_class">
		<property name="show_sql">true</property>
		<property name="">update</property>

		<mapping />

</hibernate-configuration> – This is the Util file that we use to create connection with hibernate. Create under package and copy following content into it.


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()
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
} – This is the persistence entity class that will map to Contacts table in MySQL. Create under package and copy following content into it.


import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

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;

	public Long getId() {
		return id;
	public String getFirstName() {
		return firstName;
	public String getLastName() {
		return lastName;
	public String getEmailId() {
		return emailId;
	public String getCellNo() {
		return cellNo;
	public Date getBirthDate() {
		return birthDate;
	public String getWebsite() {
		return website;
	public Date getCreated() {
		return created;
	public void setId(Long 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) { = website;

Note how we have mapped Contact class with Contacts table using Java persistence API annotations.

Adding Controller to access data

We will add a controller class in Contact Manager application which will be used to get/save data from hibernate. This controller will be invoked from Struts action class. Create a file ContactManager.javaunder package and copy following content into it.


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;


public class ContactManager extends HibernateUtil {

	public Contact add(Contact contact) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		return contact;
	public Contact delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Contact contact = (Contact) session.load(Contact.class, id);
		if(null != contact) {
		return contact;

	public List<Contact> list() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		List<Contact> contacts = null;
		try {

			contacts = (List<Contact>)session.createQuery("from Contact").list();

		} catch (HibernateException e) {
		return contacts;

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 sessionFactoryobject.

Adding Struts2 Support

Let us add Struts2 support to our web application. For that, will add following entry in deployment descriptor (WEB-INF/web.xml).

Add Struts2 Filter in web.xml


Creating struts.xml

We will need to create struts.xml file that will hold the action mapping for our example. Create a filestruts.xml in resources folder and add following content into it.

<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

	<constant name="struts.enable.DynamicMethodInvocation"
		value="false" />
	<constant name="struts.devMode" value="false" />

	<package name="default" extends="struts-default" namespace="/">

		<action name="add"
			class="" method="add">
			<result name="success" type="chain">index</result>
			<result name="input" type="chain">index</result>

		<action name="delete"
			class="" method="delete">
			<result name="success" type="chain">index</result>

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

Create Struts Application in Eclipse
Create Struts2 Application in Eclipse

Create Action class

Up-till now we have almost completed our Contact Manager application in Struts2 and Hibernate. Only task left is to add Struts Action class. Create a class package and copy following content into it.


import java.util.List;


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 linkController;

	public ContactAction() {
		linkController = new ContactManager();
	public String execute() {
		if(null != contact) {
		this.contactList = linkController.list();
		return SUCCESS;
	public String add() {
		try {
		}catch(Exception e) {
		return SUCCESS;
	public String delete() {
		return SUCCESS;
	public Contact getContact() {
		return contact;
	public List<Contact> getContactList() {
		return contactList;
	public void setContact(Contact contact) { = contact;
	public void setContactList(List<Contact> contactsList) {
		this.contactList = contactsList;
	public Long getId() {
		return id;
	public void setId(Long id) { = id;

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.

The Contact Manager App

That’s it. The app is ready, just compile and run the project in Eclipse Run -> Run As -> Run on Server. Set the URL to:
http://localhost:<port>/<project name>/index

Fill the contact form and hit enter and the new contact will be persisted in database and will be shown in below table. Similarly, click on delete link next to a record. It will delete the record from database.

Let me know your input about this application.



Entry filed under: struts 2.

Advance J2EE Part 1: Introduction of Struts 2 Framework

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

%d bloggers like this: