Www.helper3.com
热门关键字: php net javascript java
Struts2基础 专题
专题目录
您的位置:java > Struts2基础专题 > Struts2+Hibernate集成实例
Struts2+Hibernate集成实例
作者:--    发布时间:2019-11-20 10:18:19
在 struts2 中,没有官方的插件集成hibernate框架。但是,可以通过以下步骤解决方法:
  1. 注册一个自定义的 servletcontextlistener
  2. 在 servletcontextlistener 类, 初始化hibernate会话,并将其存储到servlet上下文。
  3. 在动作类, 可以通过servlet上下文的hibernate会话,并执行任务正常的hibernate操作。
请参阅它们的关系:
struts 2 <-- (servlet context) ---> hibernate <-----> database  

在本教程中,在struts中2开发我们显示了一个简单的客户模块(添加和列表功能),并使用 hibernate 进行数据库操作。使用上述部分机制集成(存储和检索在servlet上下文hibernate的session)。

1. 工程目录结构

来看看这个完整的项目文件夹结构。

2. mysql表结构脚本

创建一个客户(customer)表。下面是sql表脚本。
create table `customer` (
  `customer_id` bigint(20) unsigned not null auto_increment,
  `name` varchar(45) not null,
  `address` varchar(255) not null,
  `create_date` datetime not null,
  primary key (`customer_id`)
) engine=innodb auto_increment=2 default charset=utf8;

4. hibernate 相关配置

hibernate的模型和配置的东西。

customer.java – 创建客户表对应的一个类。

package com.h3.customer.model;

import java.util.date;

public class customer implements java.io.serializable {

	private long customerid;
	private string name;
	private string address;
	private date createddate;

	//getter and setter methods
}

customer.hbm.xml – hibernate映射文件客户表。

<?xml version="1.0"?>
<!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.h3.customer.model.customer" 
	table="customer" catalog="h3">

        <id name="customerid" type="java.lang.long">
            <column name="customer_id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="address" not-null="true" />
        </property>
        <property name="createddate" type="timestamp">
            <column name="created_date" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

hibernate.cfg.xml – hibernate数据库配置文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-configuration public
"-//hibernate/hibernate configuration dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/h3</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">false</property>
    <mapping resource="com/h3/customer/hibernate/customer.hbm.xml" />
  </session-factory>
</hibernate-configuration>

5. hibernate servletcontextlistener

创建一个类 servletcontextlistener, 并初始化hibernate会话,并将其存储到servlet上下文。

hibernatelistener .java

package com.h3.listener;

import java.net.url;

import javax.servlet.servletcontextevent;
import javax.servlet.servletcontextlistener;

import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
 
public class hibernatelistener implements servletcontextlistener{
 
    private configuration config;
    private sessionfactory factory;
    private string path = "/hibernate.cfg.xml";
    private static class clazz = hibernatelistener.class;
 
    public static final string key_name = clazz.getname();

	public void contextdestroyed(servletcontextevent event) {
	  //
	}
 
	public void contextinitialized(servletcontextevent event) {
 
	 try { 
	        url url = hibernatelistener.class.getresource(path);
	        config = new configuration().configure(url);
	        factory = config.buildsessionfactory();
	         
	        //save the hibernate session factory into serlvet context
	        event.getservletcontext().setattribute(key_name, factory);
	  } catch (exception e) {
	         system.out.println(e.getmessage());
	   }
	}
}
在 web.xml 文件中注册监听器。

web.xml

<!doctype web-app public
 "-//sun microsystems, inc.//dtd web application 2.3//en"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>struts 2 web application</display-name>
  
  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
	  org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter
	</filter-class>
  </filter>
  
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <listener>
    <listener-class>
	  com.h3.listener.hibernatelistener
    </listener-class>
  </listener>
 
</web-app>

6. action

在动作类, 可以通过servlet上下文的hibernate会话和执行正常的hibernate任务。

customeraction.java

