Struts 2 + Spring + Hibernate集成示例_cyan20115的博客-程序员秘密

技术标签: java  数据库  设计模式  

下载它– Struts2-Spring-Hibernate-Integration-Example.zip

在本教程中,它显示了“ Struts2 + Spring + Hibernate ”之间的集成。 在继续之前,请确保检查以下教程。

  1. Struts 2 + Hibernate集成示例
  2. Struts 2 + Spring集成示例
  3. Struts 1.x + Spring + Hibernate集成示例

请参阅集成步骤摘要:

  1. 获取所有依赖库(很多)。
  2. 注册Spring的ContextLoaderListener以集成Struts 2和Spring。
  3. 使用Spring的LocalSessionFactoryBean集成Spring和Hibernate。
  4. 完成,所有连接。

见关系:

Struts 2 <-- (ContextLoaderListener) --> Spring <-- (LocalSessionFactoryBean) --> Hibernate

这将是一个很长的教程,几乎没有说明,请确保您查看了以上3篇文章以了解详细说明。

教程开始…

它将创建一个带有添加客户和列出客户功能的客户页面。 前端使用Struts 2进行显示, Spring作为依赖项注入引擎, Hibernate进行数据库操作。 开始...

1.项目结构

项目文件夹结构。

Struts2 Spring Hibernate Project Structure
Struts2 Spring Hibernate Project Structure

2. MySQL表脚本

客户的表脚本。

DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3,依赖库

本教程要求许多依赖库。

Struts2…

<!-- Struts 2 -->
        <dependency>
	    <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-core</artifactId>
	    <version>2.1.8</version>
        </dependency>
	<!-- Struts 2 + Spring plugins -->
	<dependency>
            <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-spring-plugin</artifactId>
	    <version>2.1.8</version>
        </dependency>

MySQL…

<!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

弹簧…

<!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>2.5.6</version>
	</dependency>

休眠中...

<!-- Hibernate core -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.7.ga</version>
	</dependency>

	<!-- Hibernate core library dependency start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>

	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>

	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
	<!-- Hibernate core library dependency end -->

	<!-- Hibernate query library dependency start -->
	<dependency>
		<groupId>antlr</groupId>
		<artifactId>antlr</artifactId>
		<version>2.7.7</version>
	</dependency>
	<!-- Hibernate query library dependency end -->

4.休眠中...

只需要模型和映射文件,因为Spring将处理Hibernate配置。

Customer.java –为客户表创建一个类。

package com.mkyong.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客户的休眠映射文件。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20 Julai 2010 11:40:18 AM by Hibernate Tools 3.2.5.Beta -->
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
		table="customer" catalog="mkyong">
        <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>

5. Struts 2…

实现Bo和DAO设计模式。 在Spring bean配置文件中,所有的Bo和DAO都将由Spring进行DI。 在DAO中,使其扩展Spring的HibernateDaoSupport以集成Spring和Hibernate集成。

CustomerBo.java

package com.mkyong.customer.bo;

import java.util.List;
import com.mkyong.customer.model.Customer;
 
public interface CustomerBo{
	
	void addCustomer(Customer customer);
	List<Customer> listCustomer();
	
}

CustomerBoImpl.java

package com.mkyong.customer.bo.impl;

import java.util.List;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
 
public class CustomerBoImpl implements CustomerBo{
	
	CustomerDAO customerDAO;
	//DI via Spring
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	//call DAO to save customer
	public void addCustomer(Customer customer){
		customerDAO.addCustomer(customer);
	}
	
	//call DAO to return customers
	public List<Customer> listCustomer(){
		return customerDAO.listCustomer();
	}
}

CustomerDAO.java

package com.mkyong.customer.dao;

import java.util.List;
import com.mkyong.customer.model.Customer;
 
public interface CustomerDAO{
	
	void addCustomer(Customer customer);
	List<Customer> listCustomer();	
	
}

CustomerDAOImpl.java

package com.mkyong.customer.dao.impl;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
 
public class CustomerDAOImpl extends HibernateDaoSupport 
    implements CustomerDAO{
	
	//add the customer
	public void addCustomer(Customer customer){
		getHibernateTemplate().save(customer);
	}
	
	//return all the customers in list
	public List<Customer> listCustomer(){
		return getHibernateTemplate().find("from Customer");		
	}
	
}

