Struts 2 + Hibernate integration example

In Struts2, there are no official plugins to integrate the Hibernate framework. But, you can workaround with the following steps :

  1. Register a custom ServletContextListener.
  2. In the ServletContextListener class, initialize the Hibernate session and store it into the servlet context.
  3. In action class, get the Hibernate session from the servlet context, and perform the Hibernate task as normal.

See the relationship :


Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database 

In this tutorial, it shows a simple customer module (add and list function), developed in Struts 2, and perform the database operation with Hibernate. The integration part is using the above stated mechanism (store and retrieve the Hibernate session in the servlet context).

This workaround is very similar with the classic Struts 1.x and Hibernate integration, just the classic Struts 1.x is using the Struts’s plugins; While the Struts 2 is using the generic servlet listener.

1. Project structure

See this full project folder structure.

Struts 2 Hibernate integration example

2. MySQL table script

Create a customer table for the demonstration. Here’s the SQL table script.


DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3. Dependency

Get the Struts2, Hibernate and MySQL dependency libraries.


//...
	<!-- Struts 2 -->
	<dependency>
	        <groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.1.8</version>
        </dependency>

	<!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

	<!-- Hibernate core -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.7.ga</version>
	</dependency>

	<!-- Hibernate core library dependency start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>

	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>

	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
	<!-- Hibernate core library dependency end -->

	<!-- Hibernate query library dependency start -->
	<dependency>
		<groupId>antlr</groupId>
		<artifactId>antlr</artifactId>
		<version>2.7.7</version>
	</dependency>
	<!-- Hibernate query library dependency end -->
//...

4. Hibernate Stuffs

The Hibernate model and configuration stuffs.

Customer.java – Create a class for customer table.


package com.mkyong.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

	private Long customerId;
	private String name;
	private String address;
	private Date createdDate;

	//getter and setter methods
}

Customer.hbm.xml – Hibernate mapping file for customer.


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
	table="customer" catalog="mkyong">

        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

hibernate.cfg.xml – Hibernate database configuration file.


<?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="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">false</property>
    <mapping resource="com/mkyong/customer/hibernate/Customer.hbm.xml" />
  </session-factory>
</hibernate-configuration>

5. Hibernate ServletContextListener

Create a ServletContextListener, and initialize the Hibernate session and store it into the servlet context.

HibernateListener .java


package com.mkyong.listener;

import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateListener implements ServletContextListener{
 
    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;
 
    public static final String KEY_NAME = clazz.getName();

	public void contextDestroyed(ServletContextEvent event) {
	  //
	}
 
	public void contextInitialized(ServletContextEvent event) {
 
	 try { 
	        URL url = HibernateListener.class.getResource(path);
	        config = new Configuration().configure(url);
	        factory = config.buildSessionFactory();
	         
	        //save the Hibernate session factory into serlvet context
	        event.getServletContext().setAttribute(KEY_NAME, factory);
	  } catch (Exception e) {
	         System.out.println(e.getMessage());
	   }
	}
}

Register the listener in the web.xml file.
web.xml


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</display-name>
  
  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
	  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	</filter-class>
  </filter>
  
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <listener>
    <listener-class>
	  com.mkyong.listener.HibernateListener
    </listener-class>
  </listener>
 
</web-app>

6. Action

In Action class, get the Hibernate session from the servlet context and perform the Hibernate task as normal.

CustomerAction.java


package com.mkyong.customer.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.customer.model.Customer;
import com.mkyong.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
 
public class CustomerAction extends ActionSupport 
	implements ModelDriven{

	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
	
	public String execute() throws Exception {
		return SUCCESS;
	}

	public Object getModel() {
		return customer;
	}
	
	public List<Customer> getCustomerList() {
		return customerList;
	}

	public void setCustomerList(List<Customer> customerList) {
		this.customerList = customerList;
	}

	//save customer
	public String addCustomer() throws Exception{
		
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

		Session session = sessionFactory.openSession();

		//save it
		customer.setCreatedDate(new Date());
	 
		session.beginTransaction();
		session.save(customer);
		session.getTransaction().commit();
	 
		//reload the customer list
		customerList = null;
		customerList = session.createQuery("from Customer").list();
		
		return SUCCESS;
	
	}
	
	//list all customers
	public String listCustomer() throws Exception{
		
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

		Session session = sessionFactory.openSession();

		customerList = session.createQuery("from Customer").list();
		
		return SUCCESS;
	
	}	
}

7. JSP page

JSP page to add and list the customer.

customer.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 + Hibernate integration example</h1>

