详解SSM环境的搭建(下)

发布于 2020-08-13  661 次阅读


在上一篇博客中详解SSM环境的搭建(上),我也经搭建好了是SSM的基本框架,并进行了简单的测试。但是并没有给MySQL添加事务管理以及并没有测试数据库的增删查改功能。接下来便继续详细进行各个功能的测试。
1.添加新的依赖

 <!-- 引入aop依赖 -->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.9.6</version>
      </dependency>
      <!-- 引入Spring解析JSon数据的依赖 -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.11.2</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.11.2</version>
      </dependency>
      <!-- 将参数map的参数值注入JavaBean中 -->
      <dependency>
          <groupId>commons-beanutils</groupId>
          <artifactId>commons-beanutils</artifactId>
          <version>1.9.4</version>
      </dependency>

完整的pom.xml文件为:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>ssmdemo3</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssmdemo3 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
<!--    项目编码-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
<!--    用户版本锁定,方便修改版本-->
    <spring.version>5.2.8.RELEASE</spring.version>
  </properties>

  <dependencies>
<!--    引入JUnit测试依赖-->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0-M1</version>
      <scope>test</scope>
    </dependency>
<!--    引入Spring的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <!-- 引入Spring-jdbc依赖包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
<!--引入servlet的依赖包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
<!--引入jsp依赖包-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- 引入mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!-- 引入mybatis的Spring依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
    <!-- 引入MySQL依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
    <!-- 引入c3p0连接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.5</version>
    </dependency>
    <!-- 引入jstl表达式的依赖包 -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
      <!-- 引入aop依赖 -->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.9.6</version>
      </dependency>
      <!-- 引入Spring解析JSon数据的依赖 -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.11.2</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.11.2</version>
      </dependency>
      <!-- 将参数map的参数值注入JavaBean中 -->
      <dependency>
          <groupId>commons-beanutils</groupId>
          <artifactId>commons-beanutils</artifactId>
          <version>1.9.4</version>
      </dependency>

  </dependencies>

  <build>
    <finalName>ssmdemo3</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2.更新AccountDao.java的代码,添加mybatis的注解

package dao;

import entity.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Classname:AccountDao
 * @description:用于访问数据库,实现对数据库的增删除改操作
 * @author: 陌意随影
 * @Date: 2020-08-12 19:55
 * @Version: 1.0
 **/
@Repository("accountDao")
public interface AccountDao {
    /**
     * @Description :向数据库中存入新的用户,并返回是否存储成功
     * @Date 19:56 2020/8/12 0012
     * @Param * @param account :要保存的用户
     * @return boolean
     **/
    @Insert("insert into account(name,password,age,createTime,money) values(#{name},#{password},#{age},#{createTime},#{money})")
     public  int saveAccount(Account account);
     /**
      * @Description :更新用户
      * @Date 19:58 2020/8/12 0012
      * @Param * @param account :
      * @return boolean
      **/
     @Update("update account set name=#{name},password=#{password},age=#{age},createTime=#{createTime},money=#{money} where id=#{id}")
     public int updateAccount(Account account);
     /**
      * @Description :通过ID删除用户
      * @Date 19:59 2020/8/12 0012
      * @Param * @param id :
      * @return boolean
      **/
     @Delete("delete from account where id=#{id}")
     public  int deleteAccount(int id);
     /**
      * @Description :通过用户id查找用户
      * @Date 19:59 2020/8/12 0012
      * @Param * @param id :
      * @return entity.Account
      **/
     @Select("select* from account where id=#{id}")
     public Account findAccount(int id);
     /**
      * @Description :查找所有的用户
      * @Date 20:00 2020/8/12 0012
      * @Param * @param  :
      * @return java.util.List<entity.Account>
      **/
     @Select("select* from account")
     public List<Account> findAllAccount();
}

3.在AccountService.java中添加转账方法用于模拟事务是否正确执行,同时在AccountServiceImpl.java中实现该接口。

package service;

import entity.Account;

import java.util.List;

/**
 * Classname:ssmdemo3
 * @description: 用户业务逻辑接口
 * @author: 陌意随影
 * @Date: 2020-08-12 19:55
 */
