Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 Hibernate integration


May 15, 2021 Struts2


Table of contents


Hibernate is a high-performance object/relationship retention and query service that is licensed under the open source GNU Wide General Public License (LGPL) and is free to download. I n this chapter. W e'll learn how to integrate Struts2 with Hibernate. I f you're not familiar with Hibernate, check out our Hibernate tutorial.

Database settings

For this tutorial, we'll use the struts2_tutorial" MySQL database, which is connected to the machine using the user name "root" without a password. F irst, you need to run the following script. T his script creates a new table called student and creates a small number of records in this table:

CREATE TABLE IF NOT EXISTS `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(40) NOT NULL,
  `last_name` varchar(40) NOT NULL,
  `marks` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

--
-- Dumping data for table `student`
--

INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) 
  VALUES(1, 'George', 'Kane', 20);
INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) 
  VALUES(2, 'Melissa', 'Michael', 91);
INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) 
  VALUES(3, 'Jessica', 'Drake', 21);

Hibernate configuration

Next, let's create .cfg.xml, which is the hibernate profile.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
   <property name="hibernate.connection.driver_class">c
      om.mysql.jdbc.Driver
   </property>
   <property name="hibernate.connection.url">
      jdbc:mysql://www.w3cschool.cn/struts_tutorial
   </property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.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 class="cn.w3cschool.hibernate.Student" />
</session-factory>
</hibernate-configuration> 

Let's take a look at the hibernate profile. F irst, we declare the use of the MySQL driver. T hen we declared jdbc url to connect to the database. W e then declare the username, password, and pool size of the connection. W e also point out that we want show_sql see SQL in the log file by turning the "2000s" into true. L earn what these properties mean through the Hibernate tutorial. F inally, we set the mapping class to cn.w3cschool.hibernate.Student created in this chapter.

Environment construction

This project requires a lot of jar files, the following is a screenshot of the full list of required JAR files:

Struts2 Hibernate integration

Most JAR files are available as part of the struts distribution. I f you have an application server installed, such as glassfish, websphere or jboss, then you can get most of the remaining jar files from the appserver's lib folder. I f not, you can download the file separately:

The rest of the files you should be able to assign from struts2.

Hibernate class

Now let's create the required java class for hibernate integration. F ollow the .java Student:

package cn.w3cschool.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {
	
   @Id
   @GeneratedValue
   private int id;
   @Column(name="last_name")
   private String lastName;
   @Column(name="first_name")
   private String firstName;
   private int marks;
   public int getId() {
    return id;
   }
   public void setId(int id) {
    this.id = id;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public int getMarks() {
      return marks;
   }
   public void setMarks(int marks) {
      this.marks = marks;
   }
}

This is a POJO class, a student table represented by the Hibernate specification. I t has property id, firstName, and lastName that correspond to the name of the object table column. L et's create a StudentDAO .java file, as follows:

package cn.w3cschool.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.
                     annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.
                     annotations.TransactionTarget;

public class StudentDAO {
	
   @SessionTarget
   Session session;

   @TransactionTarget
   Transaction transaction;

   @SuppressWarnings("unchecked")
   public List<Student> getStudents()
   {
      List<Student> students = new ArrayList<Student>();
      try
      {
         students = session.createQuery("from Student").list();
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
      return students;
   }

   public void addStudent(Student student)
   {
      session.save(student);
   }
}

The StudentDAO class is the data access layer of the Student class. I t has a way to list all students and then save a new student record.

Action class

The following file AddStudentAction .java defines our action class. W e have two ways to act here: execute() and listStudents(). T he execute() method is used to add new student records. W e use dao's save() approach to achieve this. A nother listStudents() method is used to list students. W e use the dao list method to get a list of all students.

package cn.w3cschool.struts2;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.w3cschool.hibernate.Student;
import cn.w3cschool.hibernate.StudentDAO;

public class AddStudentAction extends ActionSupport 
            implements ModelDriven<Student>{

   Student student  = new Student();
   List<Student> students = new ArrayList<Student>();
   StudentDAO dao = new StudentDAO();
   @Override
   public Student getModel() {
      return student;
   }

   public String execute()
   {
      dao.addStudent(student);
      return "success";
   }

   public String listStudents()
   {
      students = dao.getStudents();
      return "success";
   }

   public Student getStudent() {
      return student;
   }

   public void setStudent(Student student) {
      this.student = student;
   }

   public List<Student> getStudents() {
      return students;
   }

   public void setStudents(List<Student> students) {
      this.students = students;
   }
	
}

You'll notice that we're implementing the ModelDriven interface. T his is used when your action class handles a specific model class (such as Student) rather than individual properties (such as firstName, lastName). T he ModelAware interface requires you to implement a way to return to the model. I n our case, we return the "student" object.

Create a view file

Now create a .jsp view file that:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head>
<body>
   <s:form action="addStudent">
   <s:textfield name="firstName" label="First Name"/>
   <s:textfield name="lastName" label="Last Name"/>
   <s:textfield name="marks" label="Marks"/>
   <s:submit/>
   <hr/>
   <table>
      <tr>
         <td>First Name</td>
         <td>Last Name</td>
         <td>Marks</td>
      </tr>
      <s:iterator value="students">	
         <tr>
            <td><s:property value="firstName"/></td>
            <td><s:property value="lastName"/></td>
            <td><s:property value="marks"/></td>
           </tr>
      </s:iterator>	
   </table>
   </s:form>
</body>
</html>

The .jsp is very simple. I n the above section, we have a form submitted to addStudent.action. I t accepts firstName, lastName and marks. Because addStudent action is bound to ModelAware's AddSudentAction, a student bean is automatically created with values automatically populated with firstName, lastName, and marks.
In the following section, we browse the list of students (see AddStudentAction.java) and display the values of firstname, lastname, and marks in the table.

Struts configuration

Let's use the 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.devMode" value="true" />

   <package name="myhibernate" extends="hibernate-default">

      <action name="addStudent" method="execute"
         class="cn.w3cschool.struts2.AddStudentAction">
         <result name="success" type="redirect">
               listStudents
         </result>
      </action>

      <action name="listStudents" method="listStudents"
         class="cn.w3cschool.struts2.AddStudentAction">
         <result name="success">/students.jsp</result>
      </action>

</package>

</struts>

The important thing to note is that our package "myhibernate" extends the struts2 default package called "hibernate-default". T hen we declare two actions: addStudent and listStudents. A ddStudent calls the execute() of the AddStudentAction class, and then, on success, the listStudents method. The listStudent method calls listStudents() on the AddStudentAction class and uses the .jsp as a view.

Now, right-click on the project name, and then click "Export" and "WAR File" to create a WAR file. T he WAR file is then deployed in Tomcat's webapps directory. Finally, when you start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/student.jsp, the following interface is displayed:

Struts2 Hibernate integration

In the above section, we get a form that enters the value of the new student record, and the following section lists the students in the database. C ontinue to add a new student record, and then press Submit. The screen refreshes and shows you an updated list each time you click Submit.