Monday, July 02, 2007

struts2 + spring + hibernate

(If u don't how struts2+spring works, see struts2+spring workflow)

What i'm trying do to here:
i have a table named "User" in our database.
now i want to build a web-application using struts2+spring+hibernate
1. to add new user to database and
2. to log in to home page for existing user.

Download sourcecodes

Files (java/xml) i'll create for this:

1. "User" table in database.

2. User.java:
which will be mapped with that "User" table.
3. User.hbm.xml:
that maps User table with User.java.
4. IUserDao.java:
interface for data access object.
5. UserDAOHibernateImpl.java:
which implements IUserDao.java
6. IUserService.java:
interface for service
7. UserServiceImpl.java:
which implements IUserService
8. UserAction.java:
action class for struts2
9. applicationContext.xml:
Register your objects via the Spring configuration.
all the above files and data source will be configured here.
10. struts.xml:
its the configuration file for struts2 (which was struts-config.xml for struts1)
11. output *.jsp files, i've used 3 here:
11.i) addUser.jsp: to add new user in DB
11.ii) login.jsp: to log in existing user
11.iii) hello.jsp: says hello to the user after successful log in.
12. xml files for validation
13. and good old web.xml

jar files we need are same as this example

so now.......Ready... Set... GO!

1.Let, database used is mysql. database name ExampleDB and table name User.


create database ExampleDB;
use ExampleDB;
create table User(
name varchar(20),
id
varchar(20) not null primary key
);





2. write the web.xml file:

In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests.

If you don't know how to write web.xml for struts2, see web.xml

In most cases, we can simply use web.xml for struts2-blank template. we just need to add the following lines to configure the Spring listener.

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener

</listener-class>
</listener>



Everything else is same as any other web.xml for struts2.

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="example" version="2.4"
xmlns=
"http://java.sun.com/xml/ns/j2ee"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>


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

<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener

</listener-class>
</listener>

</web-app>





3.write User.java file that will be used to map the User table.

package com.example.user; 

public class User {

private String id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {

this.name = name;
}
/** * @return Returns the userId. */

public String getId() {
return id;
}

/** * @param userId The userId to set. */
public void setId(String userId) {
this.id = userId;
}

}






4.Now maps the database table with .java file. To do this, write the mapping file, User.hbm.xml :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >


<!--Maps User.java class with User
database table -->


<hibernate-mapping>
<class name="com.example.user.User"

table="User">


<id name="id" column="id" >
<generator class="assigned" />

</id>
<!--
id tag represents the primary key of
database table generator class defines
how key will be generated.
Here we've choose "assigned", that is key will be
assigned before insert.
Other generator classes are:
1.native
2.increment : auto increment the key value
-->


<property name="name" column="name" />

<!--
property tag maps columns other than
the primary key column.
-->


</class>
</hibernate-mapping>



Put all your *.hbm.xml files in com/example/user/hbm folder.

5.Write the Data Access Object that would be used to access database using hibernate.
At first we would write the interface : IUserDao.java

package com.example.user ; 
public interface IUserDao {
public String addUser(User user);
public User findUserById(final String Id);


}

//Now write UserDAOHibernateImpl.java :

package com.example.user;
import org.springframework.orm.
hibernate3.HibernateTemplate;

public class UserDAOHibernateImpl
implements IUserDao
extends HibernateDaoSupport
{


public String addUser(User user){
String success;
try{
getHibernateTemplate().save(user);
success="Welcome !";
}
catch(Exception e){
success="Sorry, user cannot be added";
}
return success;
}

public User findUserById(final String id){

return (User)

getHibernateTemplate().get(User.class, id);
}

}






getHibernateTemplate().save(user) would insert user into the User database table
we've used HibernateTemplate because it provides easy method to do basic queries and also it is thread safe.
get method will return the user object with given id if such an user existed, otherwise null will be returned.