CustomerAction.java – Struts2操作不再需要扩展ActionSupport ,Spring会处理它。

package com.mkyong.customer.action;

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

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;
import com.opensymphony.xwork2.ModelDriven;
 
public class CustomerAction implements ModelDriven{

	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
	
	CustomerBo customerBo;
	//DI via Spring
	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}

	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{
		
		//save it
		customer.setCreatedDate(new Date());
		customerBo.addCustomer(customer);
	 
		//reload the customer list
		customerList = null;
		customerList = customerBo.listCustomer();
		
		return "success";
	
	}
	
	//list all customers
	public String listCustomer() throws Exception{
		
		customerList = customerBo.listCustomer();
		
		return "success";
	
	}
	
}

6.春天...

几乎所有配置都在这里完成,Spring专门从事集成工作:)。

CustomerBean.xml –声明Spring的bean:Action,BO和DAO。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 	<bean id="customerAction" class="com.mkyong.customer.action.CustomerAction">
		<property name="customerBo" ref="customerBo" />	
	</bean>

	<bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
		<property name="customerDAO" ref="customerDAO" />
	</bean>
	
   	<bean id="customerDAO" class="com.mkyong.customer.dao.impl.CustomerDAOImpl" >
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
 
</beans>

database.properties –声明数据库详细信息。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password

DataSource.xml –创建一个数据源bean。

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
     <value>WEB-INF/classes/config/database/properties/database.properties</value>
   </property>
</bean>
 
  <bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>
 
</beans>

HibernateSessionFactory.xml –创建一个sessionFactory bean来集成Spring和Hibernate。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
<!-- Hibernate session factory -->
<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>
 
    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>
 
    <property name="mappingResources">
		<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
		</list>
    </property>	
 
</bean>
</beans>

SpringBeans.xml –创建一个核心Spring的bean配置文件,充当中央bean管理。

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
	
	<!-- Database Configuration -->
	<import resource="config/spring/DataSource.xml"/>
	<import resource="config/spring/HibernateSessionFactory.xml"/>
 
	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>
 
</beans>

7. JSP页面

在JSP页面上显示带有Struts 2标签的元素。

customer.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 + Spring + 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="customerAction" method="addCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>
	
		<action name="listCustomerAction"
			class="customerAction" method="listCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>
		
	</package>
	
</struts>

9. Struts 2 +弹簧

要集成Struts 2和Spring,只需注册ContextLoaderListener侦听器类,定义一个“ contextConfigLocation ”参数,以要求Spring容器解析“ SpringBeans.xml ”而不是默认的“ applicationContext.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>
 
  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/classes/SpringBeans.xml</param-value>
  </context-param>
  
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  
</web-app>

10.演示

测试一下: http:// localhost:8080 / Struts2Example / listCustomerAction.action

Struts2 Spring Hibernate Example
Struts2 Spring Hibernate Example

参考

  1. Struts 2 + Hibernate集成示例
  2. Struts 2 + Spring集成示例
  3. 具有完整Hibernate插件的Struts 2 + Hibernate示例
  4. Struts 1.x + Spring + Hibernate集成示例

翻译自: https://mkyong.com/struts2/struts-2-spring-hibernate-integration-example/

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cyan20115/article/details/106552184

智能推荐

Jmeter特殊情况一:登录请求中密码加密的情况_jmeter csv 数据加密_sarah_yff的博客-程序员秘密

转载地址:http://blog.csdn.net/quiet_girl/article/details/50579193如果使用jmeter模拟一个oschina(开源中国)登录请求,普通的登录请求在之前有讲过,这里不再细说,主要是针对加密的密码,面对这种情况,如果使用之前的方法,不能够请求成功,这里需要注意一点,在HTTP信息头管理器里面添加一个元素User-Agent,通

iOS开发-------简易的人物信息浏览器(UISplitViewController分页控制器 与 UIWebView 网页界面)_RITL的博客-程序员秘密

一般来讲,UISplitViewController(分页控制器)是iPad用的很多的控制,而在iPhone中用的很少,因为iPad的屏幕远大于iPhone,但是随着iPhone6 Plus 以及 iPhone6S Plus 的推出,以及手机的定位,这种控制也是需要掌握的,特别是iOS8之后,这个组件的很多东西都有了更新,所以来讲,这个用的也是不少的,那么什么叫做分页控制器呢,用图来解释,也是做的

