1、环境搭建(整合spring3.0.5+hibernate3.6.10+struts2.3.8)

来源:互联网 发布:什么是云网络储存硬盘 编辑:程序博客网 时间:2024/05/17 09:08

一、新建工程

工程类型为Web Project,设置默认编码为UTF-8,并创建如下文件夹:
conf文件夹  类型为Source Folder  ,主要是存放配置文件
test文件夹   类型为Source Folder单元测试包


二、搭建Spring环境(spring3.0.5)

1、导包(需导的包分为两类,一类是核心包,一类是依赖包)

   核心包:这个是在spring-framework包中的,在spring 官网即可下

   org.springframework.asm-3.0.5.RELEASE.jar

   org.springframework.core-3.0.5.RELEASE.jar

   org.springframework.beans-3.0.5.RELEASE.jar

   org.springframework.context-3.0.5.RELEASE.jar

   org.springframework.expression-3.0.5.RELEASE.jar

   依赖包:这个需要另外到apache官网上下,主要有:

    com.springsource.org.apache.log4j-1.2.15.jar

    com.springsource.org.apache.commons.logging-1.1.1.jar

    com.springsource.org.apache.commons.collections-3.2.1.jar

2、在conf文件夹下新建一个spring的配置文件,取名随意,这里命名为beans.xml,内容如下:

<?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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd         http://www.springframework.org/schema/aop          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">    <!-- 开启注解驱动支持 --><context:annotation-config /><!-- 开启自动扫描装配 --><context:component-scan base-package="com.charlie.shop" /></beans>


3、测试一下是否搭建成功

新建一个接口HelloInterface

package com.charlie.shop;public interface HelloInterface {public void sayHello();}

实现类 HelloImpl

package com.charlie.shop;public class HelloImpl implements HelloInterface{@Overridepublic void sayHello() {System.out.println("HelloWorld!!!");}}

测试类SpringTest

