SpringMVC_SSM整合
一、回顾SpringMVC访问接口流程
1.容器加载分析
-
容器分析

-
手动注册WebApplicationContext
public class ServletConfig extends AbstractDispatcherServletInitializer {@Overrideprotected WebApplicationContext createServletApplicationContext() {//获取SpringMVC容器AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.register(SpringMvcConfig.class);return context;}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}@Overrideprotected WebApplicationContext createRootApplicationContext() {return null;} }
2.容器加载过程分析
-
tomcat 服务器启动的时候,加载ServletConfig类之后,做初始化web容器操作,相当于 web.xml
-
执行注册容器的方法,获取 SpringMVC容器 WebApplicationContext
@Nullableprotected WebApplicationContext createRootApplicationContext() {Class<?>[] configClasses = this.getRootConfigClasses();if (!ObjectUtils.isEmpty(configClasses)) {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.register(configClasses);return context;} else {return null;}}protected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();Class<?>[] configClasses = this.getServletConfigClasses();if (!ObjectUtils.isEmpty(configClasses)) {context.register(configClasses);}return context;} -
通过@ComponentScan(“cn.sycoder.controller”) 加载 Controller 下面的bean 进 WebApplicationContext
@RestController public class TestController {@GetMapping("/test/{id}")public String test(@PathVariable Long id) {return "ok:" + id;} } -
把使用了 RequestMapping 注解的方法的 value — 对应一个方法,建立起了一对一映射关系(可以想象hashmap)
- /test/{id} ---- test 方法
3.请求接口过程
- 访问 http://localhost:8082/test/1
- 匹配 springmvc 的 / servletMapping 规则,交给 springmvc 处理
- 解析 /test/1路径找到对应的 test 方法
- 执行方法
- 因为使用 RestController ,所以返回方法的返回值作为响应体返回给浏览器
4.SSM整合会出现bean界定不清楚问题
- SpringMVC 需要加载哪些bean?
- controller 层(表现层即可)
- Spring 加载哪些bean?
- service
- dao
4.1如何处理
-
将spring配置注入到 web 容器中
@Configuration @ComponentScan(value={"cn.sycoder.service","cn.sycoder.dao"}) public class SpringConfig { }public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};} }
4.2验证两个容器的bean相互不干扰
-
验证代码
@Test public void test(){AnnotationConfigApplicationContext applicationContext =new AnnotationConfigApplicationContext(SpringConfig.class);ITestService bean = applicationContext.getBean(ITestService.class);bean.get(1L);TestController bean1 = applicationContext.getBean(TestController.class);System.out.println(bean1.test(1L)); }
二、SSM整合
1.SSM整合流程分析
- 概述SSM:Spring SpringMVC Mybatis
1.1创建工程
-
导入依赖
- ssm 所需要的依赖包
-
配置 web 项目入口配置替换 web.xml(AbstractAnnotationConfigDispatcherServletInitializer)
-
配置 Spring 配置类交给 web 容器管理
@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};} -
配置 SpringMVC 配置类交给 web 容器管理
@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};} -
配置请求拦截规则,交给 springmvc 处理
@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}
-
1.2配置 Spring
- SpringConfig
- @Configuration 标记Spring配置类,替换Spring-config-xml
- @ComponetScan 扫描需要被Spring 管理的bean
- @EnableTransactionManagment 启动管理事务支持
- @PropertySource 引入db.properties 配置文件
- 配置 JdbcConfig 配置类
- 使用德鲁伊 DataSource 数据源
- 构建平台事务管理器 DataSourceTransactionManager
- 配置 MyBatis 配置类
- 构建 SqlSessionFactoryBean
- 指定 MapperScanner 设置 mapper 包扫描寻找 mapper.xml 文件
1.3配置 SpringMVC
- 配置SpringMvcConfig
- @Configuration
- @ComponentScan 只扫描 Controller
- 开启SpringMVC 注解支持 @EnableWebMvc
1.4开发业务
- 使用注解
- 注入bean 注解
- @Autowired
- @RestController
- @GetMapping
- @RequestParam
- @PostMapping
- @RequestBody
- @DeleteMapping
- @PathVariable
- @PutMapping
- @GetMapping
- @Service
- @Transactional
- junit
- @RunWith
- @ContextConfiguration
- @Test
- 注入bean 注解
2.SSM整合
2.1导入依赖
-
依赖
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.17.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.17.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.17.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency></dependencies>
2.2创建各目录结构
-
目录如下