public interface AccountService {
    /**
     * @Description :向数据库中存入新的用户,并返回是否存储成功
     * @Date 19:56 2020/8/12 0012
     * @Param * @param account :要保存的用户
     * @return boolean
     **/
    public  boolean saveAccount(Account account);
    /**
     * @Description :更新用户
     * @Date 19:58 2020/8/12 0012
     * @Param * @param account :
     * @return boolean
     **/
    public boolean updateAccount(Account account);
    /**
     * @Description :通过ID删除用户
     * @Date 19:59 2020/8/12 0012
     * @Param * @param id :
     * @return boolean
     **/
    public  boolean deleteAccount(int id);
    /**
     * @Description :通过用户id查找用户
     * @Date 19:59 2020/8/12 0012
     * @Param * @param id :
     * @return entity.Account
     **/
    public Account findAccount(int id);
    /**
     * @Description :查找所有的用户
     * @Date 20:00 2020/8/12 0012
     * @Param * @param  :
     * @return java.util.List<entity.Account>
     **/
    public List<Account> findAllAccount();
    /**
     * @Description :ID为sourceId的用户转账money到用户ID为targetId的用户
     * @Date 22:51 2020/8/12 0012
     * @Param * @param sourceId
     * @param targetId
     * @param money :
     * @return boolean
     **/
    public boolean transMoney(int sourceId,int targetId,int money);
}
package service.impl;

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

import java.util.List;

/**
 * Classname:AccountServiceImpl
 *
 * @description:
 * @author: 陌意随影
 * @Date: 2020-08-12 20:11
 * @Version: 1.0
 **/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    //自动注入dao
    @Autowired
    AccountDao accountDao;
    @Override
    public boolean saveAccount(Account account) {
        return  accountDao.saveAccount(account)==1;
    }

    @Override
    public boolean updateAccount(Account account) {
        return accountDao.updateAccount(account)==1;
    }

    @Override
    public boolean deleteAccount(int id) {
        return accountDao.deleteAccount(id)==1;
    }

    @Override
    public Account findAccount(int id) {
        return accountDao.findAccount(id);
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public boolean transMoney(int sourceId, int targetId, int money) {
//        获取对应的用户
        Account sourceIdAccount = accountDao.findAccount(sourceId);
        Account targetAccount = accountDao.findAccount(targetId);
        if (sourceIdAccount== null ||targetAccount == null){
            return false;
        }
//        更新账户余额
       sourceIdAccount.setMoney(sourceIdAccount.getMoney()-money);
        targetAccount.setMoney(targetAccount.getMoney()+money);
        boolean  fla1 = this.updateAccount(sourceIdAccount);
       //模拟转账出错误
        int i = 9/0;
        boolean fla2 = this.updateAccount(targetAccount);
        return fla1==true&&fla2==true;
    }
}

4.在index.jsp中添加添加代码

<%--
  Created by IntelliJ IDEA.
  User: 陌意随影
  Date: 2020/8/5 0005
  Time: 23:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<head>
 <title>测试首页</title>
</head>
<body>
<h3>首页</h3>
<a href="account/saveAccount?name=aaa&password=aaa&age=18&money=240">保存用户</a><br>
<a href="account/updateAccount?id=25&name=bbb&password=bbb&age=23&money=640">更新用户</a><br>
<a href="account/deleteAccount?id=25">删除用户</a><br>
<a href="account/findOne?id=25">查找用户</a><br>
<a href="account/findAllAccount">查找所有用户</a><br>
<a href="account/transMoney?sourceId=23&targetId=25&money=100">转账</a><br>
</body>
</html>

进行测试各种方法。
在pages文件夹中添加AccountList.jsp用于展示查询的用户

<%--
  Created by IntelliJ IDEA.
  User: 陌意随影
  Date: 2020/8/12 0012
  Time: 23:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>查询用户页面</title>
</head>
<body>
 <c:if test="${ not empty accountList}" >
        <c:forEach items="${accountList}" var="account" >
            <tr>
                <td>${account.id}</td>
                <td>${account.name}</td>
                <td>${account.password}</td>
                <td>${account.age}</td>
                <td>${account.money}</td>
                <td>${account.createTime}</td>
            </tr>
            <br>
        </c:forEach>
 </c:if>
 <c:if test="${not empty account}">
     <tr>
         <td>${account.id}</td>
         <td>${account.name}</td>
         <td>${account.password}</td>
         <td>${account.age}</td>
         <td>${account.money}</td>
         <td>${account.createTime}</td>
     </tr>
 </c:if>

</body>
</html>

5.更新controller中的AccountController.java中的方法

package controller;

import entity.Account;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import service.AccountService;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Classname:AccountController
 * @description:控制器
 * @author: 陌意随影
 * @Date: 2020-08-12 20:02
 * @Version: 1.0
 **/
