从 01 开始 从 01 开始
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档

晓林

程序猿,自由职业者,博主,英语爱好者,健身达人
首页
  • 📚 计算机基础

    • 计算机简史
    • 数字电路
    • 计算机组成原理
    • 操作系统
    • Linux
    • 计算机网络
    • 数据库
    • 编程工具
    • 装机
  • 🎨 前端

    • Node
  • JavaSE
  • Java 高级
  • JavaEE

    • 构建、依赖管理
    • Ant
    • Maven
    • 日志框架
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • 环境管理和配置管理-科普篇
    • Servlet
  • Spring

    • Spring基础
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC

    • SpringMVC 基础
  • SpringBoot

    • SpringBoot 基础
  • Windows 使用技巧
  • 手机相关技巧
  • 最全面的输入法教程
  • 最全面的浏览器教程
  • Office
  • 图片类工具
  • 效率类工具
  • 最全面的 RSS 教程
  • 码字工具
  • 各大平台
  • 校招
  • 五险一金
  • 职场规划
  • 关于离职
  • 杂谈
  • 自媒体
  • 📖 读书

    • 读书工具
    • 走进科学
  • 🌍 英语

    • 从零开始学英语
    • 英语兔的相关视频
    • Larry 想做技术大佬的相关视频
  • 🏛️ 政治

    • 反腐
    • GFW
    • 404 内容
    • 审查与自我审查
    • 互联网
    • 战争
    • 读书笔记
  • 💰 经济

    • 关于税
    • 理财
  • 💪 健身

    • 睡眠
    • 皮肤
    • 口腔健康
    • 学会呼吸
    • 健身日志
  • 🏠 其他

    • 驾驶技能
    • 租房与买房
    • 厨艺
  • 电影

    • 电影推荐
  • 电视剧
  • 漫画

    • 漫画软件
    • 漫画推荐
  • 游戏

    • Steam
    • 三国杀
    • 求生之路
  • 小说
  • 关于本站
  • 关于博主
  • 打赏
  • 网站动态
  • 友人帐
  • 从零开始搭建博客
  • 搭建邮件服务器
  • 本站分享
  • 🌈 生活

    • 2022
    • 2023
    • 2024
    • 2025
  • 📇 文章索引

    • 文章分类
    • 文章归档
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

    • SpringMVC 基本概念
    • SpringMVC 入门案例
    • SpringMVC 中的组件介绍
    • RequestMapping 注解的作用
    • 请求参数的绑定
    • 自定义类型转换器
    • 使用原生的 Servlet-API
    • SpringMVC 常用注解
    • 响应数据和结果视图
    • 文件上传
    • 文件上传之跨服务器
    • SpringMVC 的异常处理
    • SpringMVC 的拦截器
    • SSM 整合
      • 相关的概念
      • 数据库准备
      • 搭建环境
      • 新建 Account 类
      • 新建 dao 接口
      • 新建 service 接口和实现类
      • 新建 Controller
      • 编写 Spring
      • 编写 SpringMVC
      • Spring 整合 SpringMVC
      • 编写 Mybatis
      • Spring 整合 Mybatis
      • Mybatis 配置事务
      • 总结
  • SpringBoot

  • Java
  • SpringMVC
2023-05-15
目录

SSM 整合

# 130.SSM 整合

本文来讲解 SSM 三大框架的整合,这是一个非常重要的知识点。要开发一个项目,先将框架搭建起来,然后完成具体的开发。 ‍

# 相关的概念

整合说明:SSM 整合可以使用多种方式,咱们会选择 XML + 注解的方式,怎么简单怎么来,一般是自己写的类就用注解,而第三方的类就是用配置文件

整合的思路

  1. 先搭建整合的环境,确保每个框架能单独使用。例如先搭建 SpringMVC,确保能正常处理请求;然后搭建 Mybatis,确保能正常增删改查;
  2. 把 Spring 的配置搭建完成
  3. 再使用 Spring 整合 SpringMVC 框架
  4. 最后使用 Spring 整合 MyBatis 框架 ‍

# 数据库准备

‍

create database ssm;
use ssm;

CREATE USER IF NOT EXISTS LearnSSMUser@'%' IDENTIFIED BY 'LearnSSMUser@Password';
GRANT ALL PRIVILEGES ON ssm.* TO LearnSSMUser@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;


create table account(
	id int primary key auto_increment,
	name varchar(20),
	money double
)

INSERT into account(name, money) VALUES("王小美", 69);
INSERT into account(name, money) VALUES("刻晴", 69);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