6. Write the service class (it would seem a little redundant at first, but it's the best practice to provide service layer between action and dao class).
Usually database transaction management is applied on this layer.
//Interface for service class:

package com.example.user;

public interface IUserService {
public String add(User user);
public User findById(final String Id);

}

//Service class: UserServiceImpl.java

package com.example.user;
public class UserServiceImpl implements IUserService{

private IUserDao userDao;

public IUserDao getUserDao() {
return userDao;
}
public void setUserDao(IUserDao userDao) {

//userDao will be set by applicationContext.xml

this.userDao = userDao;
}

public String add(User user){
String result=userDao.addUser(user);
return result;
}
public User findById(String Id){
User user=userDao.findUserById(Id);
return user;
}

}





7.At last, now write the action class: UserAction.java
Here our action class will
1.take the user id
2.retrieve user name from database
3.and say " Hello <user name>"
4.add new user

package com.example.user; 

import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext ;


public class UserAction {
private IUserService userService;
private User user;
private String id;
private String name;

/** * Constructor * @param userService */
public UserAction(IUserService userService)
{

this.userService=userService;

// will be set by applicationContext.xml
}
public String execute() {
this.user=

(User)userService.findById(this.id);
String result;
if(user==null){

// returns error if user doesn't exist.

result="User id does not exist";
ActionContext.getContext().
getSession().

put("result", result);
return Action.ERROR;
}
else {
result="";
ActionContext.getContext().
getSession().
put("user", user);

// puts user object in session
return Action.SUCCESS;
}
}
public String signup(){
return Action.SUCCESS;
}
public String addUser(){
String result;
this.user=

(User)userService.findById(id);
if(user==null){
user=new User();
user.setId(this.id);
user.setName(this.name);
result=userService.add (user);
ActionContext.getContext().
getSession().
put("user", user);
}
else{
result="Id already used,
Choose another Id"
;
ActionContext.getContext().
getSession().
put("result",result);

return Action.ERROR;
}
ActionContext.getContext().
getSession().
put("result", result);
return Action.SUCCESS;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}



8.Write the jsp files: we will use 3 jsps here
1.login.jsp: take the id from user
2.hello.jsp: say hello
3.addUser.jsp: add a user



login.jsp:
<%@ taglib prefix="s" uri="/struts-tags"%>

<html >
<head>
<title>Log in</title>
</head>
<body>
<h2><s:property value="#session.result"/></h2>
<s:form action="SignIn" validate="true">
<s:textfield label="User Id" name="id" required="true"/>
<s:submit value="Login" />
</s:form>
<a href=" <s:url action="SignUp"/> "> Sign Up As A New User </a>
</body>

</html>
---------------------------------------------------------------
hello.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html >
<head>
<title>Hello</title>
</head>
<body>
<s:if test="#session.user!=null">
<h2>Hello <s:property value="#session.user.name"/></h2>
</s:if>
</body>

</html>
--------------------------------------------------------------------
addUser.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html >
<head>
<title>Sign Up</title>
</head>
<body>
<s:property value="#session.result"/></h2>
<s:form action="add" validate="true">
<s:textfield label="User Name " name="name" required="true"/>
<s:textfield label="User Id" name="id" required="true"/>
<s:submit value="Submit"/>
</s:form>
</body>

</html>





9. Write the applicationContext.xml file:

<?xml version=" 1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">


<!--
- Application context definition
-->
<beans>
<!-- ========================= RESOURCE DEFINITIONS ========================= -->

<!-- Creating a data source connection pool-->

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource ">


<property name="driverClassName">

<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/ExampleDB</value>

</property>
<!-- Provide username and password for mysql -->
<property name="username" value="root"/>
<property name="password" value=""/>



</bean>


<!-- Hibernate SessionFactory -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">


<property name="dataSource"><ref bean="dataSource"/></property>
<property name="mappingDirectoryLocations">
<list>

<value>classpath:/com/example/user/hbm</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">

org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- show the sql command in console -->
</props>
</property>

</bean>



<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

<!--
Data access object: Hibernate implementation.
-->


<!-- with transaction -->
<bean id="hibernateTemplate"

class="org.springframework.orm.hibernate3.HibernateTemplate">

<property name="sessionFactory">
<ref bean="sessionFactory"/>

</property>
</bean>

<bean id="UserDaoImpl" class="com.example.user.UserDAOHibernateImpl">
<property name="hibernateTemplate">

<ref bean="hibernateTemplate"/>
</property>
<!-- set HibernateTemplate in UserDAOHibernateImpl.java class-->
</bean>

<!--
Defination of service targets
-->

<bean id="UserServiceTarget"

class="com.example.user.UserServiceImpl">

<property name="userDao">
<ref bean="UserDaoImpl"/>

</property>
<!-- set IUserDao in UserServiceImpl.java class-->
</bean>


<!--
Definition of Transaction Manager
-->

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">


<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!--
Base service object
-->


<bean id="Service"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">

<property name="transactionManager">

<ref bean="transactionManager"/>
</property>

<property name="transactionAttributes">
<props>


<prop key="add">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<!-- specifies the methods on which transaction management will be applied-->

</props>
</property>
</bean>

<!--
Children service objects using base service and service
targets
-->


<bean id="UserService" parent="Service">

<property name="target">
<ref bean="UserServiceTarget"/>
</property>

</bean>


<!--
Definition of Action objects
-->


<bean id="userAction"
class=" com.example.user.UserAction" singleton="false">

<constructor-arg>

<ref bean="UserService"/>
</constructor-arg>
<!-- set IUserService in UserAction.java's constructor-->
</bean>

</beans>




syntax highlighted by Code2HTML, v. 0.9.1


10. Last step :) now, write the struts.xml file:


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

<package name="user" extends="struts-default">


<action name="SignIn" method="execute" class="userAction" >
<result>/hello.jsp</result>

<result name="error">/login.jsp</result>
</action>
<action name="SignUp" method="signup" class="userAction">

<result>/addUser.jsp</result>
</action>

<action name="add" method="addUser" class="userAction">

<result>/hello.jsp</result>
<result name="error">/addUser.jsp</result>
</action>

</package>

</struts>



syntax highlighted by Code2HTML, v. 0.9.1


------------------------------------------------------------------------------------------------
And here's the validation file, just save it under the same folder as the action.
filename should be <action-classname>-<action-name>-validation.xml
For login action, validation filename would be UserAction-SignIn-validation.xml


<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">


<!--
Validation rules for sign in action
-->

<validators>
<field name="id">
<field-validator type="requiredstring">
<message>You must enter user id</message>

</field-validator>
</field>
</validators>



syntax highlighted by Code2HTML, v. 0.9.1



--
Sheetal

39 comments:

Anonymous said...

Hi,

can you tell me what are the libraries and the versions that you have used in this example??

I have tried to run the application proposed at:

http://struts.apache.org/2.0.8/docs/struts-2-spring-2-jpa-ajax.html

but, it didn't work..Surely beacuse
i've missed some libraries again...

Can you help me?

Thank you a lot

Anonymous said...

Hi,

i've tried your application, following your steps. I've obtained this error:


GRAVE: Exception sending context initialized event to listener instance of class org.springframework.web.context.
ContextLoaderListener
org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]
: Invocation of init method failed;
nested exception is java.io.FileNotFoundException: class path resource [com/example/hbm/user] cannot be resolved to URL because it does not
exist
Caused by: java.io.FileNotFoundException: class path resource [com/example/hbm/user] cannot be resolved to URL because it does not
exist
at org.springframework.core.io.
ClassPathResource.getURL
(ClassPathResource.java:155)
at org.springframework.core.io.
ClassPathResource.getFile
(ClassPathResource.java:167)
at org.springframework.orm.hibernate3.
LocalSessionFactoryBean.
buildSessionFactory(
LocalSessionFactoryBean.java:678)
at org.springframework.orm.
hibernate3.AbstractSessionFactoryBean.
afterPropertiesSet
(AbstractSessionFactoryBean.java:134)
at org.springframework.beans.
factory.support.
AbstractAutowireCapableBeanFactory.
invokeInitMethods
(AbstractAutowireCapableBeanFactory.
java:1201)
at org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
initializeBean(AbstractAutowireCapableBeanFactory.
java:1171)
at org.springframework.beans.
factory.support.
AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.
java:425)
at org.springframework.beans.factory.support.
AbstractBeanFactory$1.
getObject(AbstractBeanFactory.
java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.
factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.
factory.support.
AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.
factory.support.
DefaultListableBeanFactory.
preInstantiateSingletons
(DefaultListableBeanFactory.
java:284)
at org.springframework.context.
support.AbstractApplicationContext.
refresh(AbstractApplicationContext.
java:352)
at org.springframework.web.context.
ContextLoader.
createWebApplicationContext
(ContextLoader.java:244)
at org.springframework.web.context.
ContextLoader.
initWebApplicationContext(
ContextLoader.java:187)
at org.springframework.web.
context.ContextLoaderListener.
contextInitialized
(ContextLoaderListener.java:49)
at org.apache.catalina.core.
StandardContext.listenerStart
(StandardContext.java:3827)
at org.apache.catalina.core.
StandardContext.start(
StandardContext.java:4336)
at org.apache.catalina.core.
ContainerBase.addChildInternal
(ContainerBase.java:760)
at org.apache.catalina.core.
ContainerBase.addChild(
ContainerBase.java:740)
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:120)
at org.apache.catalina.core.
ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.
ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.
StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.
StandardService.start(StandardService.java:448)
at org.apache.catalina.core.
StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
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)
13-lug-2007 15.17.20 org.apache.catalina.core.
StandardContext start
GRAVE: Error listenerStart
13-lug-2007 15.17.20 org.apache.catalina.core.StandardContext start
GRAVE: Context [/Strut2_Spring2_Hibernate3] startup failed due to previous errors
13-lug-2007 15.17.20 org.apache.catalina.core.
ApplicationContext log


