Struts 2 and Hibernate Integration

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. In this chapter. we are going to learn how to achieve Struts 2 integration with Hibernate. If you are not familiar with Hibernate then you can check our Hibernate tutorial.

Database Setup:

For this tutorial, I am going to use the "struts2_tutorial" MySQL database. I connect to this database on my machine using the username "root" and no password. First of all, you need to run the following script. This script creates a new table called student and creates few 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 us create the hibernate.cfg.xml which is the hibernate's configuration file.

<?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.tutorialspoint.com/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="com.tutorialspoint.hibernate.Student" />
</session-factory>
</hibernate-configuration> 

Let us go through the hibernate config file. 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.tutorialspoint.hibernate.Student which we will create in this chapter.

Envrionment Setup:

Next you need a whole lot of jars for this project. Attached is a screenshot of the complete list of JAR files required:

Struts and Hibernate Jars

Most of the JAR files can be obtained as part of your struts distribution. If you have an application server such as glassfish, websphere or jboss installed then you can get the majority of the remaining jar files from the appserver's lib folder. If not you can download the files individually :

Rest of the files, you should be able to get from your struts2 distribution.

Hibernate Classes:

Let us now create required java classes for the hibernate integration. Following the content of Student.java:

package com.tutorialspoint.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 that represents the student table as per Hibernate specification. It has properties id, firstName and lastName which correspond to the column names of the student table. Next let us create StudentDAO.java file as follows:

package com.tutorialspoint.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 for the Student class. It has methods to list all students and then to save a new student record.

Action Class:

Following file AddStudentAction.java defines our action class. We have two action methods here - execute() and listStudents(). The execute() method is used to add the new student record. We use the dao's save() method to achieve this. The other method, listStudents() is used to list the students. We use the dao's list method to get the list of all students.

package com.tutorialspoint.struts2;

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

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.tutorialspoint.hibernate.Student;
import com.tutorialspoint.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 will notice that we are implementing the ModelDriven interface. This is used when your action class is dealing with a concrete model class (such as Student) as opposed to individual properties (such as firstName, lastName). The ModelAware interface requires you to implement a method to return the model. In our case we are returning the "student" object.

Create view files:

Let us now create the student.jsp view file with the following content:

<%@ 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 student.jsp is pretty straightforward. In the top section, we have a form that submits to "addStudent.action". It takes in firstName, lastName and marks. Because the addStudent action is tied to the ModelAware "AddSudentAction", automatically a student bean will be created with the values for firstName, lastName and marks auto populated.

At the bottom section, we go through the students list (see AddStudentAction.java). We iterate through the list and display the values for first name, last name and marks in a table.

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.devMode" value="true" />

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

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

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

</package>

</struts>

The important thing to notice here is that our package "myhibernate" extends the struts2 default package called "hibernate-default". We then declare two actions - addStudent and listStudents. addStudent calls the execute() on the AddStudentAction class and then upon successs,it calls the listStudents action method.

The listStudent action method calls the listStudents() on the AddStudentAction class and uses the student.jsp as the view

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/HelloWorldStruts2/student.jsp. This will give you following screen:

Struts and Hibernate Result

In the top section, we get a form to enter the values for a new student record and the bottom section lists the students in the database. Go ahead and add a new student record and press submit. The screen will refresh and show you an updated list every time you click Submit.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
未来社区的建设背景和需求分析指出,随着智能经济、大数据、人工智能、物联网、区块链、云计算等技术的发展,社区服务正朝着数字化、智能化转型。社区服务渠道由分散向统一融合转变,服务内容由通用庞杂向个性化、服务导向转变。未来社区将构建数字化生态,实现数据在线、组织在线、服务在线、产品智能和决策智能,赋能企业创新,同时注重人才培养和科研平台建设。 规划设计方面,未来社区将基于居民需求,打造以服务为中心的社区管理模式。通过统一的服务平台和应用,实现服务内容的整合和优化,提供灵活多样的服务方式,如推送式、订阅式、热点式等。社区将构建数据与应用的良性循环,提高服务效率,同时注重生态优美、绿色低碳、社会和谐,以实现幸福民生和产业发展。 建设运营上,未来社区强调科学规划、以人为本,创新引领、重点突破,统筹推进、整体提升。通过实施院落+社团自治工程,转变政府职能,深化社区自治法制化、信息化,解决社区治理中的重点问题。目标是培养有活力的社会组织,提高社区居民参与度和满意度,实现社区治理服务的制度机制创新。 未来社区的数字化解决方案包括信息发布系统、服务系统和管理系统。信息发布系统涵盖公共服务类和社会化服务类信息,提供政策宣传、家政服务、健康医疗咨询等功能。服务系统功能需求包括办事指南、公共服务、社区工作参与互动等,旨在提高社区服务能力。管理系统功能需求则涉及院落管理、社团管理、社工队伍管理等,以实现社区治理的现代化。 最后,未来社区建设注重整合政府、社会组织、企业等多方资源,以提高社区服务的效率和质量。通过建立社区管理服务综合信息平台,提供社区公共服务、社区社会组织管理服务和社区便民服务,实现管理精简、高效、透明,服务快速、便捷。同时,通过培育和发展社区协会、社团等组织,激发社会化组织活力,为居民提供综合性的咨询和服务,促进社区的和谐发展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值