@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
  private AccountService accountService;
    @RequestMapping("/testSSM")
    public String testSSM(){
        //调用测试方法
        accountService.findAllAccount();
        System.out.println("框架搭建成功!");
        return "sucess";
    }
    @RequestMapping(value = "/saveAccount")
    public ModelAndView saveAccount(HttpServletRequest httpServletRequest){
        Account account = new Account();
        Map parameterMap = httpServletRequest.getParameterMap();
        BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
        try {
            beanUtilsBean.populate(account,parameterMap);
            boolean fla = accountService.saveAccount(account);
            System.out.println("保存成功:"+fla);
            ModelAndView modelAndView=new ModelAndView();
            modelAndView.setViewName("sucess");
            if (fla){
                modelAndView.addObject("msg","保存用户成功!");
            }else{
                modelAndView.addObject("msg","保存用户失败!");
            }
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("参数错误。。");
        }


    }
    @RequestMapping("/updateAccount")
    public ModelAndView updateAccount(HttpServletRequest httpServletRequest){
        Account account = new Account();
        Map parameterMap = httpServletRequest.getParameterMap();
        BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
        try {
            beanUtilsBean.populate(account,parameterMap);
            System.out.println(account);
            boolean fla = accountService.updateAccount(account);
            System.out.println("更新成功:"+fla);
            ModelAndView modelAndView=new ModelAndView();
            modelAndView.setViewName("sucess");
            if (fla){
                modelAndView.addObject("msg","更新用户成功!");
            }else{
                modelAndView.addObject("msg","更新用户失败!");
            }
            return modelAndView;
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("参数错误。。");
        }
    }
    @RequestMapping("/deleteAccount")
    public ModelAndView deleteAccount(@RequestParam int id){
        boolean fla = accountService.deleteAccount(id);
        System.out.println("删除成功:"+fla);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("sucess");
        if (fla){
            modelAndView.addObject("msg","删除用户成功!");
        }else{
            modelAndView.addObject("msg","删除用户失败!");
        }
        return modelAndView;
    }
    @RequestMapping("/findOne")
    public  ModelAndView findOne(@RequestParam int id){
        Account account = accountService.findAccount(id);
        System.out.println(account);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("accountList");
        modelAndView.addObject("account",account);
        return modelAndView;
    }
    @RequestMapping("/findAllAccount")
    public  ModelAndView findAllAccount(){
        List<Account> accountList = accountService.findAllAccount();
        System.out.println(accountList);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("accountList");
        modelAndView.addObject("accountList",accountList);
        return modelAndView;
    }
    @RequestMapping("/transMoney")
    public ModelAndView transMoney(@RequestParam int sourceId,@RequestParam int targetId,@RequestParam int money){
        boolean fla = accountService.transMoney(sourceId,targetId,money);
        System.out.println("转账成功:"+fla);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("sucess");
        if (fla){
            modelAndView.addObject("msg","转账成功!");
        }else{
            modelAndView.addObject("msg","转账失败!");
        }
        return modelAndView;
    }
}

6.在applicationContexConfig.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
<!--    开启注解扫描-->
  <context:component-scan base-package="service"/>
 <context:component-scan base-package="entity"/>
<!--导入db.properties-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--    配置数据源-->
    <bean  id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
    </bean>
<!--    配置SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    配置dao接口所在的位置,这里采用的注解配置mybatis的dao接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="basePackage" value="dao"></property>
    </bean>
<!--    添加事务管理-->
    <bean  id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--    配置事务通知-->
    <tx:advice transaction-manager="transactionManager" id="transactionInterceptor">
        <!--     配置事务的属性   -->
        <tx:attributes>
            <tx:method name="saveAccount" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
            <tx:method name="updateAccount" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
            <tx:method name="deleteAccount" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
            <tx:method name="findAccount" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
            <tx:method name="findAllAccount" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

 <aop:config>

<!--     配置切面点,这里表示对AccountServiceImpl.java中的每个方法都起作用-->
     <aop:pointcut id="pt" expression="execution(* service.impl.AccountServiceImpl.*(..))"/>
     <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="pt"></aop:advisor>
 </aop:config>
</beans>

7.启动Tomcat进行测试。经过测试发现每个功能都正确,配置的事务管理也正确。
本项目的代码已经上传到个人博客服务器,若有需要请自行下载(解压后导入idea即可):http://moyisuiying.com/wp-content/uploads/2020/08/ssmdemo4.rar


繁华落尽,雪花漫天飞舞。