import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.charlie.shop.HelloInterface;public class SpringTest {@Testpublic void test(){ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");HelloInterface hello = ac.getBean("hello", HelloInterface.class);hello.sayHello();} }

在spring配置文件中加入以下配置

<bean id="hello" class="com.charlie.shop.HelloImpl" />

运行,可以看到在控制台下成功的打印出HelloWorld!!!,这说明搭建成功,但是也看到有红色的提示如下:

log4j:WARN Please initialize the log4j system properly.

这可以通过新建一个配置文件log4j.properties来解决

log4j.properties:

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=error, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ####log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ####log4j.logger.org.hibernate.tool.hbm2ddl=debug### log HQL parse trees#log4j.logger.org.hibernate.hql=debug### log cache activity ####log4j.logger.org.hibernate.cache=debug### log transaction activity#log4j.logger.org.hibernate.transaction=debug### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

三、整合Hibernate(hibernate3.6.10)

1、建数据库

采用utf8字符集编码创建数据库,名为:shop。DDL语句如下:
CREATE DATABASE `shop` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

2、新建一个实体类Buyer,随便先定义三个属性,主要是为了测试是否整合成功用

package com.charlie.shop.domain.user;/** * 这是一个用户实体类 * @author charliezheng@yeah.net * */public class Buyer {private Integer id;private String name;private String password;public Buyer(){}public Buyer(Integer id,String name,String password){this.id = id;this.name = name;this.password = password;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

3、导包

先下载hibernate-distribution-3.6.10.Final,然后解压,导入以下包:

hibernate3.jar

\lib\required文件夹下的所有包

lib\jpa下的包----->使用JPA注解需要用到

另外,还需要加入MySql数据库驱动包和c3p0数据源包

c3p0-0.9.1.jar

mysql-connector-java-5.1.5-bin.jar

最后,还需要以下包

org.springframework.orm-3.0.5.RELEASE.jar

org.springframework.transaction-3.0.5.RELEASE.jar

org.springframework.aop-3.0.5.RELEASE.jar

aopalliance.jar

org.springframework.jdbc-3.0.5.RELEASE.jar

4、新建配置文件

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 数据库信息(连接信息写到spring的配置文件中) --><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><!--连接信息写到spring的配置文件中<property name="connection.url">jdbc:mysql:///shop</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.username">root</property>    <property name="connection.password">123456</property>--><!-- 其他配置 --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><!-- 导入映射配置 --><mapping class="com.charlie.shop.domain.user.Buyer" /></session-factory></hibernate-configuration>

新建一个属性文件存放数据库连接信息

jdbc.properties

jdbcUrl= jdbc:mysql:///shopdriverClass= com.mysql.jdbc.Driverusername= rootpassword= 123456

在spring配置文件beans.xml中读取jdbc.properties,配置数据源,整合hibernate

beans.xml

<?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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd         http://www.springframework.org/schema/aop          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">    <!-- 开启注解驱动支持 --><context:annotation-config /><!-- 开启自动扫描装配 --><context:component-scan base-package="com.charlie.shop" /><!-- 加载外部属性文件jdbc.properties --><context:property-placeholder location="classpath:jdbc.properties" /><!-- 配置数据库连接池c3p0 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><!-- 配置基本信息 --><property name="jdbcUrl" value="${jdbcUrl}"></property><property name="driverClass" value="${driverClass}"></property><property name="user" value="${username}"></property><property name="password" value="${password}"></property><!-- 配置其他一些信息 --><!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --><property name="initialPoolSize" value="3"></property><!--连接池中保留的最小连接数。Default: 3 --><property name="minPoolSize" value="3"></property><!--连接池中保留的最大连接数。Default: 15 --><property name="maxPoolSize" value="5"></property><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --><property name="acquireIncrement" value="3"></property><!--控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:0--><property name="maxStatements" value="8"></property><!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0--><property name="maxStatementsPerConnection" value="5"></property><!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --><property name="maxIdleTime" value="1800"></property></bean><!-- 配置SessionFactory --><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="configLocation" value="classpath:hibernate.cfg.xml"></property></bean><!-- 配置声明式的事务管理(采用基于注解的方式) --><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><tx:annotation-driven transaction-manager="transactionManager" /></beans>


5、用注解方式,将Buyer类声明为实体

package com.charlie.shop.domain.user;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;/** * 这是一个用户实体类 * @author charliezheng@yeah.net * */@Entitypublic class Buyer {private Integer id;private String name;private String password;private String email;public Buyer(){}public Buyer(Integer id,String name,String password){this.id = id;this.name = name;this.password = password;}@Id@GeneratedValuepublic Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(length=50,nullable=false)public String getName() {return name;}public void setName(String name) {this.name = name;}@Column(length=32,nullable=false)public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Column(length=50,nullable=false)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}

6、编写测试方法

@Testpublic void testHibernate(){ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");}

7、运行,成功,可以看到数据库中新建了一张有buyer

8、在web.xml中配置监听器

<!-- 配置Spring的监听器,用于初始化ApplicationContext对象 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:beans.xml</param-value></context-param>


四、整合Struts2(struts2.3.8)

1、导包 

把struts-2.3.8\apps\struts2-blank\WEB-INF\lib文件夹下的所有包导入到工程中

添加struts2-spring整合插件的jar:${Struts2_Home}/lib/struts2-spring-plugin-2.3.8.jar

2、在web.xml中配置struts2的Filter

<!-- 配置Struts2的主过滤器 --><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>
3、新建struts2的配置文件struts.xml

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><!-- 开启开发模式 --><constant name="struts.devMode" value="true" /><!-- 设置扩展名为action --><constant name="struts.action.extension" value="action" /><package name="default" namespace="/" extends="struts-default">   <action name="hello">     <result>        /hello.jsp     </result>   </action></package></struts>





五、附录

SSH整合所需jar包和配置文件


原创粉丝点击