文章目录


SSM整合案例

前言

首先,我们需要了解的前置知识,必须是学完了Spring,SpringMVC,MyBatis之后。因为SSM(Spring+SpringMVC+MyBatis)

回顾:

  • Spring:业务层框架,主要是完成对象的创建与管理
  • SpringMVC:表现层框架,主要是替换原来的Servlet,转发请求
  • MyBatis:著名持久层框架,事业服务与数据库之间的联系
  • SSM整合记录_mybatis

一、环境准备

如果是构建的是Maven项目,则需要引入如下的依赖,如果是构建的Web项目,则需要引入jar包:

1.1、构建maven/Dynamic Web项目

构建一个Maven项目

SSM整合记录_maven_02


或者构建一个Web项目

SSM整合记录_maven_03

1.2、引入依赖/jar包

【版本对应】

MyBatis-Spring的官网对SSM整合的版本对应有了明确的说明,如下图:

SSM整合记录_java_04

【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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.wei</groupId>
<artifactId>SSMBuilder</artifactId>
<version>1.0-SNAPSHOT</version>
<name>SSMBuilder</name>
<packaging>war</packaging>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.8.2</junit.version>
<spring.version>5.2.8.RELEASE</spring.version>
<mysql.version>8.0.28</mysql.version>
<mybatis.version>3.5.5</mybatis.version>
</properties>

<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!--数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 数据库连接池:c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>

<!-- pagehelper -->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>

<!-- dbcp的jar包 用于在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>


<!--Servlet、jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>


<!--Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--Mybatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>

<!--Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring操作数据库,还需要spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>

<!--lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>

【导入所需要的Jar包】

SSM整合记录_xml_05

1.3、创建数据库

创建一张用户表,用于演示用户管理系统的用户模块

CREATE TABLE `ssmbuilde`.`book`(  
`book_Id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书本编号',
`book_Name` VARCHAR(100) NOT NULL COMMENT '书名',
`price` float(11,2) NOT NULL COMMENT '单价',
PRIMARY KEY (`book_Id`)
) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci;

二、项目搭建

2.1、创建MVC三层架构

pojo(实体类)、mapper/mapper.xml(ORM映射)、Service/ServiceImpl(业务层)、Controller(控制层)

三、项目整合

3.1、配置Web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!-- 注册监听器ContextLoaderListener -->
<context-param>
<!--contextConfigLocation:表示配置文件位置路径的属性 -->
<param-name>contextConfigLocation</param-name>
<!--指定配置文件路径 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--注册声明过滤器,解决post请求乱码问题 -->
<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>
<!--强制request使用字符集encoding -->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制response使用字符集encoding -->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!--/*:表示强制所有请求先通过过滤器处理 -->
<url-pattern>/*</url-pattern>
</filter-mapping>

<!--项目启动后,实例化spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载springmvc的容器核心文件 -->
<init-param>
<!--springmvc配置文件的位置路径的属性 -->
<param-name>contextConfigLocation</param-name>
<!--指定文件路径 -->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--load-on-startup:表示tomcat启动是创建对象的顺序,数值越小,越早创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置映射的路径 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--使用斜杠"/" 原理:代替tomcat中的default,导致所有静态资源都交给DispatcherServlet处理, 默认情况下DispatcherServlet没有处理静态资源的能力,没有控制器对象能处理静态资源的访问,
所以访问静态资源(html,js,图片,css)请求都是404 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

注意顺序,先是过滤器、监听器、Servlet。同时在写完web.xml的时侯,还需要再资源目录(resources)下创建applicationContext.xml和Spring-MVC.xml的文件

3.2、配置applicationContext.xml

用于整合Spring、以及MyBatis的配置文件,包含了MyBatis的配置文件以及事物的相关操作

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

<!--1、dao-->
<!--在Spring容器的配置文件中加载属性文件-->
<!--关联数据库-->
<context:property-placeholder location="classpath:db.properties"/>
<!--连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<!-- 配置连接池属性 -->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--mybatis spring整合-->
<!--声明mybatis中提供的SqlSessionFactoryBean对象,这个类内部创建SqlSessionFactory的-->
<!--配置session工厂,SqlSessionFactoryBean:配置映射文件的bean,在mybatis-spring.jar中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
<!--注入mybatis全局配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

<!--mapper动态代理,加载mybatis映射文件-->
<!--创建dao对象,使用SqlSession的getMapper()方法
mapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象。
-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定sqlSessionFactory对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--注入sql映射文件包扫描器-->
<property name="basePackage" value="com.wei.mapper"/>
</bean>

<!--2、service-->
<!--@service注解扫描器-->
<context:component-scan base-package="com.wei.service"/>

<!--3、transaction-->
<!--声明事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>

<!--配置AOP通知-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<!--配置事务属性-->
<tx:attributes>
<!--添加事务管理的方法-->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="append*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="repair" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" read-only="true"/>
<tx:method name="search*" propagation="REQUIRED" read-only="true"/>
<!--SUPPORTS:有没有事务都可以-->
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>

<!--配置AOP切面-->
<aop:config>
<!--配置切入点,指定那些类需要使用事务-->
<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..service..*.*(..))"/>
</aop:config>
</beans>

3.3、配置Spring-MVC.xml

配置SpringMVC的配置文件,主要是视图解析器,静态资源以及注解驱动开启

<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.wei.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

</beans>

3.4、配置MyBatis

整合MyBatis时候,不需要再设置数据源,数据源将在Spring里完成,Mybatis的配置文件只需要设置别名(typealiases、日志以及驼峰命名转化),以及扫描的包。

<?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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true" />
<setting name="lazyLoadingEnabled" value="false"/>
</settings>
<!--设置别名-->
<typeAliases>
<!--扫描一个包-->
<package name="com.wei.pojo"></package>
</typeAliases>
</configuration>

【db.preperties】

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

四、编写前端

省略。。。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页查询</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>编号</th>
<th>书名</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items='${bookList}' var="books">
<tr>
<td>${books.bookId }</td>
<td>${books.bookName }</td>
<td>${books.price }</td>
<td>
<div>
<a href="${pageContext.request.contextPath}/ssm/add">添加书本</a>
<a href="${pageContext.request.contextPath}/ssm/update?book_Id=${books.bookId}">添加书本</a>
<a href="${pageContext.request.contextPath}/ssm/delete?book_Id=${books.bookId}" id="delBtn">删除书本</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>

</body>
</html>