‍

# 搭建环境

我们创建一个新的项目:LearnSpringMVC_SSM

配置 pom.xml,由于文件过长,这里就不展示了,主要是配置 properties 和 dependencies 标签

在 resources 下新建 log4j.properties:

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

‍

# 新建 Account 类

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;
}
1
2
3
4
5

‍ 新建实体类,并创建其 getter 和 setter 方法 ‍

# 新建 dao 接口

‍

package com.peterjxl.dao;
import com.peterjxl.domain.Account;
import java.util.List;

public interface AccountDao {
    List<Account> findAll();

    void saveAccount(Account account);
}

1
2
3
4
5
6
7
8
9
10

‍

# 新建 service 接口和实现类

‍

package com.peterjxl.service;

import com.peterjxl.domain.Account;

import java.util.List;

public interface AccountService {

    List<Account> findAll();

    void saveAccount(Account account);
}

1
2
3
4
5
6
7
8
9
10
11
12
13

‍

public class AccountServiceImpl implements AccountService{
    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存账户");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13

‍

# 新建 Controller

package com.peterjxl.controller;
public class AccountController {
  
}
1
2
3
4

# 编写 Spring

新建 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: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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

‍ 添加注解扫描,之前说过 Spring 是负责业务层的,因此要配置不处理 Controller 的注解