<h2>Add Customer</h2>
<s:form action="addCustomerAction" >
  <s:textfield name="name" label="Name" value="" />
  <s:textarea name="address" label="Address" value="" cols="50" rows="5" />
  <s:submit />
</s:form>

<h2>All Customers</h2>

<s:if test="customerList.size() > 0">
<table border="1px" cellpadding="8px">
	<tr>
		<th>Customer Id</th>
		<th>Name</th>
		<th>Address</th>
		<th>Created Date</th>
	</tr>
	<s:iterator value="customerList" status="userStatus">
		<tr>
			<td><s:property value="customerId" /></td>
			<td><s:property value="name" /></td>
			<td><s:property value="address" /></td>
			<td><s:date name="createdDate" format="dd/MM/yyyy" /></td>
		</tr>
	</s:iterator>
</table>
</s:if>
<br/>
<br/>

</body>
</html>

8. struts.xml

Link it all ~


<?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.devMode" value="true" />
 	
  <package name="default" namespace="/" extends="struts-default">
		
    <action name="addCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="addCustomer" >
       <result name="success">pages/customer.jsp</result>
    </action>
	
    <action name="listCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="listCustomer" >
        <result name="success">pages/customer.jsp</result>
    </action>		

  </package>	
</struts>

9. Demo

Access the customer module : http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 Hibernate Add Customer

Fill in the name and address fields, hits the submit button, the inserted customer details will be listed immediately.

Struts2 Hibernate List Customer

Reference

  1. Struts 2 + Hibernate integration with “Full Hibernate Plugin”
  2. ServletContextListener documentation
  3. Struts + Hibernate integration example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
cyberglad
Guest
cyberglad

change
org.hibernate
hibernate
3.2.7.ga with
org.hibernate
hibernate-entitymanager
3.5.5-Final

Otherwise your pom.xml won’t compile

Tharindu Madusanka Weeratunga
Guest
Tharindu Madusanka Weeratunga

I can’t build project it says,
Failed to execute goal on project Struts2Example: Could not resolve dependencies for project com.mkyong.common:Struts2Example:war:com.mkyong.common: Could not find artifact javax.transaction:jta:jar:1.0.1B in central (http://repo.maven.apache.org/maven2) -> [Help 1]

How can I resolve this.
I try it using netbeans

sanu
Guest
sanu

please post examples for two table one to mamy mapping example…..which include whole CRUD..

Ajay
Guest
Ajay

hi all i want to display getting database table into jsp page( using Hibernate-Version 3),,I try but i can get all value and print console only,,!!!!some one help me in this problem,,,or tell me what i have to do?

Thanks,

Dibyendu sarkar
Guest
Dibyendu sarkar

Dependency portion I am not able to understand can you please tell me, where to add those lines and for what.

venky
Guest
venky

Iam get this error when i start the server…..application is Struts2.1 with hibernate integration

can please send right answer

SEVERE: Exception sending context initialized event to listener instance of class org.apache.struts2.tiles.StrutsTilesListener
java.lang.NullPointerException
at org.apache.commons.digester.Digester.getXMLReader(Digester.java:1058)
at org.apache.commons.digester.Digester.parse(Digester.java:1887)
at org.apache.tiles.definition.digester.DigesterDefinitionsReader.read(DigesterDefinitionsReader.java:267)
at org.apache.tiles.definition.UrlDefinitionsFactory.readDefinitions(UrlDefinitionsFactory.java:286)
at org.apache.tiles.definition.UrlDefinitionsFactory.init(UrlDefinitionsFactory.java:130)
at org.apache.tiles.impl.BasicTilesContainer.initializeDefinitionsFactory(BasicTilesContainer.java:406)
at org.apache.tiles.impl.BasicTilesContainer.init(BasicTilesContainer.java:130)
at org.apache.tiles.factory.TilesContainerFactory.initializeContainer(TilesContainerFactory.java:232)
at org.apache.tiles.factory.TilesContainerFactory.createTilesContainer(TilesContainerFactory.java:198)
at org.apache.tiles.factory.TilesContainerFactory.createContainer(TilesContainerFactory.java:163)
at org.apache.tiles.web.startup.TilesListener.createContainer(TilesListener.java:90)
at org.apache.struts2.tiles.StrutsTilesListener.createContainer(StrutsTilesListener.java:68)
at org.apache.tiles.web.startup.TilesListener.contextInitialized(TilesListener.java:57)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Murat yorfun
Guest
Murat yorfun

Hello I m a new learning javaee & struts2. I dont know lib installation. Why didnt you zip file added? Why?

I find all internet but I dont find this “lib..”

Please share Your lib file and I want to be relax

Muthu
Guest
Muthu

The issue “com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.”

Can be resolved if we add the below dependency.

mysql
mysql-connector-java
5.1.24

Gaurav Dighe
Guest
Gaurav Dighe

Hello Sir,
I need tutorials for below:
1. Aware Interfaces – ApplicationAware, SessionAware, ParameterAware, ServletRequestAware and ResponseAware
2. Interceptors – param etc..

Regards,
Gaurav Dighe

adnen
Guest
adnen
Struts Problem Report Struts has detected an unhandled exception: Messages: No operations allowed after connection closed.Connection was implicitly closed due to underlying exception/error: ** BEGIN NESTED EXCEPTION ** com.mysql.jdbc.CommunicationsException MESSAGE: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Broken pipe STACKTRACE: java.net.SocketException: Broken pipe at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109) at java.net.SocketOutputStream.write(SocketOutputStream.java:153) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2739) at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2650) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1581) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695) at com.mysql.jdbc.Connection.execSQL(Connection.java:3026) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1137) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1231) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1808) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2228) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125) at org.hibernate.loader.Loader.list(Loader.java:2120) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at… Read more »
crp
Guest
crp
Hi MKYong , I am using Struts 2 – Hibernate3.0 in my application. I am facing following exception after few immediate database calls . Exception is as follow ,can you give me any suggestion : java.lang.NullPointerException WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:488) at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:725) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71)… Read more »
Orozco Hsu
Guest
Orozco Hsu

