In this example we will describe the integration of Struts 2 with Hibernate as well as using Spring and Tile in this example. We recommend firstly you have a look to previous examples Struts with Spring Integration Example and Struts2 with Tiles2 Integration Example.
Spring 5 Design Pattern Book
Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. If you are not familiar with Hibernate then you can check our Hibernate tutorial. And if you are not familiar with Spring then you can check our Spring tutorial.
Step 1: Create a Database DOJDB on MySQL Database and also we create User table on this database.
CREATE TABLE User( ID BIGINT NOT NULL AUTO_INCREMENT, USERNAME VARCHAR(20) NOT NULL, AGE BIGINT NOT NULL, GENDER VARCHAR(20) NOT NULL, JOBTYPE VARCHAR(20) NOT NULL HOBBIES VARCHAR(20) NOT NULL PRIMARY KEY (ID) );
Step 2: Create a database.properties for database configuration information in the resources folder under src folder in the created project.
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://localhost:3306/DOJDB database.user=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update
Step 3: Create a Dynamic Web Project with a name Struts2Hibernate3Spring3Tile2Integration and create packages com.dineshonjava.struts2.action, com.dineshonjava.struts2.bean, com.dineshonjava.struts2.dao, com.dineshonjava.struts2.service, com.dineshonjava.struts2.model, com.dineshonjava.struts2.utils under the src folder in the created project.
Step 4: Add below mentioned Struts 2, Hibernate 3 and Spring 3 related libraries and other libraries into the folder WebRoot/WEB-INF/lib.
Step 5: Create a Java class UserAction, UserBean, User, UserDao, UserDaoImpl, UserService, UserServiceImpl, CommonUtility under the respective packages.
Step 6: Create Spring configuration files web.xml, applicationContext.xml, tiles-def.xml under the WebRoot/WEB-INF/ and struts.xml under src/resources folders.
Step 7: Create View files under the /WebRoot/ folder. Create a view file mainTemplate.jsp, users.jsp, body.jsp, menu.jsp, haeder.jsp, footer.jsp etc.
Step 8: Project Structure
APPLICATION ARCHITECTURE
We will have a layered architecture for our demo application. The database will be accessed by a Data Access layer popularly called as DAO Layer. This layer will use Hibernate API to interact with database. The DAO layer will be invoked by a service layer. In our application we will have a Service interface called UserService.
Step 9: Hibernate Configuration file with Spring Dependencies
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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:component-scan base-package="com.dineshonjava.struts2" /> <!-- Database Configuration Start here--> <context:property-placeholder location="classpath:database.properties"/> <tx:annotation-driven transaction-manager="hibernateTransactionManager"/> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource"> <property name="driverClassName" value="${database.driver}"></property> <property name="url" value="${database.url}"></property> <property name="username" value="${database.user}"></property> <property name="password" value="${database.password}"></property> </bean> <bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory"> <property name="dataSource" ref="dataSource"></property> <property name="annotatedClasses"> <list> <value>com.dineshonjava.struts2.model.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop> </props> </property> </bean> <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager" id="hibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- Database Configuration End Here--> <bean id="user" class="com.dineshonjava.struts2.action.UserAction"/> <bean id="userBean" class="com.dineshonjava.struts2.bean.UserBean"/> </beans>
Let us go through the hibernate configuration only because rest is Spring dependency already know in spring tutorial. First, we declared that we are using MySQL driver. Then we declared the jdbc url for connecting to the database. Then we declared the connection’s username, password and pool size. We also indicated that we would like to see the SQL in the log file by turning on “show_sql” to true. Please go through the hibernate tutorial to understand what these properties mean. Finally, we set the mapping class to com.dineshonjava.struts2.model.User which we will create in this chapter.
Step 10: Create Action class and Other classes related to Application.
UserBean.java
package com.dineshonjava.struts2.bean; /** * @author Dinesh Rajput * */ public class UserBean { private String userName; private Long userAge; private String userGender; private String userJob; private String []userHobbies; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Long getUserAge() { return userAge; } public void setUserAge(Long userAge) { this.userAge = userAge; } public String getUserGender() { return userGender; } public void setUserGender(String userGender) { this.userGender = userGender; } public String getUserJob() { return userJob; } public void setUserJob(String userJob) { this.userJob = userJob; } public String[] getUserHobbies() { return userHobbies; } public void setUserHobbies(String[] userHobbies) { this.userHobbies = userHobbies; } }
User.java
package com.dineshonjava.struts2.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * @author Dinesh Rajput * */ @Entity @Table(name="User") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "id") private Long userId; @Column(name="username") private String userName; @Column(name="age") private Long userAge; @Column(name="gender") private String userGender; @Column(name="jobtype") private String userJobType; @Column(name="Hobbies") private String userHobbies; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Long getUserAge() { return userAge; } public void setUserAge(Long userAge) { this.userAge = userAge; } public String getUserGender() { return userGender; } public void setUserGender(String userGender) { this.userGender = userGender; } public String getUserJobType() { return userJobType; } public void setUserJobType(String userJobType) { this.userJobType = userJobType; } public String getUserHobbies() { return userHobbies; } public void setUserHobbies(String userHobbies) { this.userHobbies = userHobbies; } }
UserDao.java
package com.dineshonjava.struts2.dao; import java.util.List; import com.dineshonjava.struts2.model.User; /** * @author Dinesh Rajput * */ public interface UserDao { void saveUser(User user); List<User> getUserList(); }
UserDaoImpl.java
package com.dineshonjava.struts2.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.dineshonjava.struts2.model.User; /** * @author Dinesh Rajput * */ @Repository("userDao") public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; @Override public void saveUser(User user) { sessionFactory.getCurrentSession().saveOrUpdate(user); } @SuppressWarnings("unchecked") @Override public List<User> getUserList() { return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list(); } }
UserService.java
package com.dineshonjava.struts2.service; import java.util.List; import com.dineshonjava.struts2.model.User; /** * @author Dinesh Rajput * */ public interface UserService { void saveUser(User user); List<User> getUserList(); }
UserServiceImpl.java
package com.dineshonjava.struts2.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.dineshonjava.struts2.dao.UserDao; import com.dineshonjava.struts2.model.User; /** * @author Dinesh Rajput * */ @Service("userService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void saveUser(User user) { userDao.saveUser(user); } @Override public List<User> getUserList() { return userDao.getUserList(); } }
CommonUtility.java
package com.dineshonjava.struts2.utils; import java.util.ArrayList; import java.util.List; import com.dineshonjava.struts2.bean.UserBean; import com.dineshonjava.struts2.model.User; /** * @author Dinesh Rajput * */ public class CommonUtility { public static User createModel(UserBean userBean){ User user = new User(); user.setUserName(userBean.getUserName()); user.setUserAge(userBean.getUserAge()); user.setUserGender(userBean.getUserGender()); user.setUserJobType(userBean.getUserJob()); user.setUserHobbies(convertArrayToCsv(userBean.getUserHobbies())); return user; } public static List<UserBean> createUserBeanList(List<User> users){ List<UserBean> beans = new ArrayList<UserBean>(); UserBean userBean = null; for(User user : users){ userBean = new UserBean(); userBean.setUserName(user.getUserName()); userBean.setUserAge(user.getUserAge()); userBean.setUserGender(user.getUserGender()); userBean.setUserJob(user.getUserJobType()); userBean.setUserHobbies(convertCsvToArr(user.getUserHobbies())); beans.add(userBean); } return beans; } public static String convertArrayToCsv(String [] arr){ String csv = ""; for(String value : arr){ csv += value+","; } return csv; } public static String[] convertCsvToArr(String csv){ String [] values = csv.split(","); return values; } }
UserAction.java
package com.dineshonjava.struts2.action; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.dineshonjava.struts2.bean.UserBean; import com.dineshonjava.struts2.model.User; import com.dineshonjava.struts2.service.UserService; import com.dineshonjava.struts2.utils.CommonUtility; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * @author Dinesh Rajput * */ public class UserAction extends ActionSupport implements ModelDriven<UserBean>{ private static final long serialVersionUID = 1L; @Autowired private UserBean userBean; @Autowired private UserService userService; private List<UserBean> users; public String execute() { users = CommonUtility.createUserBeanList(userService.getUserList()); return "user"; } public String addUser(){ userService.saveUser(CommonUtility.createModel(userBean)); users = CommonUtility.createUserBeanList(userService.getUserList()); return "addUser"; } public String listUser(){ users = CommonUtility.createUserBeanList(userService.getUserList()); return "users"; } @Override public UserBean getModel() { return userBean; } public String alia() { return "alia"; } public String madhuri() { return "madhuri"; } public String user() { return "user"; } public List<UserBean> getUsers() { return users; } public void setUsers(List<UserBean> users) { this.users = users; } }
Create view files:
Let us now create the mainTemplate.jsp view file with the following content:
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute> </title> </head> <body> <table border="1"> <tr> <td colspan="2"><tiles:insertAttribute name="header"></tiles:insertAttribute><br/></td> </tr> <tr> <td><tiles:insertAttribute name="menu" /></td> <td><tiles:insertAttribute name="body" /></td> </tr> <tr> <td colspan="2"><tiles:insertAttribute name="footer" /></td> </tr> </table> </body> </html>
body.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style type="text/css"> b{color:navy; background-color: orange;} </style> <title>Struts2-Spring-Tiles integration | dineshonjava.com</title> </head> <body> <h2>Add User</h2><b> <s:form action="addUsermenu"> <s:textfield name="userName" key="user.name" /> <s:textfield name="userAge" key="user.age" value=""/> <s:radio name="userGender" key="user.gender" list="{'Male','Female'}" /> <s:select name="userJob" key="user.job" list="%{#{'Software':'Software','Hardware':'Hardware','Networking':'Networking','Marketing':'Marketing'}}"/> <s:checkboxlist name="userHobbies" key="user.hobby" list="{'Cricket','Football','Drawing','Cooking','Driving','Movie'}" /> <s:submit key="submit" align="center"/> </s:form> </b> <s:if test="%{users.isEmpty()}"> </s:if> <s:else> <b>List of Users</b> <table border="1"> <tr> <td><b>Name</b></td> <td><b>Age</b></td> <td><b>Gender</b></td> <td><b>Job Type</b></td> <td><b>Hobbies</b></td> </tr> <s:iterator value="users"> <tr> <td><s:property value="userName"/></td> <td><s:property value="userAge"/></td> <td><s:property value="userGender"/></td> <td><s:property value="userJob"/></td> <td><s:property value="userHobbies"/></td> </tr> </s:iterator> </table> </s:else> </body> </html>
menu.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <a href="<s:url action="usermenu"/>"> <h2>Add User</h2></a><br> <a href="<s:url action="aliamenu"/>"><h2>Alia Bhatt</h2></a><br> <a href="<s:url action="madhurimenu"/>"><h2>Madhuri Dixit</h2></a><br>
footer.jsp
<center><p><h2>Copyright © 2013 dineshonjava.com</h2></p> </center>
header.jsp
<table> <tr> <td><img src="http://2.bp.blogspot.com/-rBLnvKuVDO0/UWBnJJ4n1yI/AAAAAAAADCQ/Vh_cVJ34JFw/s1600/new-logo.png" /></td> <td><h1><span style="background-color: #FFFFcc">Struts2-Hibernate3-Tiles2-Spring3 integration</span></h1></td> </tr> </table>
users.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <a href="user">Struts2Spring3Hibernate3Tiles Example</a> </body> </html>
madhuri.jsp
<img src="http://www.topnews.in/files/Madhuri-Dixit_10.jpg" height="430" width="500" alt="Madhuri Dixit"/>
alia.jsp
<img src="http://cdntopics.onepakistan.com/wp-content/uploads/2012/10/Alia-Bhatt1.jpg" alt="Alia Bhatt"/>
Struts Configuration:
Let us put it all together using struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="myapp" /> <package name="user" extends="struts-default" namespace="/"> <result-types> <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" /> </result-types> <action name="user" class="user" method="execute"> <result name="user" type="tiles">mainTemplate</result> </action> <action name="*menu" class="user" method="{1}"> <result name="user" type="tiles">mainTemplate</result> <result name="madhuri" type="tiles">madhuri</result> <result name="alia" type="tiles">alia</result> <result name="addUser" type="tiles">mainTemplate</result> </action> </package> </struts>
myapp.properties
user.name=User Name user.age=User Age user.gender=Gender user.job=Job Type user.hobby=Hobbies submit=Add User
Tiles Configuration file-
tiles-def.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" "http://tiles.apache.org/dtds/tiles-config_2_0.dtd"> <tiles-definitions> <definition name="mainTemplate" template="/mainTemplate.jsp"> <put-attribute name="title" value="User Registration Form"/> <put-attribute name="header" value="/header.jsp"/> <put-attribute name="menu" value="/menu.jsp"/> <put-attribute name="body" value="/body.jsp"/> <put-attribute name="footer" value="/footer.jsp"/> </definition> <definition name="alia" extends="mainTemplate"> <put-attribute name="title" value="Alia Bhatt"/> <put-attribute name="body" value="/alia.jsp"/> </definition> <definition name="madhuri" extends="mainTemplate"> <put-attribute name="title" value="Madhuri Dixit"/> <put-attribute name="body" value="/madhuri.jsp"/> </definition> <definition name="success" extends="mainTemplate"> <put-attribute name="title" value="User Added Successfully"/> <put-attribute name="body" value="/success.jsp"/> </definition> </tiles-definitions>
create deployment descriptor
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts2Hibernate3Spring3Tile2Integration</display-name> <welcome-file-list> <welcome-file>users.jsp</welcome-file> </welcome-file-list> <context-param> <param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name> <param-value> /WEB-INF/tiles-def.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.apache.struts2.tiles.StrutsTilesListener </listener-class> </listener> <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> </web-app>
Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/doj/user
This will give you following screen:
Fill data of user form and submit let see following screen we will get.
http://localhost:8080/doj/addUsermenu.action
http://localhost:8080/doj/madhurimenu.action
Download Source Code + Libs
Struts2Hibernate3Spring3Tile2Integration.zip
Excellent Dinesh well appreciable..
Very well done Dinesh…Please update the stuffs in similar manner…keep it up.
hi Dinesh,I am using stuts2, hibernate, springs(for auto wiring) I am having A senario like, i am having one jsp in which it has 2 forms(eg Form1 with multiple rows, Form2 with multiple rows) when i click save button the data in the one form (Form1) shold be saved into Table1 and the Form2 data shld be saved into Table2. Please help in this regard.
Please send me your requirements with JSP files at admin@dineshonjava.com.
Hi Dinesh,
When i run the project then i got error 404
Thanks,
Wasif
Hi Dinesh,
When i run this project we are getting below erropr
type Status report
message /Struts2Hibernate3Spring3Tile2Integration/
description The requested resource (/Struts2Hibernate3Spring3Tile2Integration/) is not available.
hi dinesh after import this example into eclipse when i run this i got the following error please clarify this…
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Could not resolve placeholder 'hibernate.hbm2ddl.auto'
at
Hi,
Please put this value "create" instead of "${hibernate.hbm2ddl.auto}" because it may be not fetch value from properties file(database.properties).
Thanks
Dinesh
hi Dinesh i update create instead of auto in applicationContext.xml but even though it will shown error like below
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Could not resolve placeholder 'hibernate.hbm2ddl.create'
at
after i import this example into eclipse i just changed the build path to jdk 1.7 and tomcat 1.7 and i just update the db properties file db username and password and in applicationContext.xml i changed hibernate.hbm2ddl.create what u already said above so i update all these but even though i did not get output..so please help me
hi dinesh again i got the below error
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Could not resolve placeholder 'hibernate.hbm2ddl.create'
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:272)
Hi, Dinesh i got the output thanks for ur support any way all errors are rectified and finally i got the output thank you so much for your support
Yes same Eroor. please help.
Hi
Please use following line
<prop key="hibernate.hbm2ddl.auto">create </prop>
in stead of
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop>
Hi
Please use following line
<prop key="hibernate.hbm2ddl.auto">create</prop>
in stead of
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop>
Welcome friends.
Hi dinesh,
Its really great tutorial, In our company we are following the same architecture u r using in this example,
can u provide some examples for multiple rows submission, pagination, searching, dynamically adding the rows etc with the same struts2, hibernate, springs(autowiring)..
Hi friends,
Thanks for nice compliment and good comment.
Please explain your requirement and also you can send your requirement at admin@dineshonjava.com.
Thanks,
Dinesh
thanx alot mannnnnn!!!!!
Hi friends,
Thanks for nice compliment and good comment.
Hi Dinesh,
I am getting below error, when running the same application in eclipse:
Method public java.lang.String org.hibernate.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on org.hibernate.exception.JDBCConnectionException: Cannot open connection
The problematic instruction:
———-
==> ${msg[0]} [on line 68, column 29 in org/apache/struts2/dispatcher/error.ftl]
———-
Java backtrace for programmers:
———-
freemarker.template.TemplateModelException: Method public java.lang.String org.hibernate.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on org.hibernate.exception.JDBCConnectionException: Cannot open connection
at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:130)
at freemarker.ext.beans.SimpleMethodModel.get(SimpleMethodModel.java:138)
at freemarker.core.DynamicKeyName.dealWithNumericalKey(DynamicKeyName.java:111)
at freemarker.core.DynamicKeyName._getAsTemplateModel(DynamicKeyName.java:90)
at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)
at freemarker.core.Expression.getStringValue(Expression.java:93)
at freemarker.core.DollarVariable.accept(DollarVariable.java:76)
at freemarker.core.Environment.visit(Environment.java:221)
at freemarker.core.MixedContent.accept(MixedContent.java:92)
at freemarker.core.Environment.visit(Environment.java:221)
at freemarker.core.IfBlock.accept(IfBlock.java:82)
at freemarker.core.Environment.visit(Environment.java:221)
at freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:179)
at freemarker.core.Environment.visit(Environment.java:428)
at freemarker.core.IteratorBlock.accept(IteratorBlock.java:102)
at freemarker.core.Environment.visit(Environment.java:221)
at freemarker.core.MixedContent.accept(MixedContent.java:92)
at freemarker.core.Environment.visit(Environment.java:221)
Caused by: java.lang.NullPointerException
at freemarker.ext.beans.SimpleMemberModel.unwrapArguments(SimpleMemberModel.java:85)
at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:106)
… 43 more
Someone also posted the same query but did not get any reply. I request you, please do needful as its very urgent for me.
Thanks a lot for such a great tutorial.
Regards,
Robin
Guys, pls do reply on just above query:
when invoked on org.hibernate.exception.JDBCConnectionException: Cannot open connection
Regards,
robin
Hi Robin,
Please check following things.
1. Are you creating Database as given in application.
2.username & pwd of db.
Hi Anamika,
Thanks for reply. Actually I am iusing "hibernate.hbm2ddl.auto=create " rather than update option.So I jst only created Database schema. And belive that hibernate will make table itself. Also pwd and usename are correct, i checked it.
Are you sure its a problem of DB ? I have a bit doubt about getting sessionor might be due to struts implementaion as getting freemarker Template error. Please correct me , if am wrong.
Thank you so much for your considreration.
Regards,
Robin
Yes you are right Robin, Its problem due to connect to DB using JDBC.
use openSession() instead of getCurrentSession() and may be it work fine.
Plz send me zip file of app at admin@dineshonjava.com
Thanks,
Dinesh
Do one more thing in body.jsp.
check users.size() >0 before iterating it.
<s:if test ="%{users!= null}"> </s:if>
Hi Dinesh,
Thank you so much for your consideration.
The thing is I am getting session object by getCurrentSession() or openSession()
It's problem when trying to hit db then throwing exception.
I believe it might be due to struts 2 as apperaed in exception:
"${msg[0]} [on line 68, column 29 in org/apache/struts2/dispatcher/error.ftl]"
I am printing session object as below:
Session session= sessionFactory.openSession(); ( same behaviour with getcurrentSession())
System.out.println("atlesat m getting session……….."+session);
session object is like this:
atlesat m getting session………..SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
About JSP suggestion, it's already in your code i.e null check.
I am sending zip file to ur mail. Please get it and if possible, pls do let me know by today.
Thanks a lot bro!!
Regards,
Vibhu
I myself posted above query 🙂
Regards,
Robin/Vibhu
looking for help please….
Robin
how to delete record with out query in this project?
Hi,
Can anyone answer of above posted Query pls?
Robin
Hi Robin,
I have sent working application to your mail.
Thanks,
Dinesh
Hi Robin,
this problem is due to you declare your db configuration , jdbc, url, user, pass, driver… for that reason the server is refusing the connection because it not able to fetch. so please remove properties file and set in configuration file.
Please read following.
https://www.dineshonjava.com/2012/12/spring-mvc-with-hibernate-crud-example.html
Hi Dinesh,
Thank you so much for fixing out the issue.
But still facing one issue i.e. now it's getting session and creting table schema in db perfectly, but the thing is, it's not getting saved data in database, Only table structute is creating there.
Please suggest the same as well..
Thanks a ton bro!!
Regards,
Vibhu
hi dinesh Give me one example for creating web application by using annotations in hibernate and struts2
thanks in advance
Hi Dinesh,
Appliaction is working fine, please ignore above query!!
Regards,
Robin
Ok Robion, Enjoy learning with us.
I am very impressed by this blog. It's what I was looking for !!!
To my mind, one remark is that there are no enough explanations.
Can someone explain me why is UserBean used here?
Why didn't you use User object as model in UserAction?
Why is UserBean declared as spring bean? UserBean is simple pojo and can be created by new keyword.
Thank you very MUCH for your blog! It's invaluable help to any java beginner.
One more request @Dinesh!
Can you do us a favor to integrate Hibernate validator into this application.
I saw you included hibernate-validator-4.0.2.jar.
What I want is to setup hibernate constraints from package org.hibernate.validator.constraints.
Constraints should prevent invalid entities from being persisted into database
I had very hard time to make them work in simple Struts2+Hibernate webapp with help of struts2-fullhibernatecore-plugin.
This page can be served as starting point – https://code.google.com/p/full-hibernate-plugin-for-struts2/wiki/2_Hibernate_Validator_integration.
But I myself didn't succeed in this. I warned you….
Hi i am running struts+spring+hibernate application. i am getting error like
Servlet /StrutsSpringHibernateApp threw load() exception
java.lang.reflect.MalformedParameterizedTypeException
at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:60)
can u tell me how to resolve that exception.
can you share one spring enterprise application demo… it will help to every body….
Thanks Vovo for comments..I will post integration Hibernate validator
Thanks for this nice compliments.
Thanks,
Dinesh
Comments @LinkedIn
Very nice! Integrating multiple frameworks can be trial-and-error and time-consuming. Your example saves a lot of time and headache for someone looking to use or try this combination of technologies. Many thanks, Dinesh.
By David P.
Entertprise Software Developer/Architect