Hibernate - Struts 2 Integration



Struts 2 is a web framework which is free and opensource available from Apache, and can be downloaded from https://struts.apache.org/releases.html

In this tutorial, we will build a web application using Struts and Hibernate. You need to have jars for Struts 2 and Hibernate. Place the jar files in your CLASSPATH.

It is a simple application with 2 jsp's, index.jsp and showResults.jsp. User will enter a Student ID and hit the button 'Search'. The showResults.jsp will display Student information based on the Student ID.

Create UI Pages

Let's create following jsp pages to be used in this web application.

index.jsp

<form action="DisplayResults" method="post">
   <center>Student id:<input type="text" name="StudentId"/><br><br/>
   <input type="submit" value="Search"/></center>
</form>

showResults.jsp

<%
String as = request.getParameter("StudentId");
System.out.println("StudentId: " + as);

if(as.equals("")){
   out.print("Sorry, you have not entered Student Id");
}
int idr = Integer.parseInt(as);
Student st1 = StudentDAO.getStudent(idr);
%>
<body>
   <table border="1" align="center">
      <thead><tr><td>StudentID</td><td>First Name</td><td>Last Name</td><td>Dept<td></tr></thead>
      <tr><td><%= st1.getStudentid() %></td><td><%= st1.getfName()%></td><td><%= st1.getlName() %></td><td><%= st1.getDept() %></td></tr>
   </table>
</body>

Create Database Table

Let's create a Students table and insert data using following sql queries −

create table students( 
   StudentID int, 
   LastName varchar(255), 
   FirstName varchar(255), 
   Address varchar(255), 
   Dept varchar(255), 
   primary key(StudentID)
);

insert into students values
(1000, 'Agarwal', 'Bonny', '12 Southern Ave', 'Mathematics')
(1001, 'Pandey', 'Amit', ' 8 Ganesh Chandra Rd. ', 'Physics')
(1002, 'Kumar', 'Kalyan', '42 Brick Rd., Alipur', 'English');

Create Hibernate Configuration File

Now create a hibernate configuration file for database and other details.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <property name="hbm2ddl.auto">update</property>
      <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
      <property name="connection.url">jdbc:mysql://localhost/TUTORIALSPOINT</property>
      <property name="connection.username">root</property>
      <property name="connection.password">guest123</property>
      <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
      <mapping resource="student.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

Create Mapping Configuration File

Now create a mapping file that instructs Hibernate how to map the Student object to the database table.

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="com.tutorialspoint.webhibernate.Student" table="students">
      <id name="studentid">
         <generator class="increment"></generator>
      </id>
      <property name="firstName" column="firstname"></property>
      <property name="lastName" column="lastname"></property>
      <property name="dept" column="dept"></property>
   </class>
</hibernate-mapping>

Create Struts 2 Configuration File

Now create a configuration file for struts which instructs structs to map structs action.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation  
//DTD Struts Configuration 2.1//EN"   
"http://struts.apache.org/dtds/struts-2.1.dtd">  
<struts>
   <action name="DisplayResults" class="Student" >  
      <result name="success">showResults.jsp</result>  
   </action>
</struts>

Create WEB.XML File

Now create a web.xml, deployment descriptor under WEB-INF folder.

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   SYSTEM web-app_2_5.dtd >
   <welcome-file-list>  
      <welcome-file>index.jsp</welcome-file>  
   </welcome-file-list>  
   <filter>  
      <filter-name>studentFilter</filter-name>  
      <filter-class>  
         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
      </filter-class>  
   </filter>  
   <filter-mapping>  
      <filter-name>studentFilter</filter-name>  
      <url-pattern>/*</url-pattern>  
   </filter-mapping>  
</web-app>

Create Java Classes

Now let's create the Student class and a DAO class to persist the Student object. Student class serves as the Action class class for Struts and persistent class for Hibernate.

Student.java

package com.tutorialspoint.webhibernate;

public class Student {

   private int studentid;
   private String firstName;
   private String lastName;
   private String dept;

   public Student() {}

   public Student(int i) {
      this.studentid = i;
   }

   public String execute() {
      return "success";
   }

   public Student getStudentForId(int j) {
      Student s1 = StudentDAO.getStudent(studentid);
      return s1;
   }

   public int getStudentid() {
      return studentid;
   }
   public void setStudentid(int studID) {
      studentid = studID;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String fName) {
      this.firstName = fName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lName) {
      this.lastName = lName;
   }
   public String getDept() {
      return dept;
   }
   public void setDept(String dept) {
      this.dept = dept;
   }
}

StudentDAO.java

package com.tutorialspoint.webhibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.query.Query;
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
import java.util.List;
import java.util.Iterator;

public class StudentDAO {

   public static Student getStudent(int i) {
      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
      Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  

      SessionFactory factory=meta.getSessionFactoryBuilder().build();  
      Session session=factory.openSession();  
      Transaction tx = session.beginTransaction();

      String hql = " from Student where studentid = :student_id ";
      Query<?> query = session.createQuery(hql, Student.class);
      query.setParameter("student_id", i);

      System.out.println("student_id: " + i);
      List<Student> k = (List<Student>) query.getResultList();
      System.out.println("List size: " + k.size());
      tx.commit();
      session.close();
      Student st = new Student(1);
      for (Iterator<?> iterator = k.iterator(); iterator.hasNext();){
         st = (Student) iterator.next();
      }
      return st; 
   }
}

Flow of the application

  1. User types Student ID in index.jsp

  2. In index.jsp, the form is said to process 'DisplayResults' action. 'DisplayResults' is mapped to Student.java in struts.xml which is the Action class. The execute() method of Student.java is called, which returns "success".

  3. Upon returning "success", as declared in struts.xml, the control passes to "showResults.jsp".

Steps to deploy Web Application

We're using Tomcat to deploy this web application. Once Tomcat is installed, we're assuming TOMCAT_HOME environment variable represents the tomcat installation directory.

  • Create a directory called WebHibernate under TOMCAT_HOME/webapps directory.

  • Under this directory(TOMCAT_HOME/webapps), place index.jsp, showResults.jsp

  • Create a directory, WEB-INF in the same directory (TOMCAT_HOME/webapps).

  • Under WEB-INF, copy web.xml.

  • Create a directory lib under WEB-INF and place all the dependencies.

  • Create directory structure under WEB-INF/classes/com/tutorialspoint/webhibernate/ and place Student.class, StudentDAO.class

  • Start Tomcat

Output

Open browser, type URL: http://localhost:8080/WebHibernate .Your index page is going to look like this:

Student Id in Web Application

Enter 1000 for Student Id. The results page looks like this:

Student Details in Web Application
Advertisements