I really thank you in advance
any type of help.

LucaLuca

sheetal said...

sorry for late reply.
ur main exception is
nested exception is java.io.FileNotFoundException: class path resource [com/example/hbm/user] cannot be resolved to URL because it does not
exist

u have to put User.hbm.xml file in com/example/hbm/user folder.

sheetal said...

i have used exactly same libraries specified in http://struts.apache.org/2.0.8/docs/struts-2-spring-2-jpa-ajax.html

Anonymous said...

Hi,

I've moved the class as you told me, and it worked!!

Thank you a lot! I really appreciate your help.

Bye

sheetal said...
This comment has been removed by the author.
sheetal said...

actually i'm a newbie in these technologies and its really nice to know my codes do work !!! :)
thank u too.

Anonymous said...

Hi,

I'm a newbie too..now that your example has worked, i'm trying to implement the:

http://struts.apache.org/2.0.8/docs/struts-2-spring-2-jpa-ajax.html

But i have some problems..
Have you ever tried that?

Thank you (again..)!

sheetal said...

no, i've never tried to run that ..... can u paste the exceptions here?

Anonymous said...

Context initialization failed
org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'org.springframework.transaction.
interceptor.TransactionAttributeSourceAdvisor': Cannot create inner bean '(inner
bean)' of type [org.springframework.transaction.
interceptor.TransactionInterceptor]
while setting bean property
'transactionInterceptor'; nested
exception is org.springframework.beans.
factory.BeanCreationException:
Error creating bean with name
'(inner bean)': Cannot resolve
reference to bean
'transactionManager' while setting
bean property 'transactionManager';
nested exception is
org.springframework.beans.factory.
BeanCreationException:
Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]:
Cannot resolve reference to bean
'entityManagerFactory' while
setting bean property 'entityManagerFactory'; nested
exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in
ServletContext resource [/WEB-INF/applicationContext.xml]:
Invocation of init method failed;
nested exception is java.lang.NoClassDefFoundError:
org/hibernate/MappingNotFoundException

Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference
to bean 'transactionManager'
while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]:
Cannot resolve reference to bean
'entityManagerFactory' while
setting bean property
'entityManagerFactory'; nested
exception is org.springframework.beans.
factory.BeanCreationException:

