hibernate是一个高性能的对象/关系持久性和查询服务许可下的开源gnu通用公共许可证(lgpl),并免费下载。在这一章中,我们要学习如何实现struts2与hibernate集成。如果你不熟悉与hibernate,那么可以查看我们的hibernate教程。
在本教程中,我会使用“struts2_tutorial”mysql数据库。我连接到我的机器上使用这个数据库的用户名“root”,并且没有密码。首先,你需要运行下面的脚本。此脚本创建称为student ,并创建一个新的表,此表中的记录数:
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的配置文件hibernate.cfg.xml中。
<?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.h3.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.h3.hibernate.student" /> </session-factory> </hibernate-configuration>
让我们通过hibernate的配置文件。首先,我们正在使用的mysql驱动程序。然后,我们声明 jdbc url连接到数据库。然后,声明连接的用户名,密码以及池的大小。我们也表示,我们希望“show_sql”转向真正看到sql的日志文件中。请经过hibernate教程,了解这些属性是什么意思。最后,我们设置了的映射类com.h3.hibernate.student,我们将本章中创建。
接下来,这个项目需要一大堆的jar文件。附所需的jar文件的完整列表的截图:
大部分的jar文件可以作为struts的分布的一部分。如果有一个如glassfish应用服务器,websphere或jboss安装,那么可以得到的大部分jar文件从应用服务器的lib文件夹。如果没有,可以单独下载的文件:
hibernate jar files - hibernate.org
struts hibernate plugin - struts hibernate plugin
jta files- jta files
dom4j files - dom4j
slf4j files - slf4j
log4j files - log4j
其余的文件,应该能够从struts2的分发得到。
现在让我们来创建hibernate集成所需的java类。以下内容student.java:
package com.h3.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的规范表。它拥有属性id,firstname和lastname学生表中的列名对应。接下来让我们创建studentdao.java文件如下:
package com.h3.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类,学生类是数据访问层。它有一些方法来列出所有学生,然后保存一个新的学生记录。
以下文件addstudentaction.java定义我们的动作类。我们这里有两个动作方法 - execute() 和 liststudents()。 execute()方法是用来添加新的学生记录。使用dao的save()方法来实现这一目标。另一种方法,liststudents()用来列出学生。我们使用dao的的列表方法得到所有学生的名单。
package com.h3.struts2; import java.util.arraylist; import java.util.list; import com.opensymphony.xwork2.actionsupport; import com.opensymphony.xwork2.modeldriven; import com.h3.hibernate.student; import com.h3.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接口你会注意到,这是用来当你的操作类处理一个具体的模型类(如学生),而不是个人属性(如名字,姓氏)。的modelaware接口需要实现的方法,以返回到模型。在我们的例子中,我们返回“学生”对象。
现在让我们创建student.jsp视图文件包含以下内容:
<%@ 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”。这需要在名字,姓氏和备注。因为addstudent 动作,自动绑到modelaware的“addsudentaction”,将创建一个学生bean的名字,姓氏和标记自动填充的值。
在底部,我们去通过的学生名单(见addstudentaction.java)。我们遍历列表和显示的值在表中的姓氏,名称和备注。
让我们把它放在一起使用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.h3.struts2.addstudentaction"> <result name="success" type="redirect"> liststudents </result> </action> <action name="liststudents" method="liststudents" class="com.h3.struts2.addstudentaction"> <result name="success">/students.jsp</result> </action> </package> </struts>
这里要注意的最重要的事情是,我们包函“myhibernate”扩展struts2默认包称为“hibernate-default”。然后我们声明两个动作 - addstudent和liststudents。 addstudent调用execute()上addstudentaction类,然后,它调用liststudents操作方法successs。
liststudent动作方法调用liststudents()上addstudentaction类作为视图,并使用student.jsp
现在右击项目名称,并单击export > war 文件创建一个war文件。然后部署这个war在tomcat的webapps目录下。最后,启动tomcat服务器和尝试访问url http://localhost:8080/helloworldstruts2/student.jsp。这会给你以下画面:
在上面的部分,我们得到的一种形式,进入一个新的学生记录和底部列出了学生在数据库中的值。继续并添加一个新的学生记录,按提交。屏幕将刷新并显示您的更新列表。