2.3创建SpringConfig
-
SpringConfig(在整合项目的时候不能扫描mvc的类,否则会出现创建容器失败)
@Configuration @ComponentScan(value = {"cn.sycoder.service","cn.sycoder.dao"}) @EnableTransactionManagement @PropertySource("classpath:db.properties") @Import({DbConfig.class,MybatisConfig.class}) public class SpringConfig { }
2.4创建DbConfig配置类
-
创建数据库配置文件
jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.username=root jdbc.password=123456 -
创建DbConfig
public class DbConfig {@Value("${jdbc.url}")private String url;@Value("${jdbc.driver}")private String driver;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** 配置德鲁伊连接池* @return*/@Beanpublic DataSource dataSource(){DruidDataSource source = new DruidDataSource();source.setUrl(url);source.setDriverClassName(driver);source.setPassword(password);source.setUsername(username);return source;}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager manager = new DataSourceTransactionManager();manager.setDataSource(dataSource);return manager;}}
2.5创建MybatisConfig配置类
-
MyBatisConfig
public class MybatisConfig {@Beanpublic SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource){SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setTypeAliasesPackage("cn.sycoder.domain");return bean;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer configurer = new MapperScannerConfigurer();configurer.setBasePackage("cn.sycoder.dao");return configurer;} }
2.6创建SpringMVC配置类
-
SpringMvcConfig
@Configuration @ComponentScan("cn.sycoder.controller") @EnableWebMvc public class SpringMvcConfig { }
2.7创建Web项目入口配置类
-
ServletConfig
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};//配置Spring交给Web 管理}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};} }
3.功能开发
3.1创建数据库及表
-
创建 ssm 数据库
-
创建 item 表
create table item (id bigint auto_increment,type varchar(64) null,name varchar(64) null,remark text null,constraint item_pkprimary key (id) );
3.2编写模型类
-
添加 lombok 依赖
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version> </dependency> -
模型类
@Data public class Item {private Long id;private String name;private String type;private String remark; }
3.3编写Mapper接口
-
Mapper 接口
@Repository public interface ItemMapper {@Insert("insert into item(name,type,remark) value(#{name},#{type},#{remark})")public int save(Item item);@Delete("delete from item where id = #{id}")public int delete(Long id);@Update("update item set name = #{name},type = #{type},remark=#{remark} where id=#{id}")public int update(Item item);@Select("select * from item where id = #{id}")public Item getById(Long id);@Select("select * from item")public List<Item> list();}
3.4编写Service接口和实现类
-
Service 接口
public interface IItemService {/*** 添加闲置物品方法* @param item* @return*/public boolean save(Item item);/*** 删除闲置物品* @param id* @return*/public boolean delete(Long id);/*** 更新闲置物品* @param item* @return*/public boolean update(Item item);/*** 查询闲置物品通过id* @param id* @return*/public Item getById(Long id);/*** 查询所有闲置商品* @return*/public List<Item> lists(); } -
定义接口实现类
@Service public class ItemServiceImpl implements IItemService {@AutowiredItemMapper mapper;@Override@Transactionalpublic boolean save(Item item) {return mapper.save(item) > 0;}@Override@Transactionalpublic boolean delete(Long id) {return mapper.delete(id) >0;}@Override@Transactionalpublic boolean update(Item item) {return mapper.update(item) >0;}@Overridepublic Item getById(Long id) {return mapper.getById(id);}@Overridepublic List<Item> lists() {return mapper.list();} }
3.5编写Contorller类
-
Controller
@RestController @RequestMapping("/item") public class ItemController {@AutowiredIItemService service;@PostMappingpublic boolean save(@RequestBody Item item){return service.save(item);}@PutMappingpublic boolean update(@RequestBody Item item){return service.update(item);}@DeleteMapping("/{id}")public boolean delete(@PathVariable Long id){return service.delete(id);}@GetMapping("/{id}")public Item getById(@PathVariable Long id){return service.getById(id);}@GetMappingpublic List<Item> list(){return service.lists();} }
4.验证 ssm 整合结果
-
启动项目并且解决问题

-
修改Spring配置类
@Configuration @ComponentScan(value = {"cn.sycoder.service","cn.sycoder.dao"}) @EnableTransactionManagement @PropertySource("classpath:db.properties") @Import({DbConfig.class,MybatisConfig.class}) public class SpringConfig { }
4.1添加item 数据
-
准备 item 数据
{"name":"键盘","type":"电脑外设","remark":"9成新,半价卖"}{"name":"笔记本","type":"电脑","remark":"9成新,8折出售"}{"name":"鞋子","type":"收藏鞋","remark":"科比签名的,独一无二"} -
添加数据

4.2修改数据
-
准备数据
{"id":4,"name":"二手鞋子","type":"废鞋","remark":"破鞋子"} -
修改操作

4.3查询单个数据
-
查询id=4的物品

4.4删除单个数据
-
删除id=4的物品

4.5查询全部数据操作
-
查询全部

5.整合单元测试
-
目录结构

-
新建测试类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringConfig.class) public class ItemTest {@AutowiredIItemService service;@Testpublic void save(){Item item = new Item();item.setName("单元测试");item.setRemark("单元测试");item.setType("单元测试");boolean save = service.save(item);System.out.println(save);}@Testpublic void update(){Item item = new Item();item.setId(5L);item.setName("单元测试");item.setRemark("单元测试");item.setType("单元测试");boolean save = service.update(item);System.out.println(save);}@Testpublic void getById(){Item byId = service.getById(5L);System.out.println(byId);}@Testpublic void list(){List<Item> lists = service.lists();System.out.println(lists);} }
三、项目实战中细节问题
1.导入前端资源
1.1静态资源拦截处理
-
设置访问 index 访问主页
@Controller public class IndexController {@RequestMapping("/index")public String index(){System.out.println("----------------");return "/pages/items.html";}} -
出现静态资源被拦截问题
@Configuration public class StaticSupport extends WebMvcConfigurationSupport {@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/js/**").addResourceLocations("/js/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");} } -
将 staticSupport 交给 SpringMvc 管理
@Configuration @ComponentScan(value = {"cn.sycoder.controller","cn.sycoder.config"}) @EnableWebMvc public class SpringMvcConfig { }
1.2项目实现
-
保存方法
handleAdd () {console.log("========")axios.post("/item",this.formData).then((res)=>{//todo}) }, -
列表查询
getAll() {axios.get("/item",).then((res)=>{this.dataList = res.data;}) }, -
删除操作
handleDelete(row) {axios.delete("/item/"+row.id).then((res)=>{//todo}) }
相关文章:
SpringMVC_SSM整合
一、回顾SpringMVC访问接口流程 1.容器加载分析 容器分析 手动注册WebApplicationContext public class ServletConfig extends AbstractDispatcherServletInitializer {Overrideprotected WebApplicationContext createServletApplicationContext() {//获取SpringMVC容器An…...
【操作系统】电脑上没有IIS怎么办
文章目录 前言一、查看二、解决 前言 有的新机刚开始在计算机-管理-服务下没有IIS网络服务怎么办。 一、查看 桌面计算机/此电脑 鼠标右键:管理 服务和应用 发现没有IIS 二、解决 控制面板 程序和功能 启动或关闭Windows功能 IIS相关的所有功能选中ÿ…...
【vue】vue项目中批量下载文件并打压缩包
前言 一开始用的是循环单个文件下载,即从后台获取到文件url列表,循环对每个url单独进行下载,这样的问题是每调用一次下载,浏览器都会进行“另存为”的弹框,很麻烦!!! 关闭“下载前…...
Linux中的软件管家——yum
目录 编辑 一,软件安装的方式 二,对yum的介绍 1.yum的作用 2,yum的库 三,yum下载软件的操作 1.yumlist 2.yuminstall 3.yumremove 四,yum源的转换 一,软件安装的方式 软件安装的方式大概分为三种…...
安卓绘制原理概览
绘制原理 Android 程序员都知道 Android 的绘制流程分为 Measure、Layout、Draw 三步骤,其中 Measure 负责测量 View 的大小Layout 负责确定 View 的位置Draw 负责将 View 画在屏幕上 由 ViewRootImpl 实现的 performTraversal 方法是 Measure、layout、draw 的真正…...
接口测试工具开发文档
1 开发规划 1.1 开发人员 角 色 主要职责 负责模块 人员 备注 n xxx模块 xxx 1.2 开发计划 <附开发计划表> 1.3 开发环境和工具 开发工具 工具 作用 Notepad 编辑器 Perl 解释器 2 总体设计 设计思路:因为测试app和server。首先必须…...
面试题速记:JavaScript有哪些数据类型,它们的区别是?
JavaScript有哪些数据类型,它们的区别? JavaScript共有八种数据类型,分别是 Undefined、Null、Boolean、Number、String、Object、Symbol、BigInt。 其中 Symbol 和 BigInt 是ES6 中新增的数据类型: ●Symbol 代表创建后独一无二…...
Spring Cloud面试题
为什么需要学习Spring Cloud 不论是商业应用还是用户应用,在业务初期都很简单,我们通常会把它实现为单体结构的应用。但是,随着业务逐渐发展,产品思想会变得越来越复杂,单体结构的应用也会越来越复杂。这就会给应用带…...
计算机网络自顶向下-web页面请求历程
1. 准备: DHCP、 UDP、 IP 和以太网 假定 Bob 启动他的便携机,然后将其用一根以太网电缆连接到学校的以太网交换机 , 交换机与学校的路由器相连。学校的路由器与一个 ISP 连接, 本例中 ISP 为 comcast.net ,为学校提供了 DNS 服务…...
打造西南交通感知新范式,闪马智能携手首讯科技落地创新中心
9月4日,2023年中国国际智能产业博览会(以下简称“智博会”)在重庆拉开帷幕。大会期间,由上海闪马智能科技有限公司(以下简称“闪马智能”)与重庆首讯科技股份有限公司(以下简称“首讯科技”&…...
Android11去掉Settings中的网络和互联网一级菜单
碰到一个不要wifi不要蓝牙的项目,客户要求去掉Settings中的网络和互联网一级菜单,因为硬件都不贴,所以软件对应也要去掉。 我们可以根据packages/apps/Settings/res/xml/top_level_settings.xml的布局文件找到TopLevelNetworkEntryPreferenc…...
基于Python开发的五子棋小游戏(源码+可执行程序exe文件+程序配置说明书+程序使用说明书)
一、项目简介 本项目是一套基于Python开发的五子棋小游戏,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Python学习者。 包含:项目源码、项目文档、数据库脚本等,该项目附带全部源码可作为毕设使用。 项目都经过严格调试&a…...
JDBC入门到精通-10w总结
JDBC核心技术 笔记是以尚硅谷讲师宋红康JDBC课程为基础,加入自身学习体会,略有修改 第1章:JDBC概述 JDBC是java应用程序和数据库之间的桥梁。JDBC提供一组规范(接口)。向上是面向应用API,共应用程序使用。向…...
Linux之查看so/bin依赖(三十一)
简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长! 优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀 人生格言: 人生…...
day-45 代码随想录算法训练营(19)动态规划 part 07
70.爬楼梯(进阶) 分析:基本动态规划转换为完全背包,因为1、2 两种上楼梯方式是无限选择的 思路: 1. j 表示 容量为 j 时,装满有dp[j]种方法2. dp[j]dp[j-nums[i]]3. 初始化 dp[0]1,dp[1]14. 遍历顺序&am…...
static关键字和final关键字
在java的关键字中,static关键字和final关键字是两个必须掌握的关键字。static关键字和final关键字用法多样,且在一定环境下使用,可以提高程序的运行性能,优化程序的结构。下面将依次介绍static关键字和final关键字。注意ÿ…...
使用Postman如何在接口测试前将请求的参数进行自定义处理
1、前言 当我们使用 Postman 进行接口测试时,对于简单的不需要处理的接口,直接请求即可,但是对于需要处理的接口,如需要转码、替换值等,则就麻烦一些,一般我们都是先手动把修改好的值拷贝到请求里再进行请…...
QT第二天
1.优化登陆界面,当点击登录按钮后,在该按钮对应的槽函数中,判断账户和密码框内的数据是否为admin和123456,如果账户密码匹配成功,则提示登陆成功并关闭登录界面,如果账户密码匹配失败,则提示登录…...
鸿蒙应用程序入口UIAbility详解
一、UIAbility概述 UIAbility是一种包含用户界面的应用组件,主要用于和用户进行交互。UIAbility也是系统调度的单元,为应用提供窗口在其中绘制界面。每一个UIAbility实例,都对应于一个最近任务列表中的任务。一个应用可以有一个UIAbility&am…...
扫地僧站群·静态养站王:自动万站智能LOGO功能说明
扫地僧站群静态养站王:自动万站智能LOGO功能说明,无需配置,自动根据网站状态生成对应LOGO,高质量LOGO万站不重样.说明:模板调用智能LOGO方式:{当前域名}/logo.png 自动识别HTTP/HTTPS 只需在模板需要展示LOGO的地方放上如上标签即可。以下为L…...
浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)
✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义(Task Definition&…...
Python爬虫实战:研究MechanicalSoup库相关技术
一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...
基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真
目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销,平衡网络负载,延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...
循环冗余码校验CRC码 算法步骤+详细实例计算
通信过程:(白话解释) 我们将原始待发送的消息称为 M M M,依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)(意思就是 G ( x ) G(x) G(x) 是已知的)࿰…...
基于数字孪生的水厂可视化平台建设:架构与实践
分享大纲: 1、数字孪生水厂可视化平台建设背景 2、数字孪生水厂可视化平台建设架构 3、数字孪生水厂可视化平台建设成效 近几年,数字孪生水厂的建设开展的如火如荼。作为提升水厂管理效率、优化资源的调度手段,基于数字孪生的水厂可视化平台的…...
Axios请求超时重发机制
Axios 超时重新请求实现方案 在 Axios 中实现超时重新请求可以通过以下几种方式: 1. 使用拦截器实现自动重试 import axios from axios;// 创建axios实例 const instance axios.create();// 设置超时时间 instance.defaults.timeout 5000;// 最大重试次数 cons…...
什么?连接服务器也能可视化显示界面?:基于X11 Forwarding + CentOS + MobaXterm实战指南
文章目录 什么是X11?环境准备实战步骤1️⃣ 服务器端配置(CentOS)2️⃣ 客户端配置(MobaXterm)3️⃣ 验证X11 Forwarding4️⃣ 运行自定义GUI程序(Python示例)5️⃣ 成功效果QCamera控制观察视角QPointLight点光源QConeMesh圆锥几何网格QTransform控制实体的位置/旋转/缩放QPhongMaterialPhong光照材质(定义颜色、反光等)QFirstPersonC…...
【电力电子】基于STM32F103C8T6单片机双极性SPWM逆变(硬件篇)
本项目是基于 STM32F103C8T6 微控制器的 SPWM(正弦脉宽调制)电源模块,能够生成可调频率和幅值的正弦波交流电源输出。该项目适用于逆变器、UPS电源、变频器等应用场景。 供电电源 输入电压采集 上图为本设计的电源电路,图中 D1 为二极管, 其目的是防止正负极电源反接, …...
C语言中提供的第三方库之哈希表实现
一. 简介 前面一篇文章简单学习了C语言中第三方库(uthash库)提供对哈希表的操作,文章如下: C语言中提供的第三方库uthash常用接口-CSDN博客 本文简单学习一下第三方库 uthash库对哈希表的操作。 二. uthash库哈希表操作示例 u…...
