SSM 整合简介
SSM整合是指将Spring、Spring MVC和MyBatis三个开源框架结合使用,来搭建企业级Java Web应用的后端架构。每个框架在整体架构中承担不同的职责:
- Spring:作为核心控制层框架,负责管理对象(Bean)的生命周期以及依赖注入(DI),通过IoC容器简化了组件之间的耦合关系,并提供了AOP(面向切面编程)支持。
- Spring MVC:是Spring框架的一部分,专注于处理Web层请求响应的模型-视图-控制器(MVC)设计模式。它负责接收HTTP请求,解析参数,调用业务服务层,然后返回视图给客户端。
- MyBatis:是一个持久层框架,它与JDBC相结合,提供了一种更加灵活的方式来操作数据库。MyBatis可以自动生成SQL语句,执行数据库操作,并且通过映射文件或注解将结果集自动转换为Java对象。
常见组合:
常见框架集成组合:SSH 和 SSM
SSH: Spring + Struts + Hibernate 【已过时】
SSM : Spring+SpringMVC+Mybatis ( MyBatisPlus )
版本
Spring6 + JDK17 + Tomcat10 + MySql8 +Maven
Spring5 + JDK17(或之前) + Tomcat9 + MySql8 +Maven
步骤思路
思路:
- Spring + mybatis (先使用 Spring 整合 MyBatis )
- SpringMVC + Spring + Mybatis(在 Spring 整合 SpringMVC)
详细步骤:
新建 Maven Web 项目
配置 pom.xml 依赖
- mybatis 、spring-webmvc、mysql驱动、lombok、jstl、servlet、junit、mybatis-spring 、spring-orm、druid连接池
mybatis 相关配置文件
- mybatis-connfig.xml 、db.properties、mapper.xml
- mybatis-config.xml:别名、SQL日志、数据源配置(username,password,url,driver)
- mapper.xml : insert 、select、update、delete
spring + mybatis 相关配置
spring.xml:扫描基包
DataSource、SessionFactory、扫描Mapper接口包
数据库的设计及初始化
代码:
- pojo
- dao 接口
- service
- 编写mapper.xml ,编写SQL
springmvc 相关配置
- web.xml、springmvc.xml
详细步骤
1. 建库建表
CREATE DATABASE booksys;
USE booksys;
CREATE TABLE book(bookid INT PRIMARY KEY AUTO_INCREMENT,bookname VARCHAR(50),price FLOAT,author VARCHAR(50),pubDate DATE,ADDDATE DATETIME,modDate DATETIME
);
2. 新建 Maven Web项目
- 方式一:普通 Maven 选择 Web 骨架
- 手动新建 java 目录
- 手动新建 test 目录
- 方式二:jakartaEE -> 选择 Web Application 模板
- 自动生成 java 目录、webapp目录、test 目录
- 自动配置部分基础依赖
3. 配置 pom.xml
mybatis 、spring-webmvc、mysql驱动、lombok、jstl、servlet、junit、mybatis-spring 、spring-orm、druid连接池
完整配置:
<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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.wdzl.booksys</groupId><artifactId>ssm2023</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>ssm2023 Maven Webapp</name><url>http://maven.apache.org</url><properties><spring-version>5.3.9</spring-version></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.9</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency></dependencies><build><finalName>ssm2023</finalName></build>
</project>
4. spring + mybatis 整合
1)新建 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><!--日志配置--><setting name="logImpl" value="STDOUT_LOGGING"/></settings><typeAliases><package name="com.wdzl.pojo"/></typeAliases></configuration>
连接数据库--映射文件---DAO接口---POJO实体类
2)新建实体类
package com.wdzl.pojo;import lombok.Data;import java.util.Date;@Data
public class Book {private Integer bookId;private String bookName;private float price;private String author;private Date pubDate;private Date modDate;private Date addDate;
}
3)Dao 接口
package com.wdzl.dao;import com.wdzl.pojo.Book;import java.util.List;public interface IBookDao {List<Book> queryAll();void save(Book book);
}
4)mapper映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wdzl.dao.IBookDao"><select id="queryAll" resultType="book">select bookid,bookname,price,author,pubDate,addDate,modDate from book</select><insert id="save" parameterType="book">insert into book(bookid,bookname,price,author,pubDate,addDate,modDate)values(#{bookName},#{price},#{author},#{pubDate},#{addDate},#{modDate})</insert>
</mapper>
5)spring 整合mybatis的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"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"><context:component-scan base-package="com.wdzl"/><context:property-placeholder location="classpath:db.properties"/><!--spring+mybatis整合请求 > Dispatcher > Controller > Service > Dao > SessionFactory > DataSource > MySQL--><!--DataSource--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/></bean><!--SessionFactory--><bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:mapper/*.xml"/><property name="configLocation" value="classpath:mybatis-config.xml"/></bean><!--Mybatis 接口扫描--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.wdzl.dao"/>
<!-- <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>--></bean></beans>
6)新建业务并注解
新建接口
package com.wdzl.service;import com.wdzl.pojo.Book;import java.util.List;public interface IBookService {List<Book> queryAll();void save(Book book);
}
新建实现类
package com.wdzl.service;import com.wdzl.dao.IBookDao;
import com.wdzl.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class BookServiceImpl implements IBookService{@Autowiredprivate IBookDao bookDao;@Overridepublic List<Book> queryAll() {return bookDao.queryAll();}@Overridepublic void save(Book book) {bookDao.save(book);}
}
7)单元测试
测试 Spring 和 mybatis 是否整合成功
- 添加 junit 和 Spring-Test 依赖
- 新建 test 测试目录
- 编写测试用例
- 在src 目录下新建 test 目录
添加 junit 4 依赖 :
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope>
</dependency>
添加 spring-test 依赖
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring-version}</version>
</dependency>
编写测试用例
新建 test 目录
新建 测试用例类
- 使用注解
- 依赖注入
import com.wdzl.service.IBookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@SpringJUnitConfig(locations = "classpath:spring-dao.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class SSMTest {@Autowiredprivate IBookService bookService;@Testpublic void testSsm(){bookService.queryAll().forEach(System.out::println);}}
5. SpringMVC+Spring
- web.xml
- springmvc.xml
- 编写控制器
- 依赖业务
1)配置 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><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
2)新建和配置 spring-mvc.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: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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"><mvc:annotation-driven/><!--视图解析器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp"></property><property name="suffix" value=".jsp"></property></bean><!--静态资源-->
</beans>
3)新建控制器
package com.wdzl.controller;import com.wdzl.pojo.Book;
import com.wdzl.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controller
public class BookController {@Autowiredprivate IBookService bookService;@RequestMapping("list")public String queryAll(ModelMap modelMap){List<Book> books = bookService.queryAll();modelMap.put("list",books);return "list";}
}
4)新建 list.jsp
<%@ 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>
<c:forEach items="${list}" var="book">${book}
</c:forEach>
</body>
</html>
5) 部署 和 运行
注意:访问 list 时,爆出404 异常
原因: web 项目 元数据文件为 web.xml (程序入口)
发现通过web.xml 不能关联所有的其他 spring-dao.xml和其他映射文件等
解决办法:
- 新建 spring文件 命名 spring-ssm.xml
- 在此文件中 导入其他的文件:spring-dao.xml 和 spring-mvc.xml
- 再修改 web.xml :导入加载的文件为:spring-ssm.xml
新建 spring-ssm.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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><import resource="classpath:spring-dao.xml"/><import resource="classpath:spring-mvc.xml"/>
</beans>
修改 web.xml
<init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-ssm.xml</param-value>
</init-param>
完整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><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-ssm.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
打开浏览器,通过控制器的 RequestMapping("list") 映射的 list 请求访问即可。