ssh:spring、struts2、hibernate 这就是我们耳熟能详的ssh整合框架!

struts 控制用的 体现在web层

hibernate 操作数据库的,进行对后台数据的访问

spring 用解耦的  管理

1 . service 为 action 提供统计的调用接口,封装持久层的 DAO.

2 .可以写一些自己的业务方法。

3 .统一的 javabean 管理方法

4 .声明式事务管理

导入jar包:

步骤一:spring框架整合hibernate

整合hibernate项目具体仅仅只有两个步骤:1.将sessionFactory交给spring容器进行注入

                                                        2.将spring中的transactionManager事务管理器换成orm框架的hibernateTransactionManager

 

<!-- 事务的配置  hibernate orm的事务管理器-->
        <bean id="myTran" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
           <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
<!-- 代理工厂创建事务 -->
        <bean id="stockServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="target" ref="stockService"></property>
        <property name="transactionManager" ref="myTran"></property>
        <property name="transactionAttributes">
        <props>
        <prop key="add*">ISOLATION_DEFAULT,PROPAGATION_REQUIRED</prop>
        <prop key="buyStock">ISOLATION_DEFAULT,PROPAGATION_REQUIRED,-StockException</prop>
        </props>
        </property>
        </bean>
<!-- 创建sessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
          <property name="dataSource" ref="DataSource"></property>
          <property name="hibernateProperties">
          <props>
             <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
             <prop key="format_sql">true</prop>
             <prop key="show_sql">true</prop>
             <prop key="hibernate.connection.autocommit">true</prop>
             <prop key="hibernate.hbm2ddl.auto">update</prop> 
             <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
          </props>
          </property>
          <property name="mappingLocations" value="classpath:beans/Account.hbm.xml"></property>
        </bean>
 <!-- 创建dao即service的实现 向service中的sessionFactory进行注入 -->
        <bean id="AccountDao" class="dao.impl.Accountimpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <bean id="stockService" class="service.impl.Serviceimpl">
        <property name="acc" ref="AccountDao"></property>
        </bean>

实现增加一个账户

dao:

package dao;

import beans.Account;

public interface AccountDao {
   public int add(Account a);
}

impl:

package dao.impl;

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import beans.Account;
import dao.AccountDao;

public class Accountimpl implements AccountDao {
    
    private SessionFactory sessionFactory;//sessionFactory对象,进行注入
    @Override
    public int add(Account a) {
        sessionFactory.getCurrentSession().save(a);
        return 1;
    }
}

Iservice:

package service;

import dao.impl.StockException;
import beans.Account;
import beans.Stock;

public interface Iservice {

    public int addAccount(Account count);
}

Serviceimpl:

package service.impl;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import service.Iservice;
import beans.Account;
import beans.Stock;
import dao.AccountDao;
import dao.StockDao;
import dao.impl.StockException;

public class Serviceimpl implements Iservice {

    private AccountDao acc;//使用spring进行注入
    public AccountDao getAcc() {
        return acc;
    }
    public void setAcc(AccountDao acc) {
        this.acc = acc;
    }


    @Override
    public int addAccount(Account count) {
        return acc.add(count);
    }
}

测试类:

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import beans.Account;
import dao.impl.StockException;
import service.Iservice;

public class MyTest {
public static void main(String[] args) throws StockException {
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    Iservice dao=(Iservice)ctx.getBean("stockServiceProxy");//必须获取的是代理对象
    Account a=new Account();
    a.setAname("微冷的雨");
    a.setBalance(1000);
    dao.addAccount(a);
}
}

步骤二:使用spring整合struts

web.xml的配置

既然有Struts2,核心拦截器的配置是不可少的

通过配置ContextLoaderListener监听器,使容器启动时,自动加载applicationContext配置,

因为它实现了ServletContextListener这个接口,容器启动时会自动执行它实现的方法。

默认情况下,会加载WEB-INF/applicationContext.xml这个文件,我们可以通过配置contextConfigLocation参数改变配置文件的路径

<?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">
  <display-name></display-name>    
  
   <!--指定配置文件的位置和名称  -->
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

   <!-- 监听器:作用是在整个网站运行的时候,获取到ServletContext(application)初始化的时候,自动
    注入Spring容器
    -->
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   
  <filter>
     <filter-name>struts</filter-name>
     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
  <filter-name>struts</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

创建Action:

package action;

import service.Iservice;
import beans.Account;
import beans.Stock;

import com.opensymphony.xwork2.ActionSupport;

public class AddStockAction extends ActionSupport {

        //植入Service
        private Iservice stockServiceProxy;
        private Account account;
        
        public String add(){
            stockServiceProxy.addAccount(account);
            return SUCCESS;
        }

        public Iservice getStockServiceProxy() {
            return stockServiceProxy;
        }

        public Account getAccount() {
            return account;
        }

        public void setStockServiceProxy(Iservice stockServiceProxy) {
            this.stockServiceProxy = stockServiceProxy;
        }

        public void setAccount(Account account) {
            this.account = account;
        }            
}

创建struts.xml

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
        <package name="default" extends="struts-default">
            <!-- 定义action节点      指定action    指定方法 -->
            <action name="addaction" class="action.AddStockAction" method="add">
                <result name="success">/index.jsp</result>
            </action>    
        </package>
    </struts>

配置action

<!-- struts2 配置action              scope   范围-->
    <bean id="addStock" class="cn.hq.action.AddStockAction" scope="prototype">
          <property name="service" ref="service"></property>
    </bean>

index.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
  </head>
  
  <body>
    <h2>添加账户</h2>
    <s:form action="addaction" method="post">
        <s:textfield name="account.aname"/>
        <s:textfield name="account.balance"/>
        <s:submit value="提交"></s:submit>
    </s:form>
  </body>
</html>