Struts2+Hibernate3+Spring3简单整合练习

2024-01-05 04:58

本文主要是介绍Struts2+Hibernate3+Spring3简单整合练习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

第一步:Struts2环境的搭建

    1.从http://struts.apache.org/2.1.8.1/index.html下载struts2.1.8。如果可能的话尽量下载110mb的那个。虽然大了点但包含了源码、文档和示例。

 

    2.打开Eclipse,建立WEB项目,名称为S2SH。将struts2.1.8解压后的lib目录下的commons-fileupload-1.2.1.jarcommons-io-1.3.2.jar、freemarker-2.3.15.jar、ognl-2.7.3.jar、struts2-core-2.1.8.1.jar、xwork-core-2.1.6.jar这6个jar包拷贝到建立的web项目lib目录下。

 

    3.添加Struts2的过滤器。打开web.xml修改如下。

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><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><dispatcher>FORWARD</dispatcher><dispatcher>REQUEST</dispatcher></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>

 

    4.在类路径下建立struts.xml文件,方便起见可以直接拷贝struts2-blank-2.1.8.1下空的struts.xml。

 

    5.添加类User和UserAction,如下。为了我们的action能有更多的功能,可以继承ActionSupport,覆盖其execute方法

    User.class如下

package test.s2sh;
public class User {private String userName;private String sex;private Integer age;private String address;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}
}


UserAction.class如下

 

package test.s2sh;
public class UserAction{private User user;public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String execute() throws Exception {user = new User();user.setAddress("地球");user.setAge(25);user.setSex("男");user.setUserName("中国");return "success";}
}

    6.把写好的action配置到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><package name="default" namespace="/" extends="struts-default"><action name="user" class="test.s2sh.UserAction"><result>WEB-INF/jsp/user.jsp</result></action></package>
</struts>

    7.在WEB-INF目录下建立jsp目录,并添加user.jsp文件。jsp内容如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>s2sh</title></head><body>我的信息如下:<br />姓名:<s:property value="user.userName"/><br />性别:<s:property value="user.sex"/><br />年龄:<s:property value="user.age"/><br />地址:我来自<s:property value="user.address"/><br /></body>
</html>


 

    8.在index.jsp文件中添加<jsp:forward page="user"/>,内容如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>index</title></head><body><jsp:forward page="user"/></body>
</html>

    9.好了,把此工程部署到tomcat6上,打开浏览器访问http://localhost:8080/S2SH/

浏览器显示如下信息:

 

我的信息如下:
姓名:中国 
性别:男 
年龄: 25 
地址:我来自地球

 

   10.现在struts2运行环境搭建完成,特别注意的是<dispatcher>FORWARD</dispatcher>和<dispatcher>REQUEST</dispatcher>不能省略,否则index.jsp将无法访问到UserAction。

 

第二步:struts2+spring3.0整合

   1.下载spring3.0,网址为http://www.springsource.org/download,单击spring Framework 3.0.2.RELEASE下的Download进入下载页面(要填个表单才要下载)。找到下载页面后会有三个下载文件,名字为spring-framework-3.0.2.RELEASE.zip的是要下载的文件。  

 

   2.添加jar包,解压缩下载好的文件找到下面jar包,添加到lib目录下

       org.springframework.asm-3.0.2.RELEASE.jar

       org.springframework.beans-3.0.2.RELEASE.jar

       org.springframework.context-3.0.2.RELEASE.jar

       org.springframework.core-3.0.2.RELEASE.jar

       org.springframework.expression-3.0.2.RELEASE.jar

       org.springframework.web-3.0.2.RELEASE.jar

     在下载的struts2.1.8下找到下面jar文件,添加进lib目录下

       struts2-spring-plugin-2.1.8.1.jar

       commons-logging-api-1.1.jar

   

    3.修改web.xml文件添加spring的监听器,配置如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><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><dispatcher>FORWARD</dispatcher><dispatcher>REQUEST</dispatcher></filter-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
 

    4.在WEB-INF目录下添加applicationContext.xml,把UserAction交给Spring管理。内容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="userActionBean" class="test.s2sh.UserAction"/>
</beans>

     5.修改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.objectFactory" value="spring"/><package name="default" namespace="/" extends="struts-default"><action name="user" class="userActionBean"><result>WEB-INF/jsp/user.jsp</result></action></package>
</struts>

     6.至此所有配置都已完成,再次运行项目。如果成功则页面显示和上一步相同,内容如下

 

我的信息如下:
姓名:中国 
性别:男 
年龄: 25 
地址:我来自地球

     7.现在只是简单地实现了将action交由Spring管理。Spring的作用当然不止是这样。

 

