Struts2.3+Spring3.2+Hibernate4.2框架搭建

一、环境

SSH使用的版本:struts2.3.14、spring3.2.2、hibernate4.2.0

数据库:MYSQL

tomcat版本:apache-tomcat-7.0.42

 

二、所需要导入的jar包

2.1 struts2的jar包

  同时,整合hibernate还需要一下jar包:

2.2 spring3的jar包

2.3 hibernate4的jar包

  导入/lib/required文件夹下的所有jar包

  配置连接池需要导入/lib/optional/c3p0文件夹中的所有jar包

  数据库使用的是MYSQL,因此还需要mysql的连接驱动:mysql-connector-java-5.1.22-bin.jar

2.4 用于日志的jar包

log4j-1.2.17.jar,slf4j-api-1.7.5.jar,slf4j-log4j12-1.7.5.jar

2.5 AspectJ相关的jar包

aopalliance-1.0.jar,aspectjrt.jar,aspectjweaver.jar

 

三、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">
    <display-name>BillLogger</display-name>
    
    <!-- WebApp Root -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webapp.root</param-value>
    </context-param>
    
    <!-- Struts2 Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>struts-default.xml,struts-plugin.xml,com/billLogger/resources/struts.xml</param-value>
        </init-param>
    </filter>
    <!-- Struts2 Filter Mapping -->
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Log4j ConfigurationFile Location -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:com/billLogger/resources/log4j.properties</param-value>
    </context-param>

    <!-- Spring Log4j Listener -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- Spring Web Request Listener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

  struts的配置文件struts.xml默认存放路径在/WEB-INF/classes目录下,即将struts.xml放在src的目录下。我这里把配置文件放在com.billLogger.resources包内,因此要在init-param标签设置config的值。

  需要注意的是若设置了<param-name>config</param-name>参数,则struts-default.xml和struts-plugin.xml原来struts2默认加载的文件也要手动指定,否则不会自动加载。

 

四、配置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.devMode" value="true"></constant><!-- default set 
        to false for prod -->

    <package name="bills" namespace="/bills" extends="struts-default">
        <action name="*" class="com.billLogger.actions.bill.{1}">
            <result>/views/bills/{1}.jsp</result>
            <result name="redirect" type="redirect">${redirectUrl}</result>
        </action>
    </package>

    <package name="root-redirect" namespace="/" extends="struts-default">
        <action name="">
            <result type="redirect">bills/Listing.action</result>
        </action>
    </package>
</struts>

五、配置hibernate.cfg.xml

<!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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/moneymanagement</property>
        <property name="connection.username">root</property>
        <property name="connection.password">tyc1234</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable c3p0 connection pooling,beacause hibernate pooling is not prod-ready. 
            Apparently connection.provider_class is needed in hibernate 3+ -->
        <!-- <property name="connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property> -->
        <property name="hibernate.c3p0.min_size">1</property>
        <property name="hibernate.c3p0.max_size">100</property>
        <property name="hibernate.c3p0.idle_test_period">30</property>

        <!-- Echo all ececuted SQLto stdout for debugging -->
        <property name="show_sql">true</property>

        <!-- 对象与数据库表格映像文件 -->
        <mapping resource="com/billLogger/mode/bill.hbm.xml" />
        <mapping resource="com/billLogger/mode/category.hbm.xml" />
    </session-factory>
</hibernate-configuration>

 

  在配置c3p0连接池的时候,hibernate3一定要写上

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>这句话是用于指定hibernate的连接方式,如果没有的话,将不会指定c3p0为hibernate的连接池,c3p0的连接类直接在核心jar包中。在hibernate4中c3p0有专用jar包,这里不需要设置connection.provider_class。

六、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:p="http://www.springframework.org/schema/p" 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.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!-- SessionFactory -->
    <bean id="sessionFactory" scope="singleton" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"<!-- 和hibernate3导入的不同 --> 
    p:configLocation
="classpath:/com/billLogger/resources/hibernate.cfg.xml" /> <!-- TransactionManager --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"<!-- 和hibernate3导入的不同 -->
    p:sessionFactory-ref
