Javatpoint Logo

91-9990449935

 0120-4256464

Hibernate and Struts 2 Integration

We can integrate any struts application with hibernate. There is no requirement of extra efforts.

In this example, we going to use struts 2 framework with hibernate. You need to have jar files for struts 2 and hibernate.


Example of Hibernate and struts2 integration

In this example, we are creating the registration form using struts2 and storing this data into the database using Hibernate. Let's see the files that we should create to integrate the struts2 application with hibernate.

  • index.jsp file to get input from the user.
  • User.java A action class for handling the request. It uses the dao class to store the data.
  • RegisterDao.java A java class that uses DAO design pattern to store the data using hibernate.
  • user.hbm.xml A mapping file that contains information about the persistent class. In this case, action class works as the persistent class.
  • hibernate.cfg.xml A configuration file that contains informations about the database and mapping file.
  • struts.xml file contains information about the action class and result page to be invoked.
  • welcome.jsp A jsp file that displays the welcome information with username.
  • web.xml A web.xml file that contains information about the Controller of Struts framework.

index.jsp

In this page, we have created a form using the struts tags. The action name for this form is register.


User.java

It is a simple POJO class. Here it works as the action class for struts and persistent class for hibernate. It calls the register method of RegisterDao class and returns success as the string.


RegisterDao.java

It is a java class that saves the object of User class using the Hibernate framework.


user.hbm.xml

This mapping file contains all the information of the persitent class.


hibernate.cfg.xml

This configuration file contains informations about the database and mapping file. Here, we are using the hb2ddl.auto property, so you don't need to create the table in the database.


struts.xml

This files contains information about the action class to be invoked. Here the action class is User.


welcome.jsp

It is the welcome file, that displays the welcome message with username.


<%@ taglib uri="/struts-tags" prefix="S" %>

Welcome: <S:property value="name"/>


web.xml

It is web.xml file that contains the information about the controller. In case of Struts2, StrutsPrepareAndExecuteFilter class works as the controller.