第三步:将Spring3.0和hibernate的整合

    1.从官网下载hibernate,网址为http://sourceforge.net/projects/hibernate/files/hibernate3/3.5.1-Final/ 

 

     2.添加jar文件,解压缩hibernate3.5文件找到下面jar包,添加进lib目录

        antlr-2.7.6.jar 

        commons-collections-3.1.jar 

        dom4j-1.6.1.jar 

        javassist-3.9.0.GA.jar 

        jta-1.1.jar

        slf4j-api-1.5.8.jar 

        hibernate3.jar

   一下两个jar包在Spring3.0的spring-framework-3.0.2.RELEASE-dependencies.zip里面包含,不想从官网下的可以从我提供的附件中获得

        com.springsource.org.aopalliance-1.0.0.jar  这个可以在struts2.1.8的lib下找到。

        com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

   在Spring3.0的dist目录下找到如下jar包,添加进lib目录

        org.springframework.jdbc-3.0.2.RELEASE.jar

        org.springframework.aop-3.0.2.RELEASE.jar

        org.springframework.orm-3.0.2.RELEASE.jar

        org.springframework.transaction-3.0.2.RELEASE.jar

   从网上下载slf4j的实现包,还好以前有下载不然又要baidu了。。。

        slf4j-jdk14-1.5.8.jar      

 

   添加数据库驱动文件

       我用的是mysql5,并且在tomcat6的lib目录下以前已经添加了mysql-connector-java-5.1.10-bin.jar驱动,所以可以不用再添加驱动到项目的lib目录。 

   3.修改User类添加id属性以及set、get方法,并添加hibernate的Mapping文件User.hbm.xml,如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="test.s2sh"><class name="User" table="user"><id name="id" column="id"><generator class="native" /></id><property name="userName" /><property name="sex" length="2"/><property name="age" /><property name="address"/></class>
</hibernate-mapping>

      增加UserDao以及实现类UserDaoImpl ,内容如下

 

package test.s2sh;
public interface UserDao {public void addUser(User user);
}

package test.s2sh;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{public void addUser(User user) {this.getHibernateTemplate().save(user);}
}

      4.修改action,因为内容太简单了,所以就直接调用DAO了。内容如下

package test.s2sh;
public class UserAction{private User user;private UserDao userDao;//增加一个set方法,让spring注入public void setUserDao(UserDao userDao) {this.userDao = userDao;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String execute() throws Exception {user = new User();user.setAddress("地球");user.setAge(25);user.setSex("男");user.setUserName("中国");userDao.addUser(user);return "success";}
}

    5修改applicationContext.xml,添加对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"xmlns:aop="http://www.springframework.org/schema/aop"  xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 配置数据库连接 --><bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- jdbc4.0 已经不需要指定驱动的类名了,当然这需要所添加的驱动符合jdbc4.0标准 <property name="driverClassName" value="com.mysql.jdbc.Driver"/>--><property name="url" value="jdbc:mysql://localhost:3306/test"/><property name="username" value="root"/><property name="password" value="123456"/></bean><!-- 集成hibernate的配置文件 --><bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mappingResources"><list><value>test/s2sh/User.hbm.xml</value></list></property><property name="hibernateProperties"><value>hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialecthibernate.show_sql=truehibernate.hbm2ddl.auto=create-drop</value></property></bean><!-- 配置事务管理器 --><bean name="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="add*" propagation="REQUIRED"/></tx:attributes></tx:advice><aop:config><!-- 因为逻辑太简单了,所以就把事务配置在了Dao层。实际使用中是不会在dao层配置事务的。 --><aop:advisor advice-ref="txAdvice" pointcut="execution(* test.s2sh.UserDao.*(..))"/></aop:config><!-- 这里使用了set方法进行注入--><bean name="userDao" class="test.s2sh.UserDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean><bean name="userActionBean" class="test.s2sh.UserAction"><property name="userDao" ref="userDao"/></bean>
</beans>

   6.然后把工程布置到tomcat下,访问http://localhost:8080/S2SH/ ,显示输入如下

我的信息如下:
姓名:中国
性别:男
年龄:25
地址:我来自地球
已成功保存信息至数据库,返回id为:1


转自:http://314858770.iteye.com/blog/654909

这篇关于Struts2+Hibernate3+Spring3简单整合练习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/571709

相关文章

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过

Springboot整合Redis主从实践

《Springboot整合Redis主从实践》:本文主要介绍Springboot整合Redis主从的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言原配置现配置测试LettuceConnectionFactory.setShareNativeConnect

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st