Error creating bean with name 'entityManagerFactory' defined in
ServletContext resource [/WEB-INF/applicationContext.xml]:
Invocation of init method failed;
nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/MappingNotFoundException

Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/
MappingNotFoundException

Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/MappingNotFoundException

Caused by: java.lang.NoClassDefFoundError: org/hibernate/
MappingNotFoundException
at org.hibernate.ejb.
HibernatePersistence.
createContainerEntityManagerFactory
(HibernatePersistence.java:125)
at org.springframework.orm.jpa.
LocalContainerEntityManagerFactoryBean.
createNativeEntityManagerFactory
(LocalContainerEntityManagerFactory
Bean.java:218)
at org.springframework.orm.jpa.
AbstractEntityManagerFactoryBean.
afterPropertiesSet(AbstractEntity
ManagerFactoryBean.java:251)
at org.springframework.beans.
factory.support.
AbstractAutowireCapableBeanFactory.
invokeInitMethods
(AbstractAutowireCapableBeanFactory
.java:1201)
at org.springframework.beans.factory.
support.AbstractAutowireCapable
BeanFactory.initializeBean(
AbstractAutowireCapableBeanFactory.
java:1171)
at org.springframework.beans.
factory.support.AbstractAutowire
CapableBeanFactory.createBean
(AbstractAutowireCapableBeanFactory
.java:425)
at org.springframework.beans.factory.
support.AbstractBeanFactory$1.
getObject(AbstractBeanFactory.
java:251)
at org.springframework.beans.factory.
support.DefaultSingletonBean
Registry.getSingleton(
DefaultSingletonBeanRegistry.
java:156)
at org.springframework.beans.
factory.support.
AbstractBeanFactory.
getBean(AbstractBeanFactory.
java:248)
at org.springframework.beans.
factory.support.
AbstractBeanFactory.
getBean(AbstractBeanFactory.
java:160)
at org.springframework.beans.
factory.support.BeanDefinition
ValueResolver.resolveReference
(BeanDefinitionValueResolver.java:261)
at org.springframework.beans.
factory.support.BeanDefinitionValue
Resolver.resolveValueIfNecessary
(BeanDefinitionValueResolver.
java:109)
at org.springframework.beans.
factory.support.
AbstractAutowireCapableBeanFactory.
applyPropertyValues(
AbstractAutowireCapableBean
Factory.java:1099)
at org.springframework.beans.
factory.support.
AbstractAutowireCapableBeanFactory.
populateBean(AbstractAutowire
CapableBeanFactory.java:861)
at org.springframework.beans.
factory.support.AbstractAutowire
CapableBeanFactory.createBean
(AbstractAutowireCapableBean
Factory.java:421)
at org.springframework.beans.
factory.support.
AbstractBeanFactory$1.
getObject(AbstractBeanFactory.
java:251)
at
org.springframework.beans.
factory.support.
DefaultSingletonBeanRegistry.
getSingleton(
DefaultSingletonBeanRegistry.
java:156)
at org.springframework.beans.
factory.support.
AbstractBeanFactory.getBean
(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:261)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:109)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:215)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:87)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:96)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:83)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:66)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:312)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1180)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:733)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:511)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:337)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4336)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
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:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
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)
16-lug-2007 10.54.57 org.apache.catalina.core.StandardContext listenerStart
GRAVE: Exception sending context initialized event to listener instance of class
org.springframework.web.context.
ContextLoaderListener
org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'org.springframework.transaction.
interceptor.
TransactionAttributeSourceAdvisor':
Cannot create inner bean '(inner bean)' of type [org.springframework.transaction.
interceptor.TransactionInterceptor]
while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference
to bean 'transactionManager' while
setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/MappingNotFoundException
Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/MappingNotFound
Exception
Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/
MappingNotFoundException
Caused by: org.springframework.beans.factory.
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/
MappingNotFoundException
Caused by: java.lang.NoClassDefFoundError:
org/hibernate/
MappingNotFoundException
at org.hibernate.ejb.
HibernatePersistence.
createContainerEntityManager
Factory(HibernatePersistence.
java:125)
at org.springframework.orm.jpa.
LocalContainerEntity
ManagerFactoryBean.
createNativeEntityManagerFactory
(LocalContainerEntityManager
FactoryBean.java:218)
at org.springframework.orm.jpa.
AbstractEntityManagerFactoryBean.
afterPropertiesSet
(AbstractEntityManagerFactoryBean.
java:251)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1201)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1171)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:261)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:109)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:261)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:109)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:215)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:861)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:87)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:96)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:83)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:66)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:312)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1180)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:733)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:511)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:337)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4336)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
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:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
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)

