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:
struts2-hibernate-contact-manager

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.

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

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.
struts2-hibernate-package

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.
WebContent/index.jsp

<%@ 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>

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.

<?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>

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

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

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();
		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;
	}
}

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

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

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

Related:
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<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;
	}
}

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

struts2-hibernate-contact-manager
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.
Cheers.

Download Source

Download Source without JAR files (19.2 KB)

Download Source with JAR files (8.5 MB)



286 Comments

  • hsathavara 11 January, 2013, 17:05

    How can we get list of the contacts displayed in jsp?
    Please explain the mechanism of the action to get list of the contacts.

  • Mukesh Kumar 6 February, 2013, 14:33

    HI Viral,
    I am very very thanks for this post. It is very helpful for me to struts 2 integration with hibernate.

  • dfhdhd 18 February, 2013, 16:46

    editting functionality not working

  • Maher 19 February, 2013, 19:03

    Hello VP, and thank u for this tutorial,
    if i want to add to this code an update, like update next to the delete link with update methods in action and manager.
    i get this record with a new method called fetchRecord(long id) ..
    how i get the result of this method if i dnt wanna use the request.setParameter in JSP and the action.
    thank you in advanced for your reply.

  • Enrico 28 February, 2013, 17:57

    Hello, I’m new to the world of web development, and this tutorial was very useful for me, thanks.

  • Santosh 5 March, 2013, 16:22

    hi, i am confused here please explaine form me in below code

    what is “contact” here

    thanks in advance

    Santosh Srivastava

    • Santosh 5 March, 2013, 16:31

      hi,
      i am confuse here what is “contact” in “contact.firstName” in jsp.

      thanks in advance
      Santosh Srivastava

  • Innocent 12 March, 2013, 16:40

    Hallo, I was brought to this web site, because I thought I could see jquery.autocomplete in action. from http://viralpatel.net/blogs/tutorial-create-autocomplete-feature-with-java-jsp-jquery/ where is the autocomplete ?!?

  • marouani 23 March, 2013, 23:13

    j’ai remplacé Mysql par oracle mais mais j’ai quelque erreurs je me demande s’il y a quelqu’un qui peut m’aider MERCI BIEN

  • marouani 23 March, 2013, 23:14

    java.lang.ExceptionInInitializerError
    net.viralpatel.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
    net.viralpatel.contact.util.HibernateUtil.(HibernateUtil.java:8)
    net.viralpatel.contact.view.ContactAction.(ContactAction.java:20)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    java.lang.Class.newInstance0(Unknown Source)
    java.lang.Class.newInstance(Unknown Source)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:119)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
    com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
    com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:288)
    com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

  • nadia 23 March, 2013, 23:51

    Salut j’ai remplacer Mysql par ORACLE mais j’ai quelque erreur j’espère qu’il y a quelqu’un qui peut m’aider MERCIII

    java.lang.ExceptionInInitializerError
    net.viralpatel.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
    net.viralpatel.contact.util.HibernateUtil.(HibernateUtil.java:8)
    net.viralpatel.contact.view.ContactAction.(ContactAction.java:20)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    java.lang.Class.newInstance0(Unknown Source)
    java.lang.Class.newInstance(Unknown Source)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:119)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
    com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
    com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:288)
    com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

  • marouani 25 March, 2013, 18:03

    j’ai remplacé Mysql par oracle mais j’ai quelque erreurs j’espère que vous m’aider
    java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

    cause mère

    java.lang.StackOverflowError
    java.security.AccessController.doPrivileged(Native Method)
    com.sun.naming.internal.VersionHelper12.getContextClassLoader(Unknown Source)
    com.sun.naming.internal.VersionHelper12.loadClass(Unknown Source)
    javax.naming.spi.NamingManager.getObjectFactoryFromReference(Unknown Source)
    javax.naming.spi.NamingManager.getObjectInstance(Unknown Source)
    org.apache.naming.NamingContext.lookup(NamingContext.java:793)
    org.apache.naming.NamingContext.lookup(NamingContext.java:140)
    org.apache.naming.NamingContext.lookup(NamingContext.java:781)
    org.apache.naming.NamingContext.lookup(NamingContext.java:153)
    org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
    javax.naming.InitialContext.lookup(Unknown Source)
    org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:162)
    org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:172)

  • Arden 2 April, 2013, 0:22

    Hi All,
    I’m getting a “Cannot open connection” error.
    Has this happened to anyone else?
    Best,
    A

    • Michael 5 April, 2013, 11:41

      Hi,Arden,
      I guess you need to change the file ‘hibernate.cfg.xml’ as the connection parameters is incorrect,e.g. please confirm the username or password is right ,wish can help to you:)

    • ajay 26 May, 2013, 7:27

      hi, just checj ur’s database name along with username and password of database.\
      in hibernate.cfg.xml file.

      com.mysql.jdbc.Driver

      jdbc:mysql://localhost:3306/test

      root
      root

  • Arden 2 April, 2013, 19:29

    Got it working, I was missing project libraries.

    Thank you for the great tutorial

    It would be nice to add an edit feature.

  • Vibha 8 April, 2013, 22:02

    Sir!.. I just need to know,how can I create this in netbeans… I have never worked on Eclipse.. It would be very kind of you,if you wud tell me…

  • surender 11 April, 2013, 14:16

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

    ——————————————————————————–

    type Status report

    message No result defined for action net.viralpatel.contact.view.ContactAction and result input

    description The requested resource (No result defined for action net.viralpatel.contact.view.ContactAction and result input) is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.29

    am finding this error can you tell me

    • Amit 15 June, 2013, 20:10

      I also encountered with the same problem.

      Actually it happens because of wrong input .

  • Vikram 12 April, 2013, 7:16

    This is good sample.. as I am a beginner for struts.. All the steps are very clearly mentioned…

  • Vikram 15 April, 2013, 6:01

    Hi Viral,

    I had one quick question for you? How can I create Update records functionality in this example.. I want to try and make some more modification to it but I am not getting any source to do soo.. it would be great help if you can explain me how to achieve this..

  • jaya 16 April, 2013, 1:23

    Hi

    I am trying a login form with struts ui tags. but my login page is not opening using tomcat
    here is the jsp file

    Customer Registration

    Customer Registration

    any help appreciated

  • Sajed Shaikh 17 April, 2013, 12:31

    HTTP Status 500 – Filter execution threw an exception

    type Exception report

    message Filter execution threw an exception

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Filter execution threw an exception

    root cause

    java.lang.ExceptionInInitializerError
    net.sajed.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
    net.sajed.contact.util.HibernateUtil.(HibernateUtil.java:8)
    net.sajed.contact.view.ContactAction.(ContactAction.java:21)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:119)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
    com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
    com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:288)
    com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

    root cause

    org.hibernate.HibernateException: /hibernate.cfg.xml not found
    org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
    org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1439)
    org.hibernate.cfg.Configuration.configure(Configuration.java:1461)
    org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
    net.sajed.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
    net.sajed.contact.util.HibernateUtil.(HibernateUtil.java:8)
    net.sajed.contact.view.ContactAction.(ContactAction.java:21)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    java.lang.Class.newInstance0(Class.java:355)
    java.lang.Class.newInstance(Class.java:308)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:119)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
    com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
    com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
    com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:288)
    com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.32 logs.
    Apache Tomcat/7.0.32
    [feedly mini]

  • radhika 17 April, 2013, 22:47

    Hi
    can some one help me ..getting no actopn mapped error cross checked all the jar in lib & buildpath but still getting it .
    e Status report

    There is no Action mapped for namespace / and action name index.

    thanks
    -pallavi

  • radhika 17 April, 2013, 22:49

    Hi
    can some one help me ..getting no actopn mapped error cross checked all the jar in lib & buildpath but still getting it .
    e Status report

    There is no Action mapped for namespace / and action name index.

    • kamal 30 May, 2013, 0:25

      same for me I think:”There is no Action mapped for namespace / and action name add.”

  • akram 23 April, 2013, 22:43

    works like a boss
    thanks man

  • mikemelon 11 May, 2013, 13:54

    Thank you for your project ! It is very useful for a learner.
    I have download, deployed and run the project.

    But I have find a BUG in this project, that is:
    when I insert the contact, I get two repeated contacts every time.

    I checked the code, and find in the execute() method of ContactAction.java,
    there is not consistent with this weblog.
    So I commented it and the problem disappears.

    	public String execute() {
    //		if(null != contact) {
    //			linkController.add(getContact());
    //		}
    		this.contactList = linkController.list();
    		System.out.println(contactList);
    		System.out.println(contactList.size());
    		return SUCCESS;
    	}
    
  • Ranjiz 23 May, 2013, 11:16

    Awesome coding…. Thanx dear frnd…

  • Amardeep 23 May, 2013, 17:49

    sir there is no mapping for viewing the add contact

  • Amardeep 23 May, 2013, 17:49

    please help me…….

  • vijay 31 May, 2013, 14:26

    Nice yaar !

    very helpful.

    executed well !!!

    Thank u….

  • Francesco 31 May, 2013, 19:33

    Hi there just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Opera.
    I’m not sure if this is a format issue or something to do with internet browser compatibility but I thought I’d post to let you know.
    The layout look great though! Hope you get the problem fixed
    soon. Many thanks

  • Alexxx 10 June, 2013, 14:43

    Hi, is possible to run it with H2 or other db?
    – I changed hibernate.cfg.xml pointing to new db e new driver,
    – deleted old db driver and copied the new one.
    – Redeployed
    but still have such error:
    11:05:27,855 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/StrutsHibernate].[default]] Servlet.service() for servlet default threw exception:

    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader@168fc43e{vfs:///C:/Users/alex/workspaceAnd/.metadata/.plugins/org.jboss.ide.eclipse.as.core/jboss-6.1.0.Final/deploy/StrutsHibernate.war}
    	at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:480) [jboss-classloader.jar:2.2.1.GA]
    	at java.lang.ClassLoader.loadClass(Unknown Source) [:1.6.0_34]
    	at java.lang.Class.forName0(Native Method) [:1.6.0_34]
    	at java.lang.Class.forName(Unknown Source) [:1.6.0_34]
    	at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:123) [:3.3.1.GA]
    	at org.hibernate.connection.DriverManagerConnectionProvider.configure(DriverManagerConnectionProvider.java:84) [:3.3.1.GA]
    	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:137) [:3.3.1.GA]
    	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:79) [:3.3.1.GA]
    	at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:448) [:3.3.1.GA]
    	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:89) [:3.3.1.GA]
    	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2101) [:3.3.1.GA]
    	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1325) [:3.3.1.GA]
    	at net.viralpatel.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14) [:]
    	at net.viralpatel.contact.util.HibernateUtil.(HibernateUtil.java:8) [:]
    	at net.viralpatel.contact.view.ContactAction.(ContactAction.java:21) [:]
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [:1.6.0_34]
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) [:1.6.0_34]
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) [:1.6.0_34]
    

    Why? Miss to do some other changes?

    • Viral Patel 10 June, 2013, 15:28

      You are getting this error because MySQL driver jar is not present in your classpath. I assume you dont want to run this example with MySQL. In that case you need to change the connection.driver_class and dialect properties in hibernate.cfg.xml file to appropriate driver class. Also the username/password and connection string needs to be modified accordingly. Only hibernate.cfg.xml file will be changed.

  • sushma 13 June, 2013, 18:01

    hi,
    i am gettingNPE when i try to add contact and in console {log4j:WARN No appenders could be found for logger (com.opensymphony.xwork2.config.providers.XmlConfigurationProvider).
    log4j:WARN Please initialize the log4j system properly.}
    Somebody please help,thanks in advance

    java.lang.NullPointerException
    org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:500)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)

  • Amit 15 June, 2013, 18:26

    Hi Viral

    I am using this application , but i made some changes in database section,, i am using oracle 10g XE , i already changed the hibernate.cfg.xml, also added required library. but i am getting the exception

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

    ——————————————————————————–

    type Status report

    message No result defined for action net.viralpatel.contact.view.ContactAction and result input

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/6.0.37

    Waiting for ur reply
    Thanks,
    Amit

  • Amit 15 June, 2013, 20:06

    Hi Viral,

    Finally i executed this tutorial with oracle 10g .

    Thanks for a nice tutorial.

    I have a question that what is the difference b/w ActionSupport and ActionServlet ?
    I checked on google its saying just ActionSupport is used in Struts2.0 and ActionServlet is used for struts1.x ,, but i am not satisfied can u please help me on this.

    Thanks,
    Amit

Leave a Reply

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

Note

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]