This article is a tutorial on how to integrate the Struts framework and Hibernate OR mapper in a Java web based application. These days, struts and hibernate are used commonly in the web based applications to enhance performance. This tutorial recommends basic knowledge in struts and hibernate , even though its a lucid guide for the beginners.
Struts Framework Introduction:
Apache Struts Framework is developed for implementing the MVC architecture for our applications. MVC architecture will separate the Business logic , Presentation logic and the page flow controller . This will help the developer to change any components without any or less impact on each others.
Hibernate Introduction:
Hibernate is one of the popular Object Relational Mapper for java. It provides powerful ,ultra-high performance OR persistence and Database query service for java web based applications.
Struts – Hibernate Integration:
Here we can see how we can develop the high performance application by implementing the Struts and Hibernate all together in one system. You can feel the performance of your application goes high through the struts hibernate integration. Lets start with an example on how we can integrate it in our application. The applications starts with the blank struts framework and we need to add the Hibernate library files into them. The additional and the important thing we need is the integration Plugin ,that should be defined in the struts-config.xml file. Here in this article I would like to start with an example application “Rank List Generationâ€.This application will insert marks and student details to the Database ,then generates and display the Rank list to the user.
Download Struts, Hibernate, Ant and MySql Driver:
First thing to do is to start a new blank struts application which is available along with the struts downloads. Then download and add the library files of the Hibernate , Ant and MySql driver to the application lib folder. Now we can set the ball rolling. </SPAN>
Hibernate Configuration file:
Hibernate configuration file or the hibernate.cg.xml , which should reside in the java WEB-INF/classes folder contains all the information about the database connections and table mappings .
Here is the example for the hibernate.cg.xml file :
<?xml version='1.0'encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://192.168.1.250/db_name</property> <property name="hibernate.connection.username">username</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Mapping files --> <mapping resource="/results/net/dao/hibernate/Marks.hbm.xml"/> </session-factory> </hibernate-configuration>
The Database tables will be automatically created by Hibernate while the server is started , so we need not to worry about editing and creating the tables manually through the Mysql back end. When the “hibernate.hbm2ddl.auto†property above is set to “create†, the tables content will be wiped out on every server startup. “update†will persist the previous contents on server startup.
Hibernate Table Mapping Configuration file:
From the above configuration file the <mapping> tag maps one table named “Marks†, which is used in the application. The mapping file describes the table name , and the description about its fields. The xml code for Marks.hbm.xml is given below:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping auto-import="true" default-lazy="false"> <class name="results.net.dao.hibernate.Marks" table="marks"> <id name="id" type="java.lang.Integer" column="Id" unsaved-value="null"> <generator class="native" /> </id> <property name="last_name" type="java.lang.String" column="Last_name" not-null="true" length="100" /> <property name="first_name" type="java.lang.String" column="First_name" not-null="true" length="100" /> <property name="maths" type="java.lang.Integer" column="Maths" not-null="true" /> <property name="english" type="java.lang.Integer" column="English" not-null="true" /> <property name="physics" type="java.lang.Integer" column="Physics" not-null="true" /> <property name="total" type="java.lang.Integer" column="Total" not-null="true" /> </class> </hibernate-mapping>
From the above codes we can see the property tag defines the table fields and its type and description .The class tag defines the table name and maps the bean class for that table. The name attribute in the property tag is the logical name used in Hibernate through out the application in hibernate queries. The column attribute is the actual name of that field in the mysql back end. Like wise the name attribute in the class tag describes the actual name of the table.
The Hibernate will create the table named marks on server startup , the description of the table will be as follows :
+------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | Id | int(11) | | PRI | NULL | auto_increment | | Last_name | varchar(100) | | | | | | First_name | varchar(100) | | | | | | Maths | int(11) | | | 0 | | | English | int(11) | | | 0 | | | Physics | int(11) | | | 0 | | | Total | int(11) | | | 0 | | +------------+--------------+------+-----+---------+----------------+
Java beans for tables:
From the above we can see the “results.net.dao.hibernate.Marks” is the java bean class used to store and read the records from the table “Marks”. The java bean class is as follows:
package results.net.dao.hibernate; import java.io.Serializable; public class Marks implements Serializable { /** identifier field */ private Integer id; /** persistent fields */ private String first_name; private String last_name; private Integer english; private Integer maths; private Integer physics; private Integer total; /** full constructor */ public Marks(Integer id, String first_name, String last_name, Integer english,Integer maths,Integer physics,Integer total) { this.id = id; this.first_name = first_name; this.last_name = last_name; this.english = english; this.maths = maths; this.physics = physics; this.total = total; } /** default constructor */ public Marks() { } public Integer getEnglish() { return english; } public String getFirst_name() { return first_name; } public Integer getId() { return id; } public String getLast_name() { return last_name; } public Integer getMaths() { return maths; } public Integer getPhysics() { return physics; } public Integer getTotal() { return total; } public void setEnglish(Integer english) { this.english = english; } public void setFirst_name(String first_name) { this.first_name = first_name; } public void setId(Integer id) { this.id = id; } public void setLast_name(String last_name) { this.last_name = last_name; } public void setMaths(Integer maths) { this.maths = maths; } public void setPhysics(Integer physics) { this.physics = physics; } public void setTotal(Integer total) { this.total = total; } }
There are getter and setter methods for the fields in the corresponding table as shown above.
Creating Struts Hibernate Plugin:
The important part Struts Hibernate Integration plugin does the job of creating hibernate session factory and cache it in the servlet context. This strategy enhances the performance of the application.
The Plugin class “HibernatePlugIn.java†is as follows:
package results.net.plugin; import java.net.URL; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.hibernate.HibernateException; public class HibernatePlugIn implements PlugIn { private String_configFilePath = "/hibernate.cfg.xml"; /* * the key under which the SessionFactory instance is stored * in the ServletContext */ public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName(); private SessionFactory_factory = null; public void destroy() { try{ _factory.close(); }catch(HibernateException e){ System.out.println("Unable to close Hibernate Session Factory: " + e.getMessage()); } } public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { System.out.println("*************************************"); System.out.println("**** Initilizing HibernatePlugIn **********"); Configuration configuration = null; URL configFileURL = null; ServletContext context = null; try{ configFileURL = HibernatePlugIn.class.getResource(_configFilePath); context = servlet.getServletContext(); configuration = (new Configuration()).configure(configFileURL); _factory = configuration.buildSessionFactory(); //Set the factory into session context.setAttribute(SESSION_FACTORY_KEY,_factory); }catch(HibernateException e){ System.out.println("Error while initializing hibernate: " + e.getMessage()); } System.out.println("*************************************"); } /* * Setter for property configFilePath. * @param configFilePath New value of property configFilePath. */ public void setConfigFilePath(String configFilePath) { if ((configFilePath == null) || (configFilePath.trim().length() == 0)) { throw new IllegalArgumentException("configFilePath cannot be blank or null."); } System.out.println("Setting 'configFilePath' to '" + configFilePath + "'..."); _configFilePath = configFilePath; } /*(SessionFactory) servletContext.getAttribute(HibernatePlugIn.SESSION_FACTORY_KEY);*/ }
Here _configFilePath holds the name of the Hibernate configuration file. SESSION_FACTORY_KEY stores the session factory instance in the Servlet context. init() is called on the startup of struts application . On startup the session factory is initialized and cached in the servlet context.
Installing the Plugin:
The HibernatePlugIn installation is very easy . We just need to include a line in the struts-config.xml file as :
<plug-in className="results.net.plugin.HibernatePlugIn"></plug-in>
Build and Test the application:
Now you need to build your application using the ant and test it . If the HibernatePlugin Initialization shows success during server startup your application is ready to start. The HibernatePlugin failure describes the DB connection information in the configuration file is not valid.
Your server output will display the below , if your hibernate installation is successful :
************************************* **** Initilizing HibernatePlugIn ********** *************************************
Example Rank List Application:
Here we can start our application from index.jsp where we can insert the marks of a student as well as displays the Rank list.
The index.jsp is as follows:
<%@ taglib uri="/tags/struts-html" prefix="html" %> <html> <head> <title>Results - Struts Hibernate Integration Example</title> </head> <body> <center> <%@ page import="java.util.*"%> <html:form action="/addMarksPage"> <table bgcolor="#D8D8D8" class="borders"> <tr> <td width="250" colspan="3" align="center" class="tdhed"> ADDING MARKS </td> </tr> <tr> <td colspan=3 align=center> </td> </tr> <tr> <td colspan=1 align=center width=20> </td> <td align=left> <h4>First Name</h4> </td> <td align=left> <html:text property="firstname"/> </td> </tr> <tr> <td colspan=1 align=center width=20> </td> <td align=left> <h4>Last Name</h4> </td> <td <html:text property="lastname"/> </td> </tr> <tr> <td colspan=1 align=center width=20> </td> <td align=left> <h4>English</h4> </td> <td align=left> <html:text property="english"/> </td> </tr> <tr> <td colspan=1 align=center width=20> </td> <td align=left> <h4>Maths</h4> </td> <td align=left> <html:text property="maths"/> </td> </tr> <tr> <td colspan=1 align=center width=20> </td> <td align=left> <h4>Physics</h4> </td> <td align=left> <html:text property="physics"/> </td> </tr> <tr> <td colspan=3 align=center> </td> </tr> <tr> <td colspan=3 align=center> <html:submit>ADD MARKS</html:submit> </td> </tr> </table> </html:form> <br><br> <% List results=(List)request.getAttribute("result"); if(results!=null) { %> <table cellspacing="0" class="notes_table"> <tr> <td align=center class="subhed">Rank</td> <td align=center class="subhed">Name</td> <td align=center class="subhed">English</td> <td align=center class="subhed">Maths</td> <td align=center class="subhed">Physics</td> <td align=center class="subhed">Total Marks</td> </tr> <% Iterator itr=results.iterator(); int index=1; while(itr.hasNext()) { results.net.dao.hibernate.Marks mark = (results.net.dao.hibernate.Marks)itr.next(); %> <tr> <td align=center class="notes_td1"><%=index%></td> <td align=center class="notes_td1"><%=mark.getFirst_name()%><%=mark.getLast_name()%></td> <td align=center class="notes_td1"><%=mark.getEnglish()%></td> <td align=center class="notes_td1" ><%=mark.getMaths()%></td> <td align=center class="notes_td1"><%=mark.getPhysics()%></td> <td align=center class="notes_td1"><%=mark.getTotal()%></td> </tr> <% index++; } %> </table> <% } %> <br><br> </body> </html>
Here the form submits to “/addMarksPage†which is defined in struts-config.xml . The Action class inserts the data and returns the rank list back to the index.jsp .
Server-Config.xml :
struts-config.xml act as the controller in the struts MVC architecture. It acts as the intermediary between the presentation logic and business logic and defines all the page flows.The struts-config.xml file will be as follows :
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "https://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="AddMarksPage" type="results.web.AddMarksPageActionForm"> </form-bean> </form-beans> <action-mappings> <action path="/addMarksPage" type="results.web.AddMarksPageAction" name="AddMarksPage" scope="request" validate="true" input="/pages/index.jsp"> <forward name="success" path="/pages/index.jsp"/> </action> </action-mappings> <plug-in className="results.net.plugin.HibernatePlugIn"> <!-- <set-property property="configFilePath"value="/hibernate.cfg.xml" />--> </plug-in> </struts-config>
We can see the corresponding ActionForm and Action is defined in the <form-bean> and <action> tags respectively . The Bean class defined in the <form-bean> fetches the user data and submits to the class defined in <action> . The Action class is where process user input and where the business logic runs. Thats the power of struts separating the business logic as Action class , presentation as jsp and controller as struts-config.xml.
ActionForm Class (Java Bean) :
Here we have defined the Action form bean class as AddMarksPageActionForm.java in the config file above. This bean file has the getter and setter methods of all our input fields in the home page.
The AddMarksPageActionForm.java is as below :
package results.web; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.*; public class AddMarksPageActionForm extends ActionForm { private String firstname=null; private String lastname=null; private Integer english=null; private Integer maths=null; private Integer physics=null; public Integer getEnglish() { return english; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public Integer getMaths() { return maths; } public Integer getPhysics() { return physics; } public void setEnglish(Integer english) { this.english = english; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public void setMaths(Integer maths) { this.maths = maths; } public void setPhysics(Integer physics) { this.physics = physics; } }
Action Class (Model) :
Action class does the job of business logic. Here we have the class AddMarksPageAction.java which accepts the user request and process it and stores it in the DB using OR mapper Hibernate.
AddMarksPageAction.java is as follows :
package results.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import java.util.List; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import results.net.plugin.HibernatePlugIn; import results.net.dao.hibernate.Marks; import org.hibernate.SessionFactory; import org.hibernate.Session; public class AddMarksPageAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AddMarksPageActionForm formObj = (AddMarksPageActionForm)form; /*Get the servlet context */ ServletContext context = request.getSession().getServletContext(); /*Retrieve Session Factory */ SessionFactory _factory = (SessionFactory) context.getAttribute(HibernatePlugIn.SESSION_FACTORY_KEY); /*Open Hibernate Session */ Session session = _factory.openSession(); try { //Inserting Marks to Table Marks marks = new Marks(); marks.setFirst_name(formObj.getFirstname()); marks.setLast_name(formObj.getLastname()); marks.setEnglish(formObj.getEnglish()); marks.setMaths(formObj.getMaths()); marks.setPhysics(formObj.getPhysics()); marks.setTotal(new Integer(formObj.getEnglish().intValue() +formObj.getMaths().intValue()+formObj.getPhysics().intValue())); session.beginTransaction(); session.save(marks); session.getTransaction().commit(); } catch(Exception e) { session.getTransaction().rollback(); } //Fetching result list List result=session.createQuery("from Marks order by total desc").list(); request.setAttribute("result",result); /*Close session */ session.close(); return mapping.findForward("success"); } }
In the above example retrieves the session factory and opens the hibernate session “session” . The values are set to DB bean class “Marks” from the ActionForm beans. Then the transaction is committed and stored in the DB. Later the Rank list is fetched from DB using hibernate query and assigned to request attribute which will be later retrieved and displayed in index.jsp. (Please refer the index.jsp and struts-config.xml files where the page flow and the result display is mentioned).
Build and run the application :
Now you build and run the application . It runs successfully if all your config files are set properly.
Conclusion:
This session covers the basic tutorial on the Struts-Hibernate integration and spotted suitable examples. The entire example code can be downloaded from my site. Please refer the downloads section.
Downloads:
-
Example Application :https://shabeelsyed.com/downloads/Results-Struts-Hibernate.tar.gz
-
Hibernate : http://www.hibernate.org/
References:
About the author:
Shabeel Syed Ummer works as Software Developer in Bobcares. He primarily works on Php and Java. And he is proficient in template systems like Smarty, Joomla, OsCommerce2, OpenRealty2, Struts and ibernate.
I am able to opent the tomcat console, but if I tupe http[:]//localhost/strutshinernate, strutshibernate being the name of the war file, it simply says The requested resource (/strutshibernate/) is not available. My web.xml is pasted below
Struts Blank Application
action
org.apache.struts.action.ActionServlet
config
/WEB-INF/struts-config.xml
debug
2
detail
2
2
action
*.do
index.jsp
/tags/struts-bean
/WEB-INF/struts-bean.tld
/tags/struts-html
/WEB-INF/struts-html.tld
/tags/struts-logic
/WEB-INF/struts-logic.tld
/tags/struts-nested
/WEB-INF/struts-nested.tld
/tags/struts-tiles
/WEB-INF/struts-tiles.tld
i have two diff. application one is hibernate and another struts
how to integrate.
you’re so nice..
good article. thanks a lot.
=)
Its really nice artical but configuration file is missing here.
Thanks for the tutorial dude…really very gud tutorial… i got to learn new things .. saw lot of new errors … thanks man .. appreciate it
Hi Prasad,
I have found the url mentioned is not matching with the war file you mentioned.
Please recheck the url and let me know if the issue still exists.
Thanks & Regards,
Girish.K
Hi me.like011,
Integrating hibernate with struts will better.
You can follow this steps:
1. Make a jar of hibernate application and add it in the classpath of struts application.
2. Write your database calls by using hibernate session factory.
I hope the above steps will meet your requirement.
Thanks & Regards,
Girish.K
java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from HttpSession to Session
Why do I get this when I hit the action file?
Hi ,
Please check whether you are using the hibernate Session.
Thanks & Regards,
Girish.K
sir,during connecting struts with hibernate im getting security exception
java.lang.SecurityException: class “org.apache.commons.collections.BoundedMap”‘s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(ClassLoader.java:775)
at java.lang.ClassLoader.preDefineClass(ClassLoader.java:487)
at java.lang.ClassLoader.defineClass(ClassLoader.java:614)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1853)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:875)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1330)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1209)
Hi Abhilash,
Please update the jar commons-collections.jar with the latest version.
Thanks & Regards,
Girish.K
Thanks for sharing this information as well as the most important source code. Keep sharing similar useful information here…
Many many Thanks for this nice tutorial brother….
I am developing one application using hibernate and struts. I got an exception NullPointerException in two places
1) DAO class (in save method at Transaction tx=getSession().beginTransaction())
2) Struts Action class i am creating DAO class object at this place i got an exception
I Love u…..
Nice Application….
It’s nice article but,how to separate data access logic from the action classes and how to get the session factory instance in dao classes explain
Hi.Nice way of explanation.thank you