Anonymous said...

Thank you in advance!

sheetal said...

one thing that could be a prb....i'm not sure though

in datasource bean in ur applicationContext.xml
try replacing
property name="url" value="jdbc:mysql://localhost/test"
with
property name="url" value="jdbc:mysql://localhost/quickstart"

Anonymous said...

i've changed it yet... I think it could be a problem of Hibernate mapping...but i can't understand what is wrong.. And, by google searches, it seems that nobody has tried this example...

however don't worry..I thank you for the time you're spending with me..

sheetal said...

hey, today i've run struts2+spring+jpa code without any exception.
all i've to change were datasource bean's username, password and database name.
i think u've done some very silly mistake like placing wrong files in wrong folder in ur war file.

sheetal said...

oh that application was applicable for struts-2.0.3 or greater versions. what was ur struts2 version?

sheetal said...

another thing struts2-api.jar is now deprecated, u don't have to use that

sheetal said...

some changes :
---------------------------------
in the applicationContext.xml ---

< bean id="userAction"
class=" com.example.user.UserAction"
singleton="false" >
.......
---------------------------------

all the beans defined in applicationContext.xml is singleton by-default,but action classes in struts2 shouldn't be singleton... thats why we should add singleton="false"....thanks a lot to sajid bhai :).

and another thing, u can use interceptor for login ... u'll find a sample in http://www.vitarara.org/cms/struts_2_cookbook/
creating_a_login_interceptor