Please help me, more detail is better, thanks in advance !
I’ve tried many times but I still don’t know how to resolve this error wihen doing marven

the error is:

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

I googled many sites, even I reference your another post “manually install jar to marven”, but it still shows up “Failed to load class …..”

kirokw san
Guest
kirokw san

What should I do to run it on glasfish or tomcat? Thanks in advance!

tom
Guest
tom

How would I go about setting up struts2 xml form validation on the input boxes in this example?

Shaswat
Guest
Shaswat

Hi,
When will listCustomer() method in CustomerAction will be called ????

Anshul
Guest
Anshul

hi mkyong,

I did it bymyself :)

Thanks

Anshul
Guest
Anshul

hi mkyong,

i am getting

Struts has detected an unhandled exception:
Messages:
File: com/mkyong/customer/action/CustomerAction.java
Line number: 71
Stacktraces
java.lang.NullPointerException

line no 71 is SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY_NAME);

It throws null and says

Note: An exception occurred while getting the Javadoc. See log for details.

i can see in the .classpath the values as

which is not there in my system as its an ubuntu system.

Please tell me the remedy for this

Thnaks
Regards
Anshul

Rajesh K
Guest
Rajesh K

hi even i got the same problem..!! let me knw if u solved the issue..!!

File: com/mkyong/customer/action/CustomerAction.java
Line number: 71
Stacktraces
java.lang.NullPointerException

line no 71 is SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY_NAME);

Anshul
Guest
Anshul
hi, I tried to run the example but got the following error: Struts Problem Report Struts has detected an unhandled exception: Messages: File: com/mkyong/customer/action/CustomerAction.java Line number: 71 Stacktraces java.lang.NullPointerException com.mkyong.customer.action.CustomerAction.listCustomer(CustomerAction.java:71) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) 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.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:662) You are seeing this… Read more »
Janith
Guest
Janith

I had same issue.By changing Hibernate version it worked.
I change pom.xml

org.hibernate
hibernate-entitymanager
4.1.9.Final

tom
Guest
tom
Mkyong Can you help? If I launch the page directly from http://localhost:8080/Struts2Example/pages/customer.jsp I see the following error in the logs: WARNING: Caught an exception while evaluating expression ‘customerList.size() > 0’ against value stack java.lang.NullPointerException: target is null for method size Upon trying to submit data I receive the following Hibernate error org.hibernate.PropertyValueException: not-null property references a null or transient value: com.paul.customer.model.Customer.createdDate But if i access the project as the example suggests http://localhost:8080/Struts2Example/listCustomerAction.action I see the following struts error report about the Hibernate sql submitted Struts Problem Report Struts has detected an unhandled exception: Messages: Unknown column ‘customer0_.customerId’ in ‘field list’… Read more »
tom
Guest
tom

The instructions don’t go into any depth on how to create the required ServletContextListener and the referenced link doesnt work

http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html

Can you please out line the steps required in this process – sorry if its so simple it doesnt even need to be explained.

tom
Guest
tom