[js]html实现日历功能_WW_still的博客-程序员秘密

js html css 日历功能html&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt; &lt;meta charset='utf-8'&gt; &lt;link rel='stylesheet' href='外部的css文件路径' /&gt; &lt;title&gt;demo&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;div class='calendar' id='calendar'

Asp.net Log4net 无法显示Log_Farmwang的博客-程序员秘密

log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath(&quot;~/log4net.config&quot;)));需要添加

全国计算机软件与技术报名时间,浙江:全国计算机技术与软件考试报名时间7月1日-15日..._负智年帖的博客-程序员秘密

2004年上半年全国计算机技术与软件专业技术资格(水平)考试成绩揭晓,考生可以通过声讯电话96008811(杭州)或16885103(全省)查询考试卷面成绩,待国家人事部公布考试合格分数线后,办理合格证书。我省下半年该项考试的报名时间是7月1日至15日,有关考试报名详细信息可咨询0571-85118167,或访问网站www.topcheer.cn。取消报考条件据了解,5月23日举行的全国计算机技术...

运行nrm包 nrm ls 时报错无法查询到可选择的镜像源地址的问题及解决方法_nrm use不到指定源_简单 Dan的博客-程序员秘密

node 运行nrm包 nrm ls 时报错无法查询到可选择的镜像源地址问题1.安装 npm install nrm -g2.运行 nrm ls2.1这是正常会显示报错 列如下面形式PS C:\Users\XXX\Desktop\res&gt; nrm lsinternal/validators.js:124 ^[TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received

随便推点

hdfs环境下多台虚拟机中的时间同步问题_hdfs时间同步命令_里格朗咚的博客-程序员秘密

分享两种修改时间的方法一、虚拟机单次有效,重新启动时配置竟丢失。使用SecureCRT可视化软件,将控制台设置为send commands to all session,发送命令:date -s '年-月-日 时:分:秒,如下图:二、.配置时间服务器,集群的其他机器都跟namenode所在机器同步时间,实现永久时间同步,此方法也需要开机自启ntp服务和定时任务1.检查ntp(N...

如何在CentOS 7环境中实现多版本MySQL共存,MySQL5.7与MySQL8.0,MySQL5.6_centos mysql 多版本共存_名字不能随便取的博客-程序员秘密

这里需要使用一个功能是mysqld_multi以我的机器[服务器是阿里云的CentOS7]为例,我是先装的5.7版本,接着又装了5.6和8.0的版本。MySQL5.7的安装如下:先从官网下载二进制的压缩文件wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.30-linux-glibc2.12-x86_64.tar....

关于demo.cpp:(.text.startup+0x8f): undefined reference to `vtable for SlotObject' ,问题探究_:(.text.startup+0x4f4): undefined reference to_Kshine2017的博客-程序员秘密

关于demo.cpp:(.text.startup+0x8f): undefined reference to `vtable for SlotObject’ ,问题探究1、在学习信号和槽的过程中使用了一个小例子,编辑完成之后,却出现了编译报错(标题中提到的)。于是采用了临时的解决办法,将Q_OBJECT注释,信号函数 也被我增加了一定义体。 这样可以顺利的编译,并可以运行。但是之后又遇到了新的问题

mysql root用户不存在_Mysql 刚配置数据库出现用户不存在error_善牧静然的博客-程序员秘密

前几天自己想搭一个简单的ssm框架,用到了mysql数据库,下载安装配置完成后出现了Mysql Error:The user specified as a definer (‘mysql.infoschema’@’localhost’) does not exist’)这样的错误,研究了很多,热门解答都无法解决我的问题。网上的类似问题:The user specified as a definer...

EditText无法获取焦点 获取焦点无法编辑(android:descendantFocusability用法简析 )_zz_mm的博客-程序员秘密

android:descendantFocusability用法简析 开发中很常见的一个问题,项目中的listview不仅仅是简单的文字,常常需要自己定义listview,自己的Adapter去继承BaseAdapter,在adapter中按照需求进行编写,问题就出现了,可能会发生点击每一个item的时候没有反应,无法获取的焦点。原因多半是由于在你自己定义的Item中存在诸如ImageBu

推荐文章

热门文章

相关标签