Wana said...
This comment has been removed by the author.
Anonymous said...

Hi,

I'm tried to run application but I have problem about JDBC.

ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/SshTest]] - Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource ] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Caused by:
java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource

Can you help me please?

Thanks for help...

sheetal said...

sorry for late reply... i think u r missing jar file that contains DriverManagerDataSource class. include spring-jdbc.jar, spring.jar

Rajputro said...

mashallah

Anonymous said...

Hi,

I've tried both this tutorial the one on the apache site(http://cwiki.apache.org/WW/struts-2-spring-2-jpa-ajax.html) and with both i get this error when tomcat is starting:

05-Oct-2007 15:12:04 org.apache.struts2.dispatcher.FilterDispatcher doFilter
SEVERE: error getting ActionMapping
java.lang.NullPointerException
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

i've debugged and its true actionMapper is null but i don't know why

any ideas?

cheers in advance

sheetal said...

hello anonymous, as far i know, the ActionMapper may return null if no action invocation request matches.

may be u have any typo in any jsp page s:form action="your-action-name"..
and in struts.xml
action name="your-action-name"
this two name must be same.

Anonymous said...

Hi,
I have followed all the steps as u have written in eclipse.But it fails to reach login page.It gives the following error.
HTTP Status 404 - /struts2-blank-2.0.11/

And in console there is no exception fired.

I am not getting where I am making mistake....???

Is there Ne problem with spring listener....am not using Maven(As working with eclipse)

sheetal said...

hello anonymous,
sorry for late reply.

I have found the problem........its a very very silly and very very unusual one.

It occured because context loader failed to parse the .hbm.xml file.

& this happened because i've used an extra newline in

< !DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

:D

just write
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
in one single line & your error will disappear.

sheetal said...

I've included source codes now. You can download it from http://sheetal57.googlepages.com/ExampleStruts2SpringHibernate.zip

Anonymous said...

Hello,
I have followed all the steps which u have written but it cannot able to start Tomcat server giving following error.

" Server Tomcat v5.5 Server at localhost failed to start. "

As no any port is being used by any other system.

Anonymous said...

Hi,
Added all files as given but still gives following error..

SEVERE: Error listenerStart
Mar 14, 2008 4:58:31 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/struts2_spring_hibernate] startup failed due to previous errors

I m working with Eclipse

sheetal said...

hmm, I've run the application without any problem.
listener error could happen for a number of reasons. May be for applicationContext parsing error or missing any dependent jar.
Best way to find listener error is by adding log.

Hope this would help :).

Truong said...

Hi,

I have tried and I've obtained the following error:
Could you help me please?