package com.h3.customer.action;

import java.util.arraylist;
import java.util.date;
import java.util.list;

import org.apache.struts2.servletactioncontext;
import org.hibernate.session;
import org.hibernate.sessionfactory;

import com.h3.customer.model.customer;
import com.h3.listener.hibernatelistener;
import com.opensymphony.xwork2.actionsupport;
import com.opensymphony.xwork2.modeldriven;
 
public class customeraction extends actionsupport 
	implements modeldriven{

	customer customer = new customer();
	list<customer> customerlist = new arraylist<customer>();
	
	public string execute() throws exception {
		return success;
	}

	public object getmodel() {
		return customer;
	}
	
	public list<customer> getcustomerlist() {
		return customerlist;
	}

	public void setcustomerlist(list<customer> customerlist) {
		this.customerlist = customerlist;
	}

	//save customer
	public string addcustomer() throws exception{
		
		//get hibernate session from the servlet context
		sessionfactory sessionfactory = 
	         (sessionfactory) servletactioncontext.getservletcontext()
                     .getattribute(hibernatelistener.key_name);

		session session = sessionfactory.opensession();

		//save it
		customer.setcreateddate(new date());
	 
		session.begintransaction();
		session.save(customer);
		session.gettransaction().commit();
	 
		//reload the customer list
		customerlist = null;
		customerlist = session.createquery("from customer").list();
		
		return success;
	
	}
	
	//list all customers
	public string listcustomer() throws exception{
		
		//get hibernate session from the servlet context
		sessionfactory sessionfactory = 
	         (sessionfactory) servletactioncontext.getservletcontext()
                     .getattribute(hibernatelistener.key_name);

		session session = sessionfactory.opensession();

		customerlist = session.createquery("from customer").list();
		
		return success;
	
	}	
}

7. jsp 页面

jsp页面用来添加和列出的客户。

customer.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>struts 2 + hibernate integration example</h1>

<h2>add customer</h2>
<s:form action="addcustomeraction" >
  <s:textfield name="name" label="name" value="" />
  <s:textarea name="address" label="address" value="" cols="50" rows="5" />
  <s:submit />
</s:form>

<h2>all customers</h2>

<s:if test="customerlist.size() > 0">
<table border="1px" cellpadding="8px">
	<tr>
		<th>customer id</th>
		<th>name</th>
		<th>address</th>
		<th>created date</th>
	</tr>
	<s:iterator value="customerlist" status="userstatus">
		<tr>
			<td><s:property value="customerid" /></td>
			<td><s:property value="name" /></td>
			<td><s:property value="address" /></td>
			<td><s:date name="createddate" format="dd/mm/yyyy" /></td>
		</tr>
	</s:iterator>
</table>
</s:if>
<br/>
<br/>

</body>
</html>

8. 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="default" namespace="/" extends="struts-default">
		
    <action name="addcustomeraction" 
	class="com.h3.customer.action.customeraction" method="addcustomer" >
       <result name="success">pages/customer.jsp</result>
    </action>
	
    <action name="listcustomeraction" 
	class="com.h3.customer.action.customeraction" method="listcustomer" >
        <result name="success">pages/customer.jsp</result>
    </action>		

  </package>	
</struts>

9. 实例测试执行

访问客户模块:http://localhost:8080/struts2hibernate/listcustomeraction.action

在名称和地址字段填写,点击提交按钮,插入的客户的详细信息会马上列出结果。

参考

  1. struts2 + hibernate使用“full hibernate plugin"集成
  2. servletcontextlistener 文档
  3. struts + hibernate集成实例
代码下载 - http://pan.baidu.com/s/1hqhqj7a
所有评论

loading......

滚动到顶部 滚动到底部
合作联系(微信):
www.helper3.com
关于本站:
宗旨
网站备案号:
粤ICP备17073857号-1

声明:
本站部分内容来自网络,如您发现本站内容侵害到您的利益,请联系本站管理员处理。