> 文章列表 > SSM整合-Spring整合SringMVC、Mybatis,ssm测试

SSM整合-Spring整合SringMVC、Mybatis,ssm测试

SSM整合-Spring整合SringMVC、Mybatis,ssm测试

SSM 整合简介

一、SSM整合介绍

​ SSM(Spring + SpringMVC + Mybatis) 整合,就是三个框架协同开发。

二、框架分工

  1. Spring 整合 Mybatis,就是将 Mybatis 核心配置分拣当中数据源的配置、事务管理、工厂的配置、Mapper接口的实现类等 交给Spring进行管理。
    • mybatisConfig.xml配置信息 整合到 SpringConfig.xml
  2. Spring 整合 SpringMVC,就是在web.xml当中添加监听器,当服务器启动,监听器触发,监听器执行了Spring的核心配置文件,核心配置文件被加载
    • 在web.xml中添加监听器,执行SpringMVCConfig.xml文件。

三、整合核心步骤

  1. Spring 基础框架单独运行
  2. SpringMVC 框架单独运行
  3. Spring 整合SpringMVC 框架
  4. Spring 整合Mybatis 框架
  5. 测试SSM 整合结果

SSM 整合环境配置

Spring 基础框架单独运行

一、项目结构

在这里插入图片描述

二、项目搭建

1、创建maven项目并导入依赖-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>com.etime</groupId><artifactId>day0420</artifactId><version>1.0-SNAPSHOT</version><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.5.RELEASE</spring-version><mybatis-version>3.4.6</mybatis-version></properties><dependencies><!--mybatis相关包--><!--mysql的驱动包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!--mybatis核心--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis-version}</version></dependency><!--连接池--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!--日志包--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!--分页插件--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.10</version></dependency><!--spring相关的--><!--springIOC包--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring-version}</version></dependency><!--jdbc--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring-version}</version></dependency><!--织入器包:--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency><!--springmvc依赖:--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring-version}</version></dependency><!--解析器包--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><!--文件上传--><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><!--spring整合mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.2</version></dependency><!--spring整合junit--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.16</version></dependency></dependencies>
</project>

2、创建实体类

package com.etime.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {private int sid;private String name;private int cid;
}

3、编写业务逻辑层接口及实现类

(1)业务逻辑层接口
package com.etime.service;import com.etime.pojo.Student;import java.util.List;public interface StudentService {List<Student> getAllStudent();
}
(2)业务逻辑层实现类
package com.etime.service.impl;import com.etime.pojo.Student;
import com.etime.service.StudentService;import java.util.List;public class StudentServiceImpl implements StudentService {@Overridepublic List<Student> getAllStudent() {System.out.println("StudentService getAllStudent Method!");return null;}
}

4、编写 Spring 核心配置文件

  • 在SpringConfig.xml文件中
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--扫描包下的组件(注解)--><context:component-scan base-package="com.etime.service"></context:component-scan>
</beans>

5、测试 Spring 独立运行

package com.etime.test;import com.etime.service.StudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*RunWith:是一个运行器,测试时 运行交给Spring的环境来进行自动创建Spring的应用上下文*/
@RunWith(SpringJUnit4ClassRunner.class)
// 加载Spring的配置文件
@ContextConfiguration("classpath:SpringConfig.xml")
public class SsmTest {// 自动注入@Autowiredprivate StudentService studentService;@Testpublic void SpringTest(){studentService.getAllStudent();}
}
// 结果
StudentService getAllStudent Method!Process finished with exit code 0

SpringMVC 框架单独运行

一、项目结构

在这里插入图片描述

二、项目搭建

1、在 web.xml 中配置核心控制器(DispatcherServlet)

<?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"><!--注册、配置前端控制器--><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--Spring整合:加载SpringMVC的配置文件--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:SpringMVCConfig.xml</param-value></init-param></servlet><!--设置Servlet的映射路径--><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><!--/:根路径下,所有的文件都要经过该Servlet--><url-pattern>/</url-pattern></servlet-mapping>
</web-app>