I renamed the classes now I receive this error, but I can’t find where its referenced?

SEVERE: Error configuring application listener of class com.tom.listener.HibernateListener
java.lang.NoClassDefFoundError: com/tom/listener/HibernateListener (wrong name: com/mkyong/listener/HibernateListener)

Krish
Guest
Krish
HI i got this error, I just download this Struts 2 + Hibernate integration example and i placed all dependencies. but i got this error , give me suggestions please to fix this issue SEVERE: Error configuring application listener of class com.mkyong.listener.HibernateListener java.lang.NoClassDefFoundError: Lorg/hibernate/cfg/Configuration; at java.lang.Class.getDeclaredFields0(Native Method) at java.lang.Class.privateGetDeclaredFields(Unknown Source) at java.lang.Class.getDeclaredFields(Unknown Source) at org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(DefaultInstanceManager.java:276) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:143) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1688) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1533) ... 16 more Mar 13, 2012 3:49:19 PM… Read more »
PhongNQ
Guest
PhongNQ

I got the same errors. May I help you to fix this..
I think it problems in .classpath and tomcat lib but don’t know how to fix it.

tom
Guest
tom

I’m getting the following error from eclipse
The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files

Does the servlet-api-2.5.jar need to be referenced in the library?

Ryan
Guest
Ryan

any answers on this. im also getting the same eclipse error

Sree Rama Konduri
Guest
Sree Rama Konduri

javax.servlet
servlet-api
2.5

add this to your pom file , that will fix the issue

tom
Guest
tom

Why is eclipse in linux show me this?
Project ‘Struts2Example’ is missing required library: ‘C:/Program Files/Java/jdk1.6.0_13/lib/tools.jar’

Anjani Kumar Gupta
Guest
Anjani Kumar Gupta

Need to add tools.jar from jdk in build path

tom
Guest
tom

eclipse is giving me this strange missing library requirement.. not surprising as im in linux.

Project ‘Struts2Example’ is missing required library: ‘C:/Program Files/Java/jdk1.6.0_13/lib/tools.jar’

Narasappa
Guest
Narasappa

hi I am Narasappa from bangalore.Currently I am working on Struts 2.0.I need help in displaying image Stored in mysql Using Struts 2.0.please do the the neewd full

Ali Syed
Guest
Ali Syed

Hi,

Thanks for the tutorial, I believe we need to make the below changes to pom.xml for the example to work on Tomcat 7 and MySQl5.5

Option 1 – Replace cglib 2.2 with cglib-nodep 2.2.2 (contains asm dependencies)

 
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib-nodep</artifactId>
    <version>2.2.2</version>
</dependency>	

Option 2 – Keep cglib 2.2 and add asm dependency

 
<dependency>
	<groupId>cglib</groupId>
	<artifactId>cglib</artifactId>
	<version>2.2</version>
</dependency>
<dependency>
	<groupId>asm</groupId>
	<artifactId>asm</artifactId>
	<version>3.1</version>
</dependency>	
Guillermo
Guest
Guillermo

Thxs!!!!!

Ramon
Guest
Ramon

Thanks, that was the issue with the NullPointerException!

santosh limbu
Guest
santosh limbu

i am in love with all your work…..amazing work …

Java Guru
Guest
Java Guru

Thanks a lot Kong, that post is very good and helpful for me.

Xin
Guest
Xin

Dear Mkyong,

I got the following error, would you please give a hint?

java.lang.NoClassDefFoundError: javax/transaction/Synchronization
org.hibernate.impl.SessionImpl.(SessionImpl.java:214)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:520)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:544)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:552)
com.mkyong.customer.action.CustomerAction.addUser(CustomerAction.java:46)

Thanks in advance,

Xin

Xin
Guest
Xin

One info from mkyong’s site is “This is caused by missing of the “jta.jar“, usually happened in Hibernate transaction development.” But I do have jta-1.0.1B.jar in path.

Xin

Xin
Guest
Xin

Hi Mkyong,

Thank you for reply. It didn’t work even jta-1.0.1B.jar (manually downloaded) was added to path. It finally worked when it was moved to .m2 folder.

Also, it seems that the jar for ServletActionContext is missing. javax.servlet-5.1.12 was downloaded and added to path. is it right version?

I’m also wondering that if you have any comment about this post, here is the url:
http://stackoverflow.com/questions/5687886/storing-hibernate-sessionfactory-with-struts

“I notice the example doesn’t seem to ever close the SessionFactory so I added some code in the contextDestroyed. Was this necessary?”

Thanks for help,

Xin