="sessionFactory" /> <!-- Spring Advice --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"></tx:method> <tx:method name="*"></tx:method> </tx:attributes> </tx:advice> <!-- Spring Aop Config --> <aop:config> <aop:pointcut id="pointcut" expression=" execution(* com.billLogger.services.*Impl.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /> </aop:config> <!-- Dao --> <bean id="billDao" class="com.billLogger.dao.BillDao"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- Service --> <bean id="billService" class="com.billLogger.services.BillService"> <property name="billDao"> <ref bean="billDao" /> </property> </bean> <!-- Action --> <bean id="billListAction" class="com.billLogger.actions.bill.Listing" scope="session"> <property name="billService"> <ref bean="billService" /> </property> </bean> </beans>

  这里想说下spring在对hibernate4的支持上和3是有区别的。在Hibernate4.0以上的版本,session已经自己封装了事务处理,所以在spring3.1以上的版本把HibernateTemplate去掉了。在hibernate4中获取session的时候,不需要再继承HibernateDaoSupport类,可以直接baseDao类中添加一个SessionFactory属性,再添上它的setter方法。我们使用的DAO层的实现层是要添加到applicationContext.xml中的(其实也就是spring的依赖注入)。

七、java代码

7.1 mode层

package com.billLogger.mode;

import java.sql.Date;

public class Bill {
    Long id;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    
    Float money;
    public Float getMoney() {
        return money;
    }
    public void setMoney(Float money) {
        this.money = money;
    }
    
    Date date;
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    
    Integer account;
    public Integer getAccount() {
        return account;
    }
    public void setAccount(Integer account) {
        this.account = account;
    }
}

7.2 DAO层

package com.billLogger.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.billLogger.mode.Bill;

/*
 *@author Jeniss 2013-10-14 下午4:09:26
 *@tag
 */
public class BillDao{
    protected SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
    
    public List<Bill> getAllBills() {
        String hql = "from Bill";
        Query query = getSession().createQuery(hql);
        List<Bill> bills = query.list();
        return bills;
    }
}

 

 7.3 service层

package com.billLogger.services;

import java.util.List;

import com.billLogger.dao.BillDao;
import com.billLogger.mode.Bill;

/*
 *@author Jeniss 2013-10-14 下午4:13:32
 *@tag
 */
public class BillService {
    private BillDao billDao;
    public void setBillDao(BillDao billDao) {
        this.billDao = billDao;
    }
    
    public List<Bill> getAllBills() {
        List<Bill> bills = billDao.getAllBills();
        return bills;
    }
}

 7.4 action层

package com.billLogger.actions.bill;

import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

/*
 *@author Jeniss  2013-10-8 下午5:23:37
 *@Tag
 */
public class ActionBase extends ActionSupport implements RequestAware, SessionAware, ApplicationAware {
    private static final long serialVersionUID = 1L;
    
    protected Map<String, Object> request;  
    protected Map<String, Object> session;  
    protected Map<String, Object> application;  
    public Map<String, Object> getRequest() {
        return request;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public Map<String, Object> getApplication() {
        return application;
    }

    @Override
    public void setApplication(Map<String, Object> application) {
        this.application = application;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }
}
package com.billLogger.actions.bill;

import java.util.List;

import com.billLogger.mode.Bill;
import com.billLogger.services.BillService;

public class Listing extends ActionBase{
    private static final long serialVersionUID = 1L;
    
    private BillService billService;
    public void setBillService(BillService billService) {
        this.billService = billService;
    }
    
    List<Bill> bills;
    public List<Bill> getBills() {
        return bills;
    }

    public String execute() throws Exception{
        bills = billService.getAllBills();
        return SUCCESS;
    }
}

 

  环境搭建成功。这次搭建环境花了两天的时间,在搭的过程中,主要是对打印的日志不太熟悉,造成了查错能力降低。通过搭建这个环境,对SSH各个层的作用认识更形象了。

  hibernate通过Session接口实现了对数据的操作(例如:对数据库的数据进行增删改查操作),其SessionFactory接口可以调用Session。

  spring主要特性是DI和AOP。在SSH中的作用是连接hibernate和spring。在applicationContext文件中定义sessionFactory,通过设置配置文件路径,实现对hibernate配置文件的注入和解析。定义sessionManager(事务声明),通过注入sessionFactory,得到hibernate session,实现hibernate的事务管理。把sessionFactory注入DAO层,在到daoImpl类中可以使用hibernate session。再通过依赖注入,实现service层和action。

  struts则是控制action和jsp页面的连接。

posted @ 2013-10-13 18:45  Jeniss  阅读(795)  评论(0编辑  收藏  举报