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)



183 Comments

  • madhu wrote on 27 September, 2010, 23:42

    I am using jboss and getting the error
    There is no Action mapped for namespace / and action name add. – [unknown location]
    at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:178)
    at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.int

    • rajesh yadav wrote on 21 April, 2011, 20:01

      hey first in index.jsp set add.action wich is only add.and also in the struts.xml has the only index notification so do it as the index.jsp and then map the actions in the java

  • flowers nellore wrote on 1 October, 2010, 22:15

    Great step by step feeding. I like your article.

  • An Phu wrote on 5 October, 2010, 12:49

    I’m try to do step by step but i’m worker with netbean 6.9 and i have a problem , can you help me plz !

    HTTP Status 500 -

    type Exception report

    message

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

    exception

    javax.servlet.ServletException: Filter execution threw an exception
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

    root cause

    java.lang.NoClassDefFoundError: Could not initialize class net.viralpatel.contact.controller.ContactManager
    net.viralpatel.contact.view.ContactAction.(ContactAction.java:20)
    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)
    org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)

    note The full stack trace of the root cause is available in the JBoss Web/2.1.2.GA logs.

  • Fan wrote on 9 October, 2010, 6:53

    Simple and understandable example. However, I also had to jump through hoops to get the right library files, build file, etc. to get it working. But I guess that’s part of the learning exercise. You learn better when you falter :)

    Great job. Keep it up.

  • reza wrote on 21 October, 2010, 14:50

    a very good article and understandable… :)

  • JC wrote on 26 October, 2010, 8:52

    My eclipse ide has this logged after i submit the form – SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found

    Any ideas?

    • saba wrote on 8 March, 2011, 11:31

      first u can check coding,sessionFactory fail means.u r not create session factory.crete session facrory and sessionfactory(hibernate.cfg.xml).the code is cretae database table row and ganerate primarykay and pojo class object vicevarsa.

  • Piyush wrote on 26 October, 2010, 16:14

    Thank u viral this is very good blog for information of hibernate and sturts.
    Good One….

  • JC wrote on 27 October, 2010, 7:29

    @Dani
    Many thanks for the comments on double add.

  • JC wrote on 27 October, 2010, 7:31

    Thank you for the straightforward tutorial. Found the solution to my hibernate-cfg.xml error. I placed it in the src folder instead of the resources folder and it worked fine.

  • JC wrote on 27 October, 2010, 7:34

    On the issue of the the list not being populated at the first run of the application, one could follow the suggestions pointed out.
    However, it may not always be the desired in a real application esp. if there are plenty of records already. One could just add a button for the user to initiate the listing or allowing a search for records.

  • Aneta wrote on 9 November, 2010, 22:56

    I need help, please! when I run the application with a jboss server, getting the error:

    18:41:58,305 ERROR [[jsp]] Servlet.service() para servlet jsp lanzó excepción
    java.lang.NoSuchMethodError: com.opensymphony.xwork2.util.ValueStack.findValue(Ljava/lang/String;Z)Ljava/lang/Object;
    at org.apache.struts2.components.Component.findValue(Component.java:255)
    at org.apache.struts2.components.ActionError.evaluateExtraParams(ActionError.java:75)

  • Jitendra wrote on 11 November, 2010, 15:38

    @Viral & @lupo– I am also facing the same error
    “java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity”
    when i tried to switch the application to oracle database. Please tell the solution.

  • Aneta wrote on 15 November, 2010, 14:00

    in my app add a contact run well, but don’t show the contact list below the form. I add all the jars, and i don’t know why don’t appears the LIST!! there are anybody who know this ??

  • Enkay wrote on 18 November, 2010, 20:12

    Thanks Viral for this nice tutorial… It’s short, simple and precisely cover every aspect required. I did face quite a few issues in the beginning (config issues etc…) but finally got it up and running. Thanks once again and appreciate your efforts :)

  • sonnt wrote on 24 November, 2010, 14:45

    when i run with Tomcat it has error:

    org.apache.jasper.JasperException: /index.jsp(12,0) The s:form tag declares that it accepts dynamic attributes but does not implement the required interface
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148)
    org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:777)
    org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1512)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2393)
    org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2399)
    org.apache.jasper.compiler.Node$Root.accept(Node.java:489)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
    org.apache.jasper.compiler.Validator.validate(Validator.java:1739)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:166)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:315)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:389)

    Help me please!
    thanks

  • ramkumar wrote on 9 December, 2010, 11:45

    can u telll how to integrate Struts +hibernate with spring

  • Teo wrote on 11 December, 2010, 21:44

    Hi,

    I face this problem. Can anyone tell me how to solve this?

    I have checked the database name, username and password. They are correct.

    00:39:33,762 WARN [SettingsFactory] Could not obtain connection metadata
    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)

    Thanks for your help.

    Regards,
    Teo.

    • saba wrote on 8 March, 2011, 12:19

      Hi
      u can change dileact name.and once check pojo class object name and data base table id.

    • Prasad Pednekar wrote on 6 April, 2011, 2:37

      I guess you have not included the mysql-connector jar. Check the lib directory. Also cross-check the values of the various properties in hibernate.cfg.xml

  • Jinesh Gopinathan wrote on 20 December, 2010, 14:01

    Nice Post. Well I would like to add one point.
    The class files are using annotations and while running the webapp for the first time it will generate an error “java.lang.NoClassDefFoundError: javax.persistence.Cacheable “. You have to add “hibernate-jpa-2.0-api-1.0.0.Final.jar” into the lib folder which will be available under “/lib/jpa directory in Hibernate distribution.”

  • Kaushik wrote on 22 December, 2010, 3:38

    Hi,

    Can you please let me know how to add validation to above example.

    Thanks

    Kaushik

  • Sunil wrote on 22 December, 2010, 16:14

    Hi All,
    When i run this one i got an error like There is no Action mapped for namespace / and action name index. any help pls………..

  • Naveen wrote on 28 January, 2011, 0:37

    Hi Viral,

    I’m getting following exception. Could you please correct me.

    Please reply me.

    Regards,

    Naveen

    javax.servlet.ServletException: Filter execution threw an exception
    root cause

    java.lang.NoClassDefFoundError: Could not initialize class net.viralpatel.contact.controller.ContactManager
    net.viralpatel.contact.view.ContactAction.(ContactAction.java:20)
    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)

  • David Jensen wrote on 30 January, 2011, 0:30

    Viral,
    Thanks for taking the time and effort to post this example. I, like most here am new to j2ee development and found your example very helpful in understanding the struts2-Spring-Hibernate MVC flow. On a side note, I ran into a few minor issues while setting it up and have tackled each other than the double add which I hope to solve by before calling it a day. I’ll (re)post with my findings maybe someone will find it useful.
    Much appreciated!
    David Jensen
    Minnesota, USA

  • David Jensen wrote on 30 January, 2011, 2:21

    Here’s what I did to prevent the double add action. Hope this helps.

    Filename: ContactAction.java

    public String execute() {
    /*if(null != contact) {
    linkController.add(getContact());
    }*/
    this.contactList = linkController.list();
    System.out.println(contactList);
    System.out.println(contactList.size());
    return SUCCESS;
    }

    Regards,
    David Jensen

    • Viral Patel wrote on 1 February, 2011, 19:42

      @David – Thanks for the code to avoid double add action invocation.

  • David Jensen wrote on 2 February, 2011, 11:51

    Viral,
    (My post turned out to be longer than i even expected, sorry in advance.)
    I’m hoping you can point me in the right direction with an error i’m getting. I’m reworking your example code for my log in page. Not sure if it matters but i created a new struts 2 Dynamic Web Project with Tomcat 7 and am using all the same jars i used in your Contact Manager tutorial. Basically i replaced 2 existing string fields with username & password and removed all others then reassigned the Long delete with a String delete, renamed package and jsp/java filenames with a variation of Login*. As a fist step i wanted to simply use a login to add, delete then figure out just a select which would validate username and password against MySQL 5.1.

    Here’s a snipit of the error log.

    Initial SessionFactory creation failed.org.hibernate.AnnotationException: No identifier specified for entity: com.crowriverheights.struts2.welcome.Login
    Feb 2, 2011 12:26:35 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet [default] in context with path [/crowriverheights] threw exception [Filter execution threw an exception] with root cause
    org.hibernate.AnnotationException: No identifier specified for entity: com.crowriverheights.struts2.welcome.Login

    HibernateUtil.java
    package com.crowriverheights.struts2.welcome;

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

    Is the error saying it can’t find my hibernate.cfg.xml file or that it found it but can’t read it?

    Again, sorry for the length of this post and any thoughts are very much appreciated.

    Thanks,
    David Jensen

  • David Jensen wrote on 5 February, 2011, 7:24

    Viral,
    I did a lot of reading (on your site and a book) and a lot of tinkering with the code and got it working. If i figure out how i did it I will post my results, maybe it will be helpful to others.

    Thanks again,
    David Jensen

  • smitha wrote on 21 February, 2011, 11:42

    Hi Viral,

    Thansks for the example.

    When i run with http://localhost:8082/StrutsHelloWorld/ it is displaying index page but when click on add button it giving me an error no resource found and when I run with http://localhost:8082/StrutsHelloWorld/index also i am getting same error

    could you please suggest where I am going wrong.

    Thanks
    Smitha

  • rajeshvimal wrote on 7 March, 2011, 17:35

    thanx a lot for the grate example…
    it helps me too..
    in the development of Struts2+hibernate3 application….
    thanx
    Rajesh

    • Viral Patel wrote on 7 March, 2011, 18:06

      @Rajeshvimal – Thanks a lot for the kind words :)

  • Stu McClure wrote on 23 March, 2011, 0:04

    Thanks Viral!! I liked the format you presented this example in. Very clear and concise. I had a fair amount of problems getting the right library versions to work together (that was the cause of the Filter error) but finally did (nothing new to using multiple frameworks :) ). I also used the code from David, thanks bud!

  • Swara wrote on 27 March, 2011, 5:05

    Thank a lotttt for detailed explanation, very clear and concise……gr8 work….useful for hibernate beginners….

  • Abdullah Wasi wrote on 29 March, 2011, 18:02

    Nice work !
    Thanks

  • roberto wrote on 15 April, 2011, 9:22

    Hi, I have some problems. I not find the libraries ejb3-persistence.jar, hibernate-annotations-3.2.0.ga.jar, hibernate-commons-annotations.jar, hibernate-core.jar, hsql.jar, log4j-1.2.15.jar,sfl4j-log12-1.4.2.jar.

    I download struts-2.2.1.1 and hibernate-distribution-3.6.3.Final-dist. But there are not this libraries.

    Can you help me? Where can i download this libraries? Thanks

  • Pushpak wrote on 15 April, 2011, 13:37

    I am trying to run this example in my tomcat 6.0, but It shows 404 exception at the start.

  • Ajmal wrote on 19 April, 2011, 15:40

    Hai Viral,
    Thanks for your simple application and detailed example .
    But when I am trying to run the application in tomcat 5.5 I got some errors like

    log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester.sax).
    log4j:WARN Please initialize the log4j system properly.

    Can you help me please…

  • arun mk wrote on 6 May, 2011, 9:31

    i tried the above example . but i add new contact that time i get this erroe

    type Exception report

    message

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

    exception

    java.lang.NullPointerException
    com.contact.action.ContactAction.add(ContactAction.java:34)

  • Sujan wrote on 10 May, 2011, 13:06

    nice article..very understandable and helpful…

  • Dipankar Roy wrote on 12 May, 2011, 17:41

    It really a great artical to help initial working on Struts.

  • Vivek wrote on 26 May, 2011, 13:34

    Hi, I have some problems.i got following problem.

    No result defined for action cms.UserAction and result input – action – file:/D:/eclipse-jee-galileo-M7-win32/eclipse/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Cms/WEB-INF/classes/struts.xml:54:73
    at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:350)
    at java.lang.Thread.run(Unknown Source)
    plz any body help me.
    thanks in advance.

  • Jijo wrote on 31 May, 2011, 15:08

    Hi Viral,

    This is a excellent example for a starter like me.

    I have successfully implemented hibernate to my struts 2 app following the same.

    However,I have faced few issues like

    1) After I enter the contact details thru my form and submit. The database is inserted with a new record but if I refresh the page again somehow the data is reinserted again,Since the same action is invoked.Kindly suggest some tips for handling such scenarios.

    2) How do I edit my data using the above example?

    appreciate your quick response.

    Regards,
    Jijo

  • alok wrote on 15 June, 2011, 15:11

    Hi,
    I am getting this error as mentioned below,could some one help me out.There are no errors in my entire program.

    HTTP Status 404 – /ContactManager/add

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

    type Status report

    message /ContactManager/add

    description The requested resource (/ContactManager/add) is not available.

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

    Apache Tomcat/6.0.32

  • newbie wrote on 20 July, 2011, 17:10

    Thanks for the example. It is very good. I have two questions. 1 how to delete a row based on some keys or where clause (no index id)? 2. How to select/update/delete joint table entries? Thanks.

  • shoaib wrote on 8 August, 2011, 12:02

    it’s really great article . plz specify from netbean.. i am using netbean 6.8 ..

  • Rishikant wrote on 8 August, 2011, 15:38

    Very good and easily understandable artical.

  • Prachi wrote on 17 August, 2011, 15:30

    Hi viral,
    Thanks for this simple and nice tutoial. I tried your tutorial,bt m not getting list below..
    so in add method, i called list.
    Now,
    when i add any contact then and then only m able to see list..
    bt i want it to remain stable.
    wot to do?

    • Viral Patel wrote on 17 August, 2011, 22:24

      @Prachi – Well I think I do not understand your issue! Do you mean that when the page is loaded first, you do not see any list of contacts in below table? And you see only when you add a contact?

  • Anupam wrote on 26 August, 2011, 17:39

    Hi Viral,
    I am using your example as the base of my project. It is almost complete and working perfectly. I am not using spring framework.
    Now, I have to implement Web Services in my project so that my resources can be accessed by outside world. I guess REST plugin is there for this purpose, but all the tutorials on net are based on Spring framework. Can you forward me to right direction to implement this.
    And thanks a lot for this example.

  • Mz wrote on 27 August, 2011, 11:03

    Hi,
    i have problems in the modification of the “index.jsp” , in the textfield i don’t undestand how important is the contact of name=contact.firstname in this exemple. I try to change it but it’s doesn’t work. I changed the name of my model class form contact to another name but still work. And if i change the terme “contact” in the jsp, i have compile problem..
    Please help..

    • Mz wrote on 27 August, 2011, 11:13

      what this contact means? thx u again

  • Mallikarjun P wrote on 10 September, 2011, 1:04

    hi.. the below error i got while m running in the tomcat server.. plz tel me the solutions. i have tried all the possibilities and paths.. but it is showing same error..,,

    thanks with regards..

    HTTP Status 404 – There is no Action mapped for namespace / and action name .

    type Status report

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

    description The requested resource (There is no Action mapped for namespace / and action name .) is not available.

    • shashikant wrote on 21 October, 2011, 11:37

      i also got the same error. can any body help me

      thanks

  • Divya wrote on 12 October, 2011, 20:55

    Hi Viral,

    The Tutorial is really cool. In my project I am using EJB3.0 integration with Hibernate and we are planning to publish it as a web Service. We are making use of Oracle Database. Can you please help me with this.

  • mylene wrote on 20 October, 2011, 16:19

    This article has helped me immensely! Just what I needed to learn Struts 2 and Hibernate with MySQL. Thanks! :)

  • shashikant wrote on 21 October, 2011, 11:31

    hey, this article is really very good, but can any body help me, After completing the project i am getting no errors but while run : http://localhost:8080/ContactManager/index

    i am getting an error 404- /ContactManager/index resourse is not available

    please reply me any body.

  • Son Nguyen wrote on 27 October, 2011, 10:38

    I used Jboss 6 and I got this issue. Any helps, pls

    12:37:37,787 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Parse: name=vfs:///D:/Development/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_6.0_Runtime_Server1319692714911/deploy/StrutsHelloWorld.war state=PreParse mode=Manual requiredState=Parse: org.jboss.deployers.spi.DeploymentException: Error creating managed object for vfs:///D:/Development/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_6.0_Runtime_Server1319692714911/deploy/StrutsHelloWorld.war
    at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) [:2.2.2.GA]
    Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: Caused by: org.xml.sax.SAXException: cvc-datatype-valid.1.2.1: ’2.2.3′ is not a valid value for ‘decimal’. @ vfs:///D:/Development/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_6.0_Runtime_Server1319692714911/deploy/StrutsHelloWorld.war/WEB-INF/lib/struts2-dojo-plugin-2.2.3.1.jar/META-INF/struts-dojo-tags.tld[6,37]
    at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.error(SaxJBossXBParser.java:416) [jbossxb.jar:2.0.3.GA]
    DEPLOYMENTS IN ERROR:
    Deployment “vfs:///D:/Development/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_6.0_Runtime_Server1319692714911/deploy/StrutsHelloWorld.war” is in error due to the following reason(s): org.xml.sax.SAXException: cvc-datatype-valid.1.2.1: ’2.2.3′ is not a valid value for ‘decimal’. @ vfs:///D:/Development/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_6.0_Runtime_Server1319692714911/deploy/StrutsHelloWorld.war/WEB-INF/lib/struts2-dojo-plugin-2.2.3.1.jar/META-INF/struts-dojo-tags.tld[6,37]

Leave a Reply

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

*