ssh框架搭建

完整的項目結構如左圖所示。所需jar包如左圖所示。


接下來開始搭建項目:

1、配置struts環境

1.1、導入struts2所需jia包

1.2、在web.xml中配置struts過濾器(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">  
    <!-- 配置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>  
    <!--  配置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>  
    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>
 


1.3、導入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">  
       
    </package>  
      
</struts>


2、配置hibernate環境

2.1創建數據庫



2.2導入hibernate所需的jar包

2.3導入hibernate的配置文件
2.3.1hibernate.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>  
        
        <!-- 配置數據庫方言 -->  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <!-- 根據映射產生表結構的類型:  
            create-drop:木有表結構創建,下次啓動時刪除重新創建。適合學習階段  
            create:只做創建  
            update:探測表結構夠的變化,對於數據庫沒有的,進行更新操作。適合學習階段  
            validate:對比與數據庫的結構  
         -->  
        <property name="hibernate.hbm2ddl.auto">update</property>  
        <!-- 顯示sql語句及格式:開發調試階段非常有用 -->  
        <property name="hibernate.show_sql">true</property>  
        <property name="hibernate.format_sql">true</property>  
          
        <!-- 告知映射文件 -->  
        <mapping resource="com/lr/domain/Person.hbm.xml"/>  
        
        
    </session-factory>  
</hibernate-configuration> 

2.3.2 新建一個Person類,建立一個Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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.lr.domain">  
      <class name="Person">  
        <id name="id">  
            <generator class="native"/>  
        </id>  
        <property name="name"/>  
    </class>
</hibernate-mapping> 

3、配置spring環境

3.1 導入spring所需jar包

3.2 導入applicationContext.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  6.                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  7.                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  8.     <!-- 自動掃描與裝配bean -->  
  9.     <context:component-scan base-package="com.lr"></context:component-scan>  
  10.     
  11. </beans>  


4、接下來開始整合

4.1 spring與hibernate整合
spring來管理sessionFactory和事務

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>  
        
        <!-- 配置數據庫方言 -->  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <!-- 根據映射產生表結構的類型:  
            create-drop:木有表結構創建,下次啓動時刪除重新創建。適合學習階段  
            create:只做創建  
            update:探測表結構夠的變化,對於數據庫沒有的,進行更新操作。適合學習階段  
            validate:對比與數據庫的結構  
         -->  
        <property name="hibernate.hbm2ddl.auto">update</property>  
        <!-- 顯示sql語句及格式:開發調試階段非常有用 -->  
        <property name="hibernate.show_sql">true</property>  
        <property name="hibernate.format_sql">true</property>  
          
        <!-- 告知映射文件 -->  
        <mapping resource="com/lr/domain/Person.hbm.xml"/>  
        
        
    </session-factory>  
</hibernate-configuration> 


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.lr"></context:component-scan>

<!-- 導入外部的properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 指定hibernate的配置文件位置 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- 配置c3p0數據庫連接池 -->
<property name="dataSource">
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 數據連接信息 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${user}"></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>
</property>
</bean> 
<bean id="testAction" class="com.lr.test.TestAction" 
   scope="prototype">
</bean>
<!-- 配置聲明式事務管理(採用註解的方式) -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
</beans>


jdbc.properties
jdbcUrl = jdbc:mysql:///myssh
driverClass = com.mysql.jdbc.Driver
user = root
password = lirui

5、測試spring

springTest.java
測試sessionFactory
package com.lr.test;

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//測試sessionFactory
@Test
public void testSessionFactory(){
SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
System.out.println(sessionFactory);
}
}
使用junit測試,返回一個sessionFactory的地址。

Person.java
package com.lr.domain;

public class Person {

private Long id;
private String name;

public Person(){}
public Person(Long id, String name) {
this.id = id;
this.name = 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;
}
}

Person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.lr.domain">  
      <class name="Person">  
        <id name="id">  
            <generator class="native"/>  
        </id>  
        <property name="name"/>  
    </class>
</hibernate-mapping> 

測試事務
TestService.java
package com.lr.test;

import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lr.domain.Person;

@Service("testService")
public class TestService {

@Resource
private SessionFactory sessionFactory;
@Transactional
public void saveTwoUser(){
Session currentSession = sessionFactory.getCurrentSession();
currentSession.save(new Person());
}
}





6、spring與sturts整合

整合之前:
TestAction.java
package com.lr.test;

import javax.annotation.Resource;
import com.opensymphony.xwork2.ActionSupport;

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

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,當與Spring整合後,class屬性寫的就是bean的名稱-->  
        <action name="test" class="com.lr.test.testAction">  
            <result name="success">/test.jsp</result>  
        </action>  
    </package>  
</struts>

test.jsp
<%@ 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>Insert title here</title>
</head>
<body>
<h2>你好</h2>
</body>
</html>


導入struts2-spring-plugin-2.1.8.1.jar包,完成struts和spring的整合

testAction.java

package com.lr.test;

import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import com.opensymphony.xwork2.ActionSupport;

@Controller  
@Scope("prototype") 
public class TestAction extends ActionSupport {

@Resource  
    private TestService testService;
@Override
public String execute() throws Exception{
System.out.println("-------->testAction");
testService.saveTwoUser();
return "success";
}
}
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,當與Spring整合後,class屬性寫的就是bean的名稱-->  
        <action name="test" class="testAction">  
            <result name="success">/test.jsp</result>  
        </action>  
    </package>     
</struts> 

在瀏覽器上運行:http://localhost:8080/xbmuoa/test.action


完成ssh框架的整合。