Struts 2 简明教程
Struts 2 and Hibernate Integration
Hibernate 是一项高性能对象/关系持久性与查询服务,该服务通过开放源代码 GNU Lesser General Public License (LGPL) 获得许可,并可免费下载。在本章中,我们将了解如何将 Struts 2 集成到 Hibernate 中。如果您不熟悉 Hibernate,则可以查看我们的 Hibernate tutorial 。
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
对于本教程,我将使用“struts2_tutorial”MySQL 数据库。我使用用户名“root”和无密码连接到我的机器上此数据库。首先,您需要运行以下脚本。此脚本将创建一个名为 student 的新表格,并在该表格中创建一些记录−
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
接下来让我们创建 hibernate.cfg.xml,这是 Hibernate 的配置文件。
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>
让我们仔细阅读 Hibernate 配置文件。首先,我们声明了我们使用的是 MySQL 驱动程序。然后我们声明了用于连接到数据库的 jdbc url。然后我们声明了连接的用户名、密码和池大小。我们还表明,通过将“show_sql”切换为 true,我们希望看到日志文件中的 SQL。请仔细阅读 Hibernate 教程以了解这些属性的含义。
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.
最后,我们将映射类设置为 com.tutorialspoint.hibernate.Student,我们将在本章中创建此类。
Finally, we set the mapping class to com.tutorialspoint.hibernate.Student which we will create in this chapter.
Envrionment Setup
接下来,您需要为该项目引入许多 jar。附件是所需 JAR 文件的完整列表的屏幕截图−
Next you need a whole lot of jars for this project. Attached is a screenshot of the complete list of JAR files required −
大多数 JAR 文件可以作为 Struts 分发的一部分获得。如果您已安装 Glassfish、WebSphere 或 JBoss 等应用服务器,则可以从应用服务器的 lib 文件夹中获取剩余 jar 文件。如果没有,则可以单独下载这些文件−
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 −
-
Hibernate jar files − Hibernate.org
-
Struts hibernate plugin − Struts hibernate plugin
-
JTA files − JTA files
-
Dom4j files − Dom4j
-
log4j files − log4j
其余文件,您应该可以从 Struts2 分发中获取。
Rest of the files, you should be able to get from your Struts2 distribution.
Hibernate Classes
现在,让我们为 Hibernate 集成创建必要的 Java 类。以下是 Student.java 的内容 −
Let us now create required java classes for the hibernate integration. Following is 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;
}
}
这是一个 POJO 类,它根据 Hibernate 规范表示 student 表。它具有与学生表中列名称相对应的 id、firstName 和 lastName 三个属性。接下来,让我们按照如下方式创建 StudentDAO.java 文件 −
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);
}
}
StudentDAO 类是 Student 类的 data access layer(数据访问层)。它具有用于列出所有学生以及保存新学生记录的方法。
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
以下文件 AddStudentAction.java 定义了我们的操作类。这里有两种操作方法 - execute() 和 listStudents()。execute() 方法用于添加新的学生记录。我们使用 dao 的 save() 方法实现这一功能。
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.
另一个方法 listStudents() 用于列出学生。我们使用 dao 的 list 方法获取所有学生的列表。
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;
}
}
您会注意到我们正在实现 ModelDriven 接口。当您的操作类用于处理具体模型类(例如 Student),而不是各个属性(例如 firstName、lastName)时,就会使用它。ModelAware 接口要求您实现一种方法来返回模型。在我们的案例中,我们返回“student”对象。
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
现在,让我们使用以下内容创建 student.jsp 视图文件 −
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>
student.jsp 非常简单明了。在顶部部分,我们有一个提交给“addStudent.action”的表单。它接收 firstName、lastName 和 marks。因为 addStudent 操作绑定到 ModelAware “AddSudentAction”,所以会自动创建一个 student bean,其中包含 firstName、lastName 和 marks 的值自动填充。
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.
在底部部分,我们浏览学生列表(见 AddStudentAction.java)。我们遍历列表并在表格中显示名字、姓氏和分数的值。
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
我们使用 struts.xml 将所有内容放在一起 −
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>
此处需要关注的一点是,我们的软件包“myhibernate”扩展了名为“hibernate-default”的 Struts2 默认软件包。然后我们声明两个操作:addStudent 和 listStudents。addStudent 在 AddStudentAction 类上调用 execute(),然后在成功后,调用 listStudents 操作方法。
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.
listStudent 操作方法在 AddStudentAction 类上调用 listStudents(),并使用 student.jsp 作为视图。
The listStudent action method calls the listStudents() on the AddStudentAction class and uses the student.jsp as the view.
现在,右键单击项目名称,然后单击 Export > WAR File 以创建 War 文件。然后将此 WAR 部署到 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/student.jsp 。这将生成以下屏幕 −
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 produce the following screen −
在顶部部分,我们获取用于输入新学生记录值的一个表单,底部部分列出了数据库中的学生。继续添加一个新学生记录并按提交。每次您单击“提交”时,屏幕将刷新并向您显示一个更新的列表。
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.