 <!-- 开启注解的扫描,只处理service和dao -->
    <context:component-scan base-package="com.peterjxl">
        <!-- 配置哪些注解不扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
1
2
3
4
5

在 service 实现类上面加注解:

@Service("accountService")
public class AccountServiceImpl implements AccountService{
1
2

‍ 新建测试类:

package com.peterjxl.test;

import com.peterjxl.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void run1(){
        // 加载Spring配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // 获取对象
        AccountService accountService = (AccountService) ac.getBean("accountService");
        // 调用方法
        accountService.findAll();
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

‍ 可以看到能正常运行

# 编写 SpringMVC

新建 resources/springmvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 开启注解扫描,只扫描Controller -->
    <context:component-scan base-package="com.peterjxl">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置视图解析器 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


    <!--过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>


</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

在 web.xml 中配置前端控制器

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- 配置编码 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

新建 webapp/index.jsp :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <a href="account/findAll">测试SpringMVC</a>
    </body>
</html>
1
2
3
4
5
6
7
8
9

修改 controller:

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户...");
        return "list";
    }
}
1
2
3
4
5
6
7
8
9
10

‍ 新建 WEB-INF/pages/list.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
      <h3>查询了所有账户信息</h3>
    </body>
</html>
1
2
3
4
5
6
7
8
9

‍ 测试:在 IDEA 中新建 Tomcat 配置,然后运行,访问可以看到能正常运行:

‍

# Spring 整合 SpringMVC

怎么判断整合成功:能在表现层调用 service 层的方法。

那么表现层得注入,所以表现层也到放到容器里,由 Spring 帮我们注入。

但是目前有这样的问题:我们在 web.xml 中配置了前端控制器,在项目一启动的时候就会加载 SpringMVC 的配置文件,但是没有加载 Spring 的配置文件。

而 springmvc.xml 中只配置了扫描 controller 的注解,其他注解不扫描;那么 Spring 的配置文件就是一直没加载的。现在我们来配置,启动项目的时候就加载 Spring。怎么弄呢?

首先,我们在学 JavaWeb 的时候,学过 ServletContext 域对象 (opens new window),该对象在服务器启动的时候创建,服务器停止的时候关闭;

我们还学过监听器,可以监听 ServletContext 的创建和销毁。我们可以用监听器去加载 Spring 的配置文件。

而 Spring 已经帮我们写了监听器,我们在 pom.xml 文件中引用了 spring-web 的依赖,我们只需配置即可,我们在 web.xml 中添加如下内容:

<!-- 配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml -->
<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>
1
2
3
4
5
6
7
8
9

我们可以看到该类的源码,继承了 ServletContextListener 这个监听器

package org.springframework.web.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

‍ 此时我们就可以注入了:

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;
    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户...");
        return "list";
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13

‍ 此时我们重启服务器并测试,可以看到能正常调用 service 的代码,控制台输出:

表现层:查询所有账户...
业务层:查询所有账户
1
2

# 编写 Mybatis

在 dao 方面直接写注解,就不使用配置文件了:

package com.peterjxl.dao;

import com.peterjxl.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface AccountDao {

    @Select("select * from account")
    List<Account> findAll();

    @Insert("insert into account (name, money) values(#{name}, #{money})")
    void saveAccount(Account account);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

‍ 新建 Mybatis 主配置文件:resources/SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  
    <!-- 配置环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="LearnSSMUser"/>
                <property name="password" value="LearnSSMUser@Password"/>
            </dataSource>
        </environment>
    </environments>
  
    <!-- 引入映射配置环境 -->
    <mappers>
        <package name="com.peterjxl.dao"/>
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

‍ 编写测试方法:

package com.peterjxl.test;

import com.peterjxl.dao.AccountDao;
import com.peterjxl.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {

    @Test
    public void run1() throws IOException {
        // 加载Mybatis配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        // 创建SqlSession对象
        SqlSession sqlSession = factory.openSession();

        // 获取代理对象
        AccountDao dao = sqlSession.getMapper(AccountDao.class);

        // 查询所有数据
        List<Account> list = dao.findAll();
        for (Account account : list){
            System.out.println(account);
        }

        // 关闭资源
        sqlSession.close();
        in.close();
    }

    @Test
    public void run2() throws IOException {
        // 加载Mybatis配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        // 创建SqlSession对象
        SqlSession sqlSession = factory.openSession();

        // 获取代理对象
        AccountDao dao = sqlSession.getMapper(AccountDao.class);

        Account account = new Account();
        account.setName("影");
        account.setMoney(400d);
        dao.saveAccount(account);
        sqlSession.commit();

        // 关闭资源
        sqlSession.close();
        in.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

此时我们运行,可以看到能正常获取数据

# Spring 整合 Mybatis

怎么才算整合成功?service 能正常调用 dao 层对象。同理还是注入,怎么将代理对象存到容器中。

我们引用了 spring-mybatis 的依赖,这个依赖就提供了相关的类用于整合 Spring。

我们在 applicationContext.xml 中添加如下配置:

<!-- Spring整合Mybatis -->

<!-- 配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
    <property name="user" value="LearnSSMUser"/>
    <property name="password" value="LearnSSMUser@Password"/>
</bean>

<!-- 配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置dao接口所在的包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.peterjxl.dao"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

在 dao 接口加上注解:

@Repository
public interface AccountDao {
1
2

在 service 实现类里注入 dao 对象:

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存账户");
        accountDao.saveAccount(account);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

‍ 在 controller 层中,加入这个用户信息:

@RequestMapping("/findAll")
public String findAll(Model model){
    System.out.println("表现层:查询所有账户...");
    List<Account> list = accountService.findAll();
    model.addAttribute("list", list);
    return "list";
}
1
2
3
4
5
6
7

在 list 中取出:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h3>查询了所有账户信息</h3>
        <c:forEach items="${list}" var="account">
            ${account.name}
        </c:forEach>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

‍ 重启服务器,访问并测试,可以看到能正常看到数据。

# Mybatis 配置事务

现在我们来到最后一步:配置事务。 ‍ 在 applicationContext.xml 中,添加如下配置:

 <!-- 配置Spring框架声明式事务管理 -->

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="*" isolation="DEFAULT"/>
    </tx:attributes>
</tx:advice>

<!-- 配置AOP增强 -->
<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.peterjxl.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

在 index.jsp 新增一个表单:

<form action="account/save" >
    姓名:<input type="text" name="name"> <br/>
    金钱:<input type="text" name="money"> <br/>
    <input type="submit" value="保存">
</form>
1
2
3
4
5

在 Controller 中新增一个保存方法,并且保存后重定向到查询所有的页面:

@RequestMapping("/save")
public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("表现层:保存账户...");
    accountService.saveAccount(account);
    response.sendRedirect(request.getContextPath() + "/account/findAll");
}
1
2
3
4
5
6

‍ 测试:

# 总结

本文我们将之前学习的三大框架整合了起来,该项目可以作为后续开发项目的时候的骨架。

已将源码上传到 Gitee (opens new window) 和 GitHub (opens new window) 上

上次更新: 2025/6/3 09:31:54
SpringMVC 的拦截器
SpringBoot 课程介绍

← SpringMVC 的拦截器 SpringBoot 课程介绍→

最近更新
01
学点统计学:轻松识破一本正经的胡说八道
06-05
02
2025 年 5 月记
05-31
03
《贫穷的本质》很棒,但可能不适合你
05-27
更多文章>
Theme by Vdoing | Copyright © 2022-2025 | 粤 ICP 备 2022067627 号 -1 | 粤公网安备 44011302003646 号 | 点击查看十年之约
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式