zoukankan      html  css  js  c++  java
  • 手动加入SSH支持、使用c3p0


    之前做的笔记,如今整理一下。大家有耐心的跟着做就能成功;

    SSH(struts2、spring、hibernate)
    *  struts2
         *  充当mvc的角色
    *  hibernate
         dao层用hibernate技术来实现
    *  spring
        *  spring的声明式事务管理
        *  应用spring的IOC和di做到全然的面向接口编程
    先加入一个数据库做測试用:使用的是mysql5.0

    create database testoa default character set utf8;
    show create database testoa;


    1.新建一个Web Project项目 TestSSH

    2.加入Struts2支持:加入jar包

    struts-2.1.8.1/apps/struts2-blank-2.1.8.1.war/WEB-INF/lib 下的所以jar包
    struts2-core.jar  核心jar包
    xwork-2.jar  xwork核心jar包 
    ognl.jar  ognl表达式 
    freemarker.jar  FreeMarker模板 
    commons-logging.jar  日志
    commons-fileupload.jar  文件上传 
    commons-io.jar  文件上传依赖的包

    配置文件:

    配置Strut2的主过滤器:   将struts-2.1.8.1/apps/struts2-blank-2.1.8.1.war/WEB-INF/web.xml下的以下内容拷贝到项目的web.xml下:

    <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>
    
    拷贝Strut2的主配置文件:
    在struts-2.1.8.1/apps/struts2-blank-2.1.8.1.war/WEB-INF/classes/struts.xml下,
    复制到project的src文件夹下
    改动几个主要的配置:

    <struts>
    	<!-- 配置问开发模式( 显示信息 和 配置文件改动后不须要重新启动) -->
        <constant name="struts.devMode" value="true" />
    	<!-- 配置扩展名为action -->
    	<constant name="struts.action.extension" value="action" />
    </struts>
    
    Struts2的环境加入完了;

    3.加入Hibernate支持

    加入jar包:

    核心jar包hibernate-distribution-3.6.0.Final/hibernate3.jar ;
    hibernate-distribution-3.6.0.Final/lib/ required下的全部包:

    还有hibernate-distribution-3.6.0.Final/lib/jpa/ hibernate-jpa-2.0-api-1.0.0.Final.jar;
    还有hibernate-distribution-3.6.0.Final/lib/ optional /c3p0/ c3p0-0.9.1.jar;
    还有数据库驱动:F:快盘JAVAjdbc mysql-connector-java-5.1.5-bin.jar ;

    加入配置文件:
    主配置文件模版:
    hibernate-distribution-3.6.0.Final/ project/ etc/ hibernate.cfg.xml 复制到项目的src下。
    加入主要的配置:
    <hibernate-configuration>
    	<session-factory>
    
    		<!-- 数据库信息(连接信息写到spring的配置文件里) -->
    		<!-- 方言 -->
    		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
    		<property name="connection.url">jdbc:mysql:///testoa</property>
    		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    		<property name="connection.username">root</property>
    		<property name="connection.password">jerome</property>
    
    		<!-- 其它配置 -->
    		<property name="show_sql">true</property>
    		<property name="hbm2ddl.auto">update</property>
    		
    	</session-factory>
    </hibernate-configuration>
    
    映射文件的模版:User.hbm.xml
    <?

    xml version="1.0"?

    > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hqu.oa.domain"> <class name="User" table="hqu_user"> <id name="id"> <generator class="native" /> </id> <property name="name" /> </class> </hibernate-mapping>

    (在hibernate-distribution-3.6.0.Final/ project 下搜索 *.hbm.xml
    随便选一个符合条件的就能够,复制到项目src下。)

    加入Spring支持:

    加入jar包:


    Spring核心包:
    spring-framework-2.5.6-with-dependencies.zip/spring-framework-2.5.6/dist/spring.jar ;
    依赖的:
    日志:
    lib/jakarta-commons/ commons-logging.jar ;
    面向切面编程(AOP)用到的:(
    /lib/ aspectj/ aspectjrt.jar和aspectjweaver.jar
    和生成代理用的:
    ib/cglib/cglib-nodep-2.1_3.jar ; )
    另一个可加的做MD5加密的 这里面有工具类:
    /lib/ jakarta-commons/ commons-codec.jar ;


    配置文件:

    ( F:Javaspring-framework-2.5.6samplesimagedbwarWEB-INF下的applicationContext.xml

    复制到src。)新建applicationContext.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"
    		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    	<!-- 自己主动扫描与装配bean -->
    	<context:component-scan base-package="com.hqu.oa"></context:component-scan>
    
    </beans>
    
    

    到此都加入ssh完了,接下去開始整合:SSH整合:

    先Spring和Hibernate整合:

    Spring来管理事务,管理sessionFactory applicationContext.xml 做例如以下配置:

    <!-- 自己主动扫描与装配bean -->
    	<context:component-scan base-package="com.hqu.oa"></context:component-scan>
    
    	<!-- 载入外部的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" />

    在src创建jdbc.properties文件 内容为:
    jdbcUrl = jdbc:mysql:///testoa
    driverClass = com.mysql.jdbc.Driver
    username = root
    password = jerome

    这时,hibernate.cfg.xml下的数据连接信息就能够凝视了:

    測试:
    创建SpringTest类 com.hqu.oa.test 下。
    代码例如以下:

    	private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    
    	//測试SessionFactory管理是否正确
    	@Test
    	public void testSessionFactory() throws Exception {
    		SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
    		System.out.println(sessionFactory);
    	}
    
    	//測试事务
    	@Test
    	public void testTransaction() throws Exception {
    
    	}
    
    

    单元測试执行例如以下:
    org.hibernate.impl.SessionFactoryImpl@...

    说明成功;
    測试事务:
    加入Service: TestService在com.hqu.oa.test 下;
    加入一个User实体:User在com.hqu.oa.domain下 :

    	private Long id;
    	private String name;
    
    	public Long getId() {
    		return id;
    	}
    
    	public void setId(Long id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    

    写映射文件:
    将之前的*.hbm.xml复制到com.hqu.oa.domain下:
    改名为 User.hbm.xml :

    <?xml version="1.0"?

    > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hqu.oa.domain"> <class name="User" table="hqu_user"> <id name="id"> <generator class="native" /> </id> <property name="name" /> </class> </hibernate-mapping>


    在hibernate.cfg.xml 导入映射文件:
    <!-- 导入映射文件 -->
    <mapping resource="com/hqu/oa/domain/User.hbm.xml" />

    在TestService 中保存两个用户:

    @Service("testService")
    public class TestService {
    	@Resource
    	private SessionFactory sessionFactory;
    
    	@Transactional
    	public void saveTwoUsers() {
    		Session session = sessionFactory.getCurrentSession();
    		session.save(new User());
    		//int a = 1 / 0;//这里会抛异常
    		session.save(new User());
    	}
    }
    

    在SpringTest单元測试:

    //測试事务
    	@Test
    	public void testTransaction() throws Exception {
    		TestService testService = (TestService) ac.getBean("testService");
    		testService.saveTwoUsers();
    	}
    

    testService 就是上面的 @Service("testService") ;
    測试成功;控制台输出两条插入的语句

    再測试 : 将TestService 的异常代码打开
    单元測试执行。查看数据库没新数据。说明事务成功;
    Spring和Hibernate整合完毕;


    Spring和Struts2整合:

    整合之前写一个action 和整合之后做对照:
    创建action TestAction在com.hqu.oa.test下:

    public class TestAction extends ActionSupport {
    	@Override
    	public String execute() throws Exception {
    		System.out.println("---->>>TestAction.execute()");
    		return "success";
    	}
    }
    

    在struts.xml配置文件配置:

      
    <package name="default" extends="struts-default" namespace="/">
    		<!-- 測试用的action -->
    		<action name="test" class="com.hqu.oa.test.TestAction">
    			<result name="success">/index.jsp</result>
    		</action>
    </package>
    
    

    部署,启动tomcat 浏览器输入:http://localhost:8080/TestSSH/test.action
    控制台输出:---->>>TestAction.execute()
    说明action成功。


    接下来做Spring和Struts2整合:

    加入F:Javastrutsstruts-2.2.1lib下的struts2-spring-plugin-2.2.1.jar;
    这样就自己主动整合了 做例如以下配置:
    在web.xml配置spring监听器:用于在应用程序启时初始化
    ApplicationContext对象。

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

    在TestService上加上注解:

    @Controller
    @Scope("prototype") //多例
    public class TestAction extends ActionSupport {
    	@Override
    	public String execute() throws Exception {
    		System.out.println("---->>>TestAction.execute()");
    		return "success";
    	}
    }
    

    改动struts.xml文件:

    	<package name="default" namespace="/" extends="struts-default">
    		<!-- 測试用的action。当与Spring整合后。class属性写的就是Spring中bean的名称 -->
    		<action name="test" class="testAction">
    			<result name="success">/test.jsp</result>
    		</action>
    	</package>
    

    重动 tomcat 測试。成功;
    Spring和Struts2整合成功。

    三个框架一起用:

    在action调用Service:
    在 TestAction下:

    @Controller
    @Scope("prototype")//多例
    public class TestAction extends ActionSupport {
    	@Resource
    	private TestService testService;
    
    	@Override
    	public String execute() throws Exception {
    		System.out.println("---->>>TestAction.execute()");
    		testService.saveTwoUsers();
    		return "success";
    	}
    }
    

    重新启动tomcat,事务也管用,成功;完毕;

    工作量好大~

    demo 链接:http://pan.baidu.com/s/1mgDqhmS password:zdev

  • 相关阅读:
    【转】Android之四大组件、六大布局、五大存储
    Android O 8.0 奥利奥
    安卓7.1新特性
    那些年我们踩过的坑,SQL 中的空值陷阱!
    8年经验面试官详解 Java 面试秘诀
    Github 第三方授权登录教程
    40个超有趣的Linux命令行彩蛋和游戏
    Synchronized锁在Spring事务管理下,为啥还线程不安全?
    Windows Server 2008 R2文件服务器升级到Windows Server 2016
    牛客练习赛61
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6818193.html
Copyright © 2011-2022 走看看