2008/04/28 19:03:56 org.apache.catalina.core.StandardContext listenerStart
致命的: クラス org.springframework.web.context.ContextLoaderListener のリスナインスタンスにコンテキスト初期化イベントを送信中の例外です
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/context/CurrentSessionContext
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:471)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:217)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
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.start(ContainerBase.java:1045)
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:585)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/context/CurrentSessionContext
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1817)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:872)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1325)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.class$(LocalSessionFactoryBean.java:175)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:555)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1367)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1333)
... 30 more
2008/04/28 19:03:56 org.apache.catalina.core.StandardContext start
致命的: Error listenerStart

Anonymous said...

I'm a newbie with these tech. when I deploy example in your blog and I meet this error.

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserService' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'taget' of bean class [org.springframework.transaction.interceptor.TransactionProxyFactoryBean]: Bean property 'taget' is not writable or has an invalid setter method. Did you mean 'target'?
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'taget' of bean class [org.springframework.transaction.interceptor.TransactionProxyFactoryBean]: Bean property 'taget' is not writable or has an invalid setter method. Did you mean 'target'?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:793)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:645)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:78)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:862)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:424)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:284)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
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:578)
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)
Sep 29, 2008 10:43:44 AM org.apache.catalina.core.StandardContext start

Can you help me to handle this problem. I thanks you very much

fromJapan said...

Remove **/User.hbm.xml.

/WEB-INF/applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=
"
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
"
>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!--========================= RESOURCE DEFINITIONS=========================-->
<!-- Creating a data source connection pool-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource ">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ExampleDB"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!--========================= BUSINESS OBJECT DEFINITIONS=========================-->
<bean id="UserDaoImpl" class="com.example.user.UserDAOHibernateImpl"/>
<bean id="UserService" class="com.example.user.UserServiceImpl">
<property name="userDao">
<ref bean="UserDaoImpl"/>
</property>
</bean>
<bean id="userAction" class=" com.example.user.UserAction" scope="prototype">
<constructor-arg>
<ref bean="UserService"/>
</constructor-arg>
</bean>
</beans>

[classpass]/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="sample" transaction-type="RESOURCE_LOCAL"/>
</persistence>

fromJapan said...

[classpass]/com.example.user.User:
package com.example.user;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="User")
public class User
{
@Id
@GeneratedValue
private String id;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String userId)
{
this.id = userId;
}
@Override
public int hashCode()
{
int hash = 0;
hash+=(this.id==null?0:this.id.hashCode());
return hash;
}
@Override
public boolean equals(Object object)
{
if(!(object instanceof User))return false;
User other=(User)object;
if(this.id==other.id)return true;
if(this.id==null)return false;
if(this.id.equals(other.id))return true;
return false;
}
@Override
public String toString()
{
return "User[id="+id+", name="+name+"]";
}
}

[classpass]/com.example.user.UserDAOHibernateImpl:
package com.example.user;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
// Springに自動登録してもらうための印
@Repository("IUserDao")
public class UserDAOHibernateImpl implements IUserDao
{
// PersistenceContextをつけておくとSpringが適切にインスタンスをセットしてくれる
@PersistenceContext
private EntityManager entityManager;
public String addUser(User user)
{
String success;
try
{
entityManager.persist(user);
success="Welcome !";
}
catch (Exception e)
{
success="Sorry, user cannot be added";
}
return success;
}
@Transactional(readOnly=true)
public User findUserById(final String id)
{
return (User)entityManager.find(User.class,id);
}
}

Truong said...

thank you for your help, i changed project.

Anonymous said...

Nice tutorial. - VaanNila

Nerses said...

This one is, probably, the best tutorial for java/spring/struts/hibernate! Thanks a Lot!

nerses

Gustavo said...

Can u post a sample using annotations instead of *.hbm.xml files? Tnx a lot

KALEES said...
This comment has been removed by the author.
KALEES said...

Hi,
You tutorial is nice.. I got overview of Struts,Spring,Hibernate integration... I tried your code but i get an error, when i run it ...
You are using below code to inject
UserService reference bean but it belongs to org.springframework.transaction.interceptor.TransactionProxyFactoryBean class..
bean id="userAction"
class="com.example.user.action.UserAction" singleton="false"
constructor-arg

ref bean="UserService"
constructor-arg

bean


but In action class constructor looks like this

public UserAction(IUserService userService)
{
System.out.println("Hello i am A");
this.userService=userService;

}

What change should i make to run this application..
Thank you..