2、创建SpringMVC核心配置文件 SpringMVCConfig.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:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--配置注解扫描器--><context:component-scan base-package="com.etime.controller"></context:component-scan><!--处理器配置--><mvc:annotation-driven></mvc:annotation-driven><!--配置视图解析器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean>
</beans>

3、创建构造器 进行测试

package com.etime.controller;import com.etime.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
@RequestMapping("/student")
public class StudentController {@GetMapping("springMvcTest")@ResponseBodypublic Student springMvcTest(){return new Student(1,"胡神",1);}
}

在这里插入图片描述

Spring 整合SpringMVC 框架

一、项目结构

​ 与 SpringMVC 框架单独运行 的项目结构一样

二、项目搭建

1、在 web.xml中 加载Spring核心配置文件及添加监听器

<!--加载Spring的核心配置文件-->
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:SpringConfig.xml</param-value>
</context-param>
<!--配置一个监听器:ServletContext-->
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2、修改StudentService实现类与控制器代码 并测试

(1)StudentServiceImpl实现类
package com.etime.service.impl;import com.etime.pojo.Student;
import com.etime.service.StudentService;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {@Overridepublic List<Student> getAllStudent() {System.out.println("StudentService getAllStudent Method!");Student s1 = new Student(1,"tom",1);Student s2 = new Student(2,"jack",2);Student s3 = new Student(3,"macy",3);List<Student> list = new ArrayList<>();list.add(s1);list.add(s2);list.add(s3);return list;}
}
(2)StudentController
package com.etime.controller;import com.etime.pojo.Student;
import com.etime.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;@Controller
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("springMvcTest")@ResponseBodypublic List<Student> springMvcTest(){return studentService.getAllStudent();}
}

在这里插入图片描述

Spring 整合Mybatis 框架

一、项目结构

在这里插入图片描述

二、项目搭建

1、编写数据持久层接口StudentMapper.java

package com.etime.mapper;import com.etime.pojo.Student;import java.util.List;public interface StudentMapper {List<Student> getAllStudent();
}

2、编写Mybatis核心配置文件StudentMapper.xml (或使用注解)

<?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.etime.mapper.StudentMapper"><select id="getAllStudent" resultType="Student">select * from student</select>
</mapper>

3、Spring 整合 Mybatis配置

(1)数据库配置文件jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_418
root=root
password=root
(2)在 SpringConfig.xml 文件中配置数据源
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--扫描包下的组件(注解)--><context:component-scan base-package="com.etime.service"></context:component-scan><!-- 注册Mybatis映射文件--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.etime.mapper"></property></bean><!--数据源--><!--加载jdbc.properties属性文件--><context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${driver}"/><property name="jdbcUrl" value="${url}"/><property name="user" value="${root}"/><property name="password" value="${password}"/></bean><!--Mybatis的核心工厂对象--><bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源--><property name="dataSource" ref="dataSource"></property><!--实体类取别名--><property name="typeAliasesPackage" value="com.etime.pojo"></property><!--mapper 文件的位置--><property name="mapperLocations" value="classpath:com/etime/mapper/*.xml"></property><!--配置分页插件--><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><value>ue>helperDialect=mysqlreasonable=truesupportMethodsArguments=trueparams=count=countSqlautoRuntimeDialect=true</value></property></bean></array></property></bean>
</beans>
(3) 在SpringConfig.xml文件中配置事务处理及事务的注解使用权限
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--注入数据源--><property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启注解式事务-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

4、修改StudentService的实现类中的方法 并测试

package com.etime.service.impl;import com.etime.mapper.StudentMapper;
import com.etime.pojo.Student;
import com.etime.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper studentMapper;@Overridepublic List<Student> getAllStudent() {return studentMapper.getAllStudent();}
}

在这里插入图片描述

