ssh整合

SSH整合前期工作

1.要创建一个数据库 third_ssh

2.要创建2个表

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_name` varchar(30) DEFAULT NULL,
  `account_money` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `real_name` varchar(50) DEFAULT NULL,
  `status` int(1) DEFAULT '0',
  `birth` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


##3.创建一个Web项目

##4.导入相关jar包(49)

1.导入struts的基础jar包(8)

在这里插入图片描述

2.导入struts的注解依赖jar包(3)

在这里插入图片描述

3.导入struts和spring的整合jar包(1)
在这里插入图片描述

4.导入hibernate必须jar包(18)

]在这里插入图片描述

5.导入hibernate的jpa需要jar包(1)

[

6.导入mysql驱动jar包(1)
在这里插入图片描述

7.导入druid连接池jar包(1)

在这里插入图片描述

8.导入spring的基础jar包(5)

9.导入aop相关jar包(4)

在这里插入图片描述

10.spring整合web的相关jar包(1)

在这里插入图片描述

11.spring整合hibernate事务相关jar包(3)

在这里插入图片描述

12.spring整合junit测试使用jar包(3)

在这里插入图片描述

5.创建各个包

在这里插入图片描述

##6.创建两个表对应的实体类和实体映射文件及实体的业务逻辑层和持久层和表现层

SSH整合纯XML版

##1.创建spring的配置文件

该配置文件默认应该在WEB-IN下,且名字为applicationContext.xml

建议:编写在根目录下,名为applicationContext.xml

注:不在默认位置,需要在web.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.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
       
</beans>


2.web.xml中进行spring监听器的注册和Struts的核心过滤器的注册

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

##3.创建struts.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="myPackage" extends="struts-default">
      
    </package>
</struts>

4.spring整合hibernate

hibernate的配置交由spring进行管理

  1. 配置数据源
  2. 创建一个SessionFactory
    1. 指定数据源
    2. 设置hibernate的相关信息
    3. 设置映射文件的位置
<?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.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
        <!--配置数据源,有Druid提供-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/third_ssh?serverTimezone=GMT%2B8"></property>
            <property name="username" value="root"></property>
            <property name="password" value="123456"></property>
        </bean>
        <!--配置Session工厂,整合hibernate-->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <!--配置数据库相关的-->
            <property name="dataSource" ref="dataSource"></property>
            <!--配置hibernate相关-->
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.hbm2ddl.auto" >update</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <!--Spring整合hibernate后,无需设置-->
                    <!-- <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
                </props>
            </property>
            <!--配置映射文件-->
            <property name="mappingLocations">
                <array>
                    <value>classpath:com/fubo/entity/*.hbm.xml</value>
                </array>
            </property>
        </bean>
   
</beans>


5.spring整合持久层

持久层操作要使用Spring提供的HibernateTemplate对象。

1.在spring的容器中创建该对象。

2.在持久层类中注入该对象。

​ 1.在持久层类中创建一个HibernateTemplate成员变量,并生成它的set方法

​ 2.在spring容器中,创建该对象,并且注入HibernateTemplate对象

在applicationContext,进行设置

  <!--创建HibernateTemplate,spring管理-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--持久层类-->
<bean id="accountDao" class="com.fubo.dao.impl.AccountDaoImpl">
    <property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
package com.fubo.dao.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import org.springframework.orm.hibernate5.HibernateTemplate;

import java.util.List;

public class AccountDaoImpl  implements AccountDao {
    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
}

6.spring配置事务管理

1.创建事务管理器:该事务管理器是spring的整合包中的

2.配置通知类

3.配置切面

applicationContext.xml

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="SUPPORTS" read-only="true"></tx:method>
        <tx:method name="transfor*" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" propagation="REQUIRED" read-only="false" />
        <tx:method name="save*" propagation="REQUIRED" read-only="false" />
        <tx:method name="add*" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" propagation="REQUIRED" read-only="false" />

    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* com.fubo.service..*.*(..))"></aop:advisor>
</aop:config>

7.spring整合struts

需要struts把创建对象的权利交由spring。

struts对象的创建在spring的配置文件中进行

struts.xml中配置Action类的地方,改为spring中Action类对应的bean的id

1.spring接管action类的创建

<bean id="accountAction" class="com.fubo.controller.AccountAction" scope="prototype">
    <property name="accountService" ref="accountService"></property>
</bean>

2.在struts.xml中进行配置

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="myPackage" extends="struts-default">
        <action name="transfor" class="accountAction" method="transfor">
            <result>/success.jsp</result>
        </action>
    </package>
</struts>

8.spring整合业务逻辑层

业务逻辑层交由spring管理\

applicationContext.xml

<bean id="accountService" class="com.fubo.service.impl.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"></property>
</bean>

9.编写持久层代码

package com.fubo.dao.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import org.springframework.orm.hibernate5.HibernateTemplate;

import java.util.List;

public class AccountDaoImpl  implements AccountDao {
    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public Account findAccountByAccountName(String accountName) {
        List<Account> objects = (List<Account>) hibernateTemplate.find("select a from Account as a where a. accountName=?0", accountName);
        if (objects.size()>0){
            return  objects.get(0);
        }
        return null;
    }

    @Override
    public void updateAccount(Account account) {
        hibernateTemplate.update(account);
    }
}

10.编写业务逻辑层代码

package com.fubo.service.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import com.fubo.service.AccountService;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public void transfor(String accountA,String accountB,Double money){
        Account account1 = accountDao.findAccountByAccountName(accountA);
        Account account2 = accountDao.findAccountByAccountName(accountB);
        account1.setAccountMoney(account1.getAccountMoney()-money);

        account2.setAccountMoney(account2.getAccountMoney()+money);
        accountDao.updateAccount(account1);
//        int i=1/0;
        accountDao.updateAccount(account2);

    }
}

11.配置表现层代码

package com.fubo.controller;

import com.fubo.service.AccountService;
import com.opensymphony.xwork2.ActionSupport;

public class AccountAction extends ActionSupport {
    private AccountService accountService;
    private String accountA;
    private String accountB;
    private Double money;

    public String transfor(){
        accountService.transfor(accountA,accountB,money);
        return SUCCESS;
    }

    public String getAccountA() {
        return accountA;
    }

    public void setAccountA(String accountA) {
        this.accountA = accountA;
    }

    public String getAccountB() {
        return accountB;
    }

    public void setAccountB(String accountB) {
        this.accountB = accountB;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}

12.编写测试页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-05
  Time: 上午 11:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="transfor" method="post">
        转出账号 <input name="accountA" type="text"><br>
        转入账号 <input name="accountB" type="text"><br>
        转出金额 <input name="money" type="text"><br>
        <button>转账</button>
    </form>
</body>
</html>

SSH整合XML和注解混合版

1.创建spring的配置文件

该配置文件默认应该在WEB-IN下,且名字为applicationContext.xml

建议:编写在根目录下,名为applicationContext.xml

注:不在默认位置,需要在web.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.xsd
                                                                               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                                                                               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<context:component-scan base-package="com.fubo.*"></context:component-scan>	
</beans>
  

2.web.xml中进行spring监听器的注册和Struts的核心过滤器的注册

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

3.创建struts.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="myPackage" extends="struts-default">
      
    </package>
</struts>

4.spring整合hibernate

hibernate的配置交由spring进行管理

  1. 配置数据源
  2. 创建一个SessionFactory
    1. 指定数据源
    2. 设置hibernate的相关信息
    3. 设置映射文件的位置
<?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.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
        <!--配置数据源,有Druid提供-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/third_ssh?serverTimezone=GMT%2B8"></property>
            <property name="username" value="root"></property>
            <property name="password" value="123456"></property>
        </bean>
        <!--配置Session工厂,整合hibernate-->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <!--配置数据库相关的-->
            <property name="dataSource" ref="dataSource"></property>
            <!--配置hibernate相关-->
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.hbm2ddl.auto" >update</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <!--Spring整合hibernate后,无需设置-->
                    <!-- <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
                </props>
            </property>
            <!--配置映射文件-->
            <property name="mappingLocations">
                <array>
                    <value>classpath:com/fubo/entity/*.hbm.xml</value>
                </array>
            </property>
        </bean>
   
</beans>


5.spring整合持久层

持久层操作要使用Spring提供的HibernateTemplate对象。

1.在spring的容器中创建该对象。

在applicationContext,进行设置

 <!--创建HibernateTemplate,spring管理-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

6.spring配置事务管理

1.创建事务管理器:该事务管理器是spring的整合包中的

2.配置通知类

3.配置切面

applicationContext.xml

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="SUPPORTS" read-only="true"></tx:method>
        <tx:method name="transfor*" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" propagation="REQUIRED" read-only="false" />
        <tx:method name="save*" propagation="REQUIRED" read-only="false" />
        <tx:method name="add*" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" propagation="REQUIRED" read-only="false" />

    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* com.fubo.service..*.*(..))"></aop:advisor>
</aop:config>

7.spring整合struts

需要struts把创建对象的权利交由spring。

struts对象的创建有注解完成

struts.xml中配置Action类的地方,改为spring中Action类对应的bean的id

1.在struts.xml中进行配置

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="myPackage" extends="struts-default">
        <action name="transfor" class="accountAction" method="transfor">
            <result>/success.jsp</result>
        </action>
    </package>
</struts>

8.spring注解管理持久层

package com.fubo.dao.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository("accountDao")
public class AccountDaoImpl  implements AccountDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public Account findAccountByAccountName(String accountName) {
        List<Account> objects = (List<Account>) hibernateTemplate.find("select a from Account as a where a. accountName=?0", accountName);
        if (objects.size()>0){
            return  objects.get(0);
        }
        return null;
    }

    @Override
    public void updateAccount(Account account) {
        hibernateTemplate.update(account);
    }
}

##9.spring注解管理业务逻辑层

package com.fubo.service.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import com.fubo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;


    public void transfor(String accountA,String accountB,Double money){
        Account account1 = accountDao.findAccountByAccountName(accountA);
        Account account2 = accountDao.findAccountByAccountName(accountB);
        account1.setAccountMoney(account1.getAccountMoney()-money);

        account2.setAccountMoney(account2.getAccountMoney()+money);
        accountDao.updateAccount(account1);
//        int i=1/0;
        accountDao.updateAccount(account2);

    }
}

10.spring注解管理表现层

package com.fubo.controller;

import com.fubo.service.AccountService;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class AccountAction extends ActionSupport {
    @Autowired
    private AccountService accountService;
    private String accountA;
    private String accountB;
    private Double money;

    public String transfor(){
        accountService.transfor(accountA,accountB,money);
        return SUCCESS;
    }

    public String getAccountA() {
        return accountA;
    }

    public void setAccountA(String accountA) {
        this.accountA = accountA;
    }

    public String getAccountB() {
        return accountB;
    }

    public void setAccountB(String accountB) {
        this.accountB = accountB;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }


}

11.编写测试页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-05
  Time: 上午 11:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="transfor" method="post">
        转出账号 <input name="accountA" type="text"><br>
        转入账号 <input name="accountB" type="text"><br>
        转出金额 <input name="money" type="text"><br>
        <button>转账</button>
    </form>
</body>
</html>

SSH纯注解版

1.创建spring配置文件,并设置扫描路径

<?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.xsd
                                                                               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                                                                               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<context:component-scan base-package="com.fubo.*"></context:component-scan>	
</beans>

2.编写一个注解配置类

注解类的作用:代替applicationContext.xml中的配置

package com.fubo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.fubo.entity.Account;
import com.fubo.entity.UserInfo;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ConfigurableWebApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
public class ApplicationContextConfig {

    /**
     * 配置数据源
     * @return
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource  = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/third_ssh?serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    /**
     * 配置hibernateTemplate功能类似于hibernate的session
     * @param sessionFactory
     * @return
     */
    @Bean
    public HibernateTemplate hibernateTemplate(SessionFactory sessionFactory){
        HibernateTemplate hibernateTemplate = new HibernateTemplate();
        hibernateTemplate.setSessionFactory(sessionFactory);
        return  hibernateTemplate;
    }

    /**
     * 配置sessionFactory(Hibernate)
     * @param dataSource
     * @return
     */
    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource){
        LocalSessionFactoryBean sessionFactory  = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        Properties properties  = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto","update");
        properties.setProperty("hibernate.show_sql","true");
        properties.setProperty("hibernate.format_sql","true");
        properties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL8Dialect");
        sessionFactory.setAnnotatedClasses(Account.class, UserInfo.class);

        //sessionFactory.setAnnotatedPackages("classpath:com.fubo.entity");
//        sessionFactory.setMappingLocations();
        sessionFactory.setHibernateProperties(properties);
        return  sessionFactory;
    }

    /**
     * 配置事务管理器
     * @param ds
     * @return
     */
    @Bean
    public HibernateTransactionManager hibernateTransactionManager(SessionFactory ds){
        return  new HibernateTransactionManager(ds);
    }
}

3.在web.xml中进行spring监听器的注册和struts过滤器的注册

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

##4.编写实体,实体要通过注解配置映射关系

package com.fubo.entity;

import javax.persistence.*;

@Entity
@Table(name="account")
public class Account {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name="account_name")
    private String accountName;
    @Column(name="account_money")
    private Double accountMoney;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public Double getAccountMoney() {
        return accountMoney;
    }

    public void setAccountMoney(Double accountMoney) {
        this.accountMoney = accountMoney;
    }
}

5.编写持久层代码

package com.fubo.dao.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository("accountDao")
public class AccountDaoImpl  implements AccountDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public Account findAccountByAccountName(String accountName) {
        List<Account> objects = (List<Account>) hibernateTemplate.find("select a from Account as a where a. accountName=?0", accountName);
        if (objects.size()>0){
            return  objects.get(0);
        }
        return null;
    }

    @Override
    public void updateAccount(Account account) {
        hibernateTemplate.update(account);
    }
}

6.编写业务逻辑层

业务逻辑层需要加入事务,需要事务的注解

package com.fubo.service.impl;

import com.fubo.dao.AccountDao;
import com.fubo.entity.Account;
import com.fubo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void transfor(String accountA,String accountB,Double money){
        Account account1 = accountDao.findAccountByAccountName(accountA);
        Account account2 = accountDao.findAccountByAccountName(accountB);
        account1.setAccountMoney(account1.getAccountMoney()-money);

        account2.setAccountMoney(account2.getAccountMoney()+money);
        accountDao.updateAccount(account1);
//        int i=1/0;
        accountDao.updateAccount(account2);

    }
}

7.表现层代码编写

package com.fubo.action;

import com.fubo.service.AccountService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
@ParentPackage("struts-default")
public class AccountAction extends ActionSupport {
    @Autowired
    private AccountService accountService;
    private String accountA;
    private String accountB;
    private Double money;
    @Action("transfor")
    public String transfor(){
        accountService.transfor(accountA,accountB,money);
        return SUCCESS;
    }

    public String getAccountA() {
        return accountA;
    }

    public void setAccountA(String accountA) {
        this.accountA = accountA;
    }

    public String getAccountB() {
        return accountB;
    }

    public void setAccountB(String accountB) {
        this.accountB = accountB;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }


}

8.编写测试页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-05
  Time: 上午 11:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="transfor" method="post">
        转出账号 <input name="accountA" type="text"><br>
        转入账号 <input name="accountB" type="text"><br>
        转出金额 <input name="money" type="text"><br>
        <button>转账</button>
    </form>
</body>
</html>

{
accountService.transfor(accountA,accountB,money);
return SUCCESS;
}

public String getAccountA() {
    return accountA;
}

public void setAccountA(String accountA) {
    this.accountA = accountA;
}

public String getAccountB() {
    return accountB;
}

public void setAccountB(String accountB) {
    this.accountB = accountB;
}

public Double getMoney() {
    return money;
}

public void setMoney(Double money) {
    this.money = money;
}

}


## 8.编写测试页面

```html
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020-01-05
  Time: 上午 11:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="transfor" method="post">
        转出账号 <input name="accountA" type="text"><br>
        转入账号 <input name="accountB" type="text"><br>
        转出金额 <input name="money" type="text"><br>
        <button>转账</button>
    </form>
</body>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值