环境:jdk1.7 spring3.2.2 struts2.3.15 hibernate3.3.2 proxool 0.9.1
一 SSH简介
SSH架构指的是使用Struts 2、Spring和Hibemate这3个框架来搭建项目的主体架构,这也是目前流行的项目架构。
Struts 2和Hibernate是两个独立的框架,它们之间没有直接的联系。由于Spring框架提供了对象管理,切面编程等非常实用的功能,如果把Struts 2和Hibernate的对象交给Spring容器进行解耦合管理,不仅能大大增强系统的灵活性,便于功能扩展,还能通过Spring提供的服务简化编码,减少开发工作量,提高开发效率。所以SSH框架整合其实就是分别实现Spring与Struts 2、Spring与Hibernate的整合,而实现整合的只要工作就是把Struts 2、Hibernate中的对象配置到Spring容器中,交给Spring来管理。
二 整合思路分析
JavaWeb应用开发经过多年的发展,已经形成了一套成熟的程序结构。一个典型的使用了Struts2和Hibernate框架的应用,其结构如图所示。
Struts2的主控制器接到请求后会调用特定的Action。在Action中又会调用业务类(Service)来执行业务逻辑。如果需要访问数据库,业务类则会继续调用数据库访问对象(DAO)。而在数据库访问对象中,则需要调用SessionFactory提供的Session实例的方法执行具体操作。Session最终会通过Connection等JDBC API来实现增删该查等操作,而Connction可以通过配置的数据源(DataSource)来提供。
通过以上分析不难看出,程序执行过程中依赖的方向是Action--->Service--->DAO--->Session(由SessionFactory提供)--->Connection(由DataSource提供),当使用Spring IOC进行依赖管理时,依赖注入的方向则正好与相反。下面通过JBOA系统中的用户登录功能展示SSH架构的搭建过程。
使用SSH架构实现JBOA系统的登录功能。
根据之前的分析,我们将按照DataSource--->SessionFactory--->DAO--->Service--->Action的顺序实现依赖注入,亦即先完成Spring和Hibernate的整合,再对业务层进行整合,最后完成Spring和Strtus 2的整合。
===============================
三 代码
需要的jar包(最精简)
代码结构
==================web.xml========================
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<error-page>
<error-code>404</error-code>
<location>/Err404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/Err500.html</location>
</error-page>
<!-- 解决延迟加载的问题start -->
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>myFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>*.php</url-pattern>
</filter-mapping>
<!-- 解决延迟加载的问题end -->
<!--struts2 config start -->
<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>
<!--struts2 config end -->
<!-- proxool连接池的配置start -->
<servlet>
<servlet-name>proxool</servlet-name>
<servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>proxool</servlet-name>
<url-pattern>/proxool.wps</url-pattern>
</servlet-mapping>
<!-- proxool连接池的配置end -->
<!--spring config start -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring config end -->
<!-- 加载日志start -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 加载日志end -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
===========连接池配置文件proxool.xml=================
<?xml version="1.0" encoding="UTF-8"?>
<!-- the proxool configuration can be embedded within your own application's.
Anything outside the "proxool" tag is ignored. -->
<datasource-config>
<!--
<proxool>
<alias>proxool_sqlserver2008</alias>
<driver-url>jdbc:sqlserver://localhost:1433;databaseName=petdb</driver-url>
<driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
<driver-properties>
<property name="user" value="sa" />
<property name="password" value="123456" />
</driver-properties>
<maximum-connection-count>100</maximum-connection-count>
<minimum-connection-count>2</minimum-connection-count>
<maximum-active-time>300000</maximum-active-time>
<maximum-new-connections>10</maximum-new-connections>
<house-keeping-sleep-time>90000</house-keeping-sleep-time>
<statistics>1m,15m,1d</statistics>
<house-keeping-test-sql>select GETDATE()</house-keeping-test-sql>
</proxool>
-->
<proxool>
<alias>proxool_mysql</alias>
<driver-url>jdbc:mysql://localhost:3306/studentdb?autoReconnect=true</driver-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver-properties>
<property name="user" value="root" />
<property name="password" value="sasa" />
</driver-properties>
<!-- 允许最大连接数,超过了这个连接,再有请求时,就排在队列中等候 -->
<maximum-connection-count>100</maximum-connection-count>
<!-- 最小连接数 -->
<minimum-connection-count>5</minimum-connection-count>
<!-- 如果检测到某个线程的活动时间大于这个数值.它将会杀掉这个线程 -->
<maximum-active-time>300000</maximum-active-time>
<!-- 指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受-->
<maximum-new-connections>10</maximum-new-connections>
<!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁-->
<house-keeping-sleep-time>90000</house-keeping-sleep-time>
<!-- 连接池使用状况统计 -->
<statistics>1m,15m,1d</statistics>
<!-- 如果发现了空闲的数据库连接,将会用这个语句来测试有效性 -->
<house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
</proxool>
<!--
<proxool>
<alias>proxool_oracle</alias>
<driver-url>jdbc:oracle:thin:@127.0.0.1:1521:orcl?autoReconnect=true</driver-url>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<driver-properties>
<property name="user" value="scott" />
<property name="password" value="tiger" />
</driver-properties>
<maximum-connection-count>100</maximum-connection-count>
<minimum-connection-count>2</minimum-connection-count>
<maximum-active-time>300000</maximum-active-time>
<maximum-new-connections>10</maximum-new-connections>
<house-keeping-sleep-time>90000</house-keeping-sleep-time>
<statistics>1m,15m,1d</statistics>
<house-keeping-test-sql>select sysdate from dual</house-keeping-test-sql>
</proxool>
-->
</datasource-config>
正式运行环境下请把中文注释去掉,否则会报错!
hibernate核心配置文件hibernate.cfg.xml
<!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="proxool.xml">proxool.xml</property>
<property name="proxool.pool_alias">proxool_mysql</property>
<property name="connection.provider_class">
org.hibernate.connection.ProxoolConnectionProvider
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
<property name="hibernate.cache.use_second_level_cache">
true
</property>
<property name="hibernate.cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
缓存配置文件ecache.xml
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="160"
overflowToDisk="true"
/>
<cache name="stu"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
</ehcache>
spring核心配置文件
===================context.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 整合hibernate -->
<bean id="myFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="mappingLocations">
<list>
<value>classpath:mappers/*.hbm.xml</value>
</list>
</property>
</bean>
<bean id="userDao" class="com.obtk.dao.UserDaoImpl">
<property name="sessionFactory" ref="myFactory"></property>
</bean>
<bean id="stuDao" class="com.obtk.dao.StudentDaoImpl">
<property name="sessionFactory" ref="myFactory"></property>
</bean>
<bean id="userBiz" class="com.obtk.biz.UserBiz">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="stuBiz" class="com.obtk.biz.StudentBiz">
<property name="stuDao" ref="stuDao"></property>
</bean>
<!-- 事务配置start -->
<bean id="txManger" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="myFactory"></property>
</bean>
<tx:advice id="txAdvise" transaction-manager="txManger">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="do*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="mycut" expression="execution(* com.obtk.biz.*.*(..))"/>
<aop:advisor advice-ref="txAdvise" pointcut-ref="mycut"/>
</aop:config>
<!-- 事务配置end -->
</beans>
最后是struts的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"struts-2.3.dtd">
<struts>
<constant name="struts.action.extension" value="php"></constant>
<constant name="struts.multipart.saveDir" value="C:\tmp"></constant>
<!-- 最大只能传1m上来 -->
<constant name="struts.multipart.maxSize" value="1048576"></constant>
<package name="ttt" extends="struts-default">
<action name="Login" class="com.obtk.actions.LoginAction">
<result name="success">index.jsp</result>
<result name="input">Login.jsp</result>
</action>
<action name="CheckUser" class="com.obtk.actions.CheckUserAction">
<result name="success" type="stream">
<param name="contentType">text/html</param>
<param name="inputName">bis</param>
</result>
</action>
<action name="Register" class="com.obtk.actions.RegisterAction">
<result name="success">Login.jsp</result>
<result name="input">Register.jsp</result>
</action>
<action name="LoadOne" class="com.obtk.actions.QueryOneStuAction">
<result name="success">ShowOne.jsp</result>
<result name="input">index.jsp</result>
</action>
<action name="QueryStuPage" class="com.obtk.actions.StudentPageAction">
<result name="success">ShowStudents.jsp</result>
<result name="error">Err404.html</result>
</action>
</package>
</struts>