SSM 整合测试

  • 需求分析:查询所有学生信息,利用Mybatis分页插件进行分页

一、实体类编写

1、班级类

package com.etime.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@NoArgsConstructor
@AllArgsConstructor
@Data
public class Classes {private int cid;private String cname;
}

2、学生类

package com.etime.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {private int sid;private String sname;private int cid;private Classes classes;
}

二、编写数据持久层

1、编写接口 StudentMapper.java中的方法

package com.etime.mapper;import com.etime.pojo.Student;import java.util.List;public interface StudentMapper {List<Student> getAllStudent();
}

2、编写映射文件 StudentMapper.xml 配置信息

<?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.etime.mapper.StudentMapper"><select id="getAllStudent" resultMap="studentAndClasses">select * from student s,classes c where s.cid=c.cid</select><resultMap id="studentAndClasses" type="Student"><id property="sid" column="sid"></id><result property="sname" column="sname"></result><result property="cid" column="cid"></result><association property="classes" javaType="Classes"><id property="cid" column="cid"></id><result property="cname" column="cname"></result></association></resultMap>
</mapper>

三、编写业务逻辑层

1、编写接口 StudentService.java中的方法

package com.etime.service;import com.etime.pojo.Student;
import com.github.pagehelper.PageInfo;public interface StudentService {PageInfo<Student> getAllStudent(int pageNum, int pageSize);
}

2、编写接口实现类中的方法

package com.etime.service.impl;import com.etime.mapper.StudentMapper;
import com.etime.pojo.Student;
import com.etime.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentMapper studentMapper;@Overridepublic PageInfo<Student> getAllStudent(int pageNum, int pageSize) {PageHelper.startPage(pageNum,pageSize);List<Student> list = studentMapper.getAllStudent();PageInfo<Student> pageInfo = new PageInfo<>(list);return pageInfo;}
}

四、编写控制层

1、编写 StudentController.java中的执行方法

package com.etime.controller;import com.etime.pojo.Student;
import com.etime.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;import java.util.List;@Controller
@RequestMapping("/student")
/*解决跨域问题*/
@CrossOrigin
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("ssmTest")@ResponseBodypublic PageInfo<Student> ssmTset(int pageNum, int pageSize){return studentService.getAllStudent(pageNum,pageSize);}
}

五、编写前端页面

1、index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title><script src="js/vue.global.js"></script><script src="js/axios.min.js"></script>
</head>
<body><div id="app"><table border="1" cellspacing="0" cellpadding="0" align="center" width="500"><tr><th>学号</th><th>姓名</th><th>班级编号</th></tr><tr v-for="(stu,index) in students"><td>{{stu.sid}}</td><td>{{stu.sname}}</td><td>{{stu.classes.cname}}</td></tr></table><div style="width: 500px;margin: auto;"><a href="javaScript:void(0)" @click="getStudentByPage(1)">首页</a><a href="javaScript:void(0)" @click="getStudentByPage(prePage)">上一页</a>{{pageNum}}/{{pageTotal}}<a href="javaScript:void(0)" @click="getStudentByPage(nextPage)">下一页</a><a href="javaScript:void(0)" @click="getStudentByPage(pageTotal)">尾页</a></div></div><script>const vueApp = Vue.createApp({data() {return {students:"",pageNum:"",pageTotal:"",prePage:"",nextPage:"",}},methods: {getStudentByPage(page){axios({url:"http://localhost:8080/day0420_war_exploded/student/ssmTest?pageNum="+page+"&pageSize=3",method:"get",}).then(resp =>{console.log(resp.data);this.students = resp.data.list;this.pageNum = resp.data.pageNum;this.pageTotal = resp.data.pages;this.prePage = resp.data.prePage;if (this.prevPage <= 0) {this.prevPage = 1;}this.nextPage = resp.data.nextPage;});}},created() {this.getStudentByPage(1);},});vueApp.mount("#app");</script>
</body>
</html>

在这里插入图片描述