Tutorial: Create Struts2 Hibernate Example in Eclipse

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 net.viralpatel.contact.controller will hold the Java class that will act as controller and will fetch the data from database and pass it to view. The net.viralpatel.contact.model package will hold the Hibernate persistent model class. The net.viralpatel.contact.view will contain the struts2 action class. And finally the net.viralpatel.contact.util 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"%>


Contact Manager


Name Email Cell No. Birthdate Homepage Delete
, ">link ">delete

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 resources folder and copy following content into it.




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

	public static SessionFactory getSessionFactory() {
		return sessionFactory;

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;

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) {
		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;

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.java under net.viralpatel.contact.controller package and copy following content into it.

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();
		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 list() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		List contacts = null;
		try {
			contacts = (List)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 sessionFactory object.

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 file struts.xml in resources folder and add following content into it.






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 ContactAction.java under net.viralpatel.contact.view package and copy following content into it.

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 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() {
		try {
		} catch (Exception e) {
		this.contactList = contactManager.list();
		return SUCCESS;

	public String delete() {
		return SUCCESS;

	public Contact getContact() {
		return contact;

	public List getContactList() {
		return contactList;

	public void setContact(Contact contact) {
		this.contact = contact;

	public void setContactList(List contactsList) {
		this.contactList = contactsList;

	public Long getId() {
		return id;

	public void setId(Long id) {
		this.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 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:

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.

Download Source

Download Source without JAR files (19.2 KB)

Download Source with JAR files (8.5 MB)


  • saurabh 31 December, 2013, 12:08

    I am getting this error after clicking on add contact
    There is no Action mapped for namespace / and action name add.
    what is the issue??????? please sir tell me…

    • saurabh 31 December, 2013, 12:37

      thnk you so much sir its wrking …

    • Saurabh 25 February, 2014, 11:28

      hello sir…. cn i get the login demo also how , in which page will have two option one for
      registration and another for login and it should check the value from database using
      hibernate can anybody send me demo like dat m trying over net
      not able to find it….so plz help me…

  • Ibrahim 5 January, 2014, 17:55

    Hello saurabh
    there is an error in your struts.xml
    i think you have to add namespace=”/” in your balise package
    and/or you have to verify the name attribute of your action if it is name=”add” like this

    • saurabh 3 February, 2014, 14:21

      I am facing the issue…if u knw the solution then let me know….
      it is showing 404: No result defined for action net.viralpatel.contact.view.ContactAction and result input

  • manjuks 13 January, 2014, 16:36

    HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input
    i am facing above issue in this coding

    • saurabh 3 February, 2014, 14:09

      hello manju did u solve the problem ?
      I am also facing the same issue…if u knw the solution then let me know….
      it is showing 404: No result defined for action net.viralpatel.contact.view.ContactAction and result input

    • Ashu 4 March, 2014, 17:57

      Hi ,
      Have u resolved the error???
      i’m facing same error:
      HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input.

  • Gagan Chamria 28 January, 2014, 17:28

    Hi Sir,
    Nice example but can you tell me for my knowledge base how
    public void setId(Long id) {
    this.id = id;

    got the request parameter id when i click on delete link of any record?

    I am new in hibernate. Thanks in advance….

  • mahesh Kirdak 29 January, 2014, 12:47

    Thanks Sir…………..

  • ankit katiyar 31 January, 2014, 13:24

    hi viral
    i m getting this error
    HTTP Status 404 – There is no Action mapped for namespace / and action name add.
    type Status report
    message There is no Action mapped for namespace / and action name add.
    description The requested resource is not available.
    Apache Tomcat/7.0.40
    pls tell me how to remove this

  • pesari 31 January, 2014, 16:10

    When i click on Add Contact Button, Am getting the below error all the time can anyone help !!!!!!

    org.hibernate.HibernateException: identifier of an instance of hibernatemodel.Contact was altered from 3 to 0
    	at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:58)
    	at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:164)
    	at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:120)
    	at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
    	at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
  • Ashu 4 March, 2014, 17:55


    I’m getting below error:
    HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input

    Please provide me solution

  • Vineeth 7 March, 2014, 13:14

    SessionFactory is shown as deprecated . Do you have some example with the latest method ,using annotations

  • Abdel 18 March, 2014, 7:09


    I am getting this error after clicking on add contact
    There is no Action mapped for namespace / and action name add.

  • Umesh 26 March, 2014, 8:27

    I have used the same code but it shows the following error
    HTTP Status 404 – There is no Action mapped for namespace / and action name add.
    can any body resolve this error
    my struts.xml is




  • Rajesh 10 April, 2014, 17:43

    I am getting error as

    HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input

    can anybody help me ?????

  • Madhav 19 April, 2014, 17:50

    Those who are getting the error as HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input.

    Two Changes needs to be done.

    Change in struts.xml

     &lt;action name=&quot;add&quot;
                class=&quot;net.viralpatel.contact.view.ContactAction&quot; method=&quot;addMethod&quot;&gt;
                &lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;
                &lt;result name=&quot;input&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;
            &lt;action name=&quot;delete&quot;
                class=&quot;net.viralpatel.contact.view.ContactAction&quot; method=&quot;deleteMethod&quot;&gt;
                &lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;

    and also change appropriate methods in the Action class.

    The action name and the method name cannot be the same.

    Thanks viral for sharing this tutorial.

    • AntonioEl 6 July, 2014, 7:16

      Because you forgot to add this in between xml header and struts.

  • Faiyaz 22 April, 2014, 12:31

    I am getting error as
    HTTP Status 404 – No result defined for action net.viralpatel.contact.view.ContactAction and result input

  • Rogerio Cardin 2 May, 2014, 2:37

    Olá, está dando erro HTTP Status 404
    a Mensagem é:
    The requested resource (There is no Action mapped for namespace / and action name add.) is not available.
    Voce poderia ajudar??

  • Wunna Lwin 8 May, 2014, 8:32

    When i click the add contact, the error page showing that is There is no Action mapped for namespace / and action name index.jsp.
    How can i solve it. help me.

    • john muteti 30 July, 2014, 9:04

      Change your struts.xml
      “package name=”blah blah” extends=”hibernate-default”>

  • Sourabh 26 May, 2014, 14:53

    hello sir,i cant not understand the Flow of Execution.Can u Explain me in detail.who does every file is liked together??

  • AntonioEl 6 July, 2014, 7:09

    Whooo!!!.. Amazing!…. Hi Viral Patel thank you for this amazing step by step tutorial you made… It works everything in my Eclipse. Thank you very much.
    For those who will not run their code, Just try to check his download source files, this will help a lot in your learning progress…

  • hemanth 8 December, 2014, 22:51


    I am getting error like : java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher

Leave a Reply

Your email address will not be published. Required fields are marked *


To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]