当前位置: 首页 > news >正文

SpringBoot 整合 SpringMVC:SpringMVC的注解管理

  1. 分类:
    1. 中央转发器(DispatcherServlet)
    2. 控制器
    3. 视图解析器
    4. 静态资源访问
    5. 消息转化器
    6. 格式化
    7. 静态资源管理
  2. 中央转发器:
    1. 中央转发器被 SpringBoot 自动接管,不需要我们在 web.xml 中配置:
      <servlet><servlet-name>chapter2</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping><servlet-name>chapter2</servlet-name><url-pattern>/</url-pattern>
      </servlet-mapping>
    2. 中央转发器被 SpringBoot 自动接管,不需要我们在 web.xml 中配置,我们现在的项目也不是 web 项目,也不存在 web.xml
    3. 查看 DispatcherServlet:
      org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,/
  3. 控制器:
    1. 控制器 Controller 在 SpringBoot 的注解扫描范围内自动管理
  4. 视图解析器自动管理:
    1. Inclusion  of  ContentNegotiatingViewResolver  and  BeanNameViewResoler  Beans
    2. ContentNegotiatingViewResoler:组合所有的视图解析器
    3. 无需再配置曾经的配置文件:
      <bean id="de" class="org.springframework.web.servlet.view.InternalResourceViewResolver">property name="prefix" value="/WEB-INF/jsp/"></property>property name="suffix" value="*.jsp"></property>
      bean>
    4. 源码:
      public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));resolver.setOrder(-2147483648);return resolver;
      }}
    5. 当我们做文件上传的时候 multpartResolver  是自动被配置好的页面
      1. 页面:
        <form action="/upload" method="post" enctype="multipart/form-data">input name="pic" type="file">input type="submit">
        form>
      2. Controller:
        @ResponseBody
        @RequestMapping("/upload")
        public String upload(@RequestParam("pic")MultipartFile file, HttpServletRequest request){String contentType = file.getContentType();String fileName = file.getOriginalFilename();
        /*System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);*///String filePath = request.getSession().getServletContext().getRealPath("imgupload/");String filePath = "D:/imgup/";try {this.uploadFile(file.getBytes(), filePath, fileName);} catch (Exception e) {// TODO: handle exception}return "success";
        }public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {File targetFile = new File(filePath);if(!targetFile.exists()){targetFile.mkdirs();}FileOutputStream out = new FileOutputStream(filePath+fileName);out.write(file);out.flush();out.close();
        };
    6. 文件上传可以通过配置来修改
      1. 打开 application.properties,默认限制是 10 MB,可以任意修改
  5. 消息转换和格式化:
    1. SpringBoot 自动配置了消息转换器
    2. 格式转换器的自动注册:
    3. 时间类型可以修改:
  6. 欢迎页面的自动装配:
    1. SpringBoot 自动指定 resources 下的 index.html
  7. SpringBoot 扩展 SpringMVC:
    1. 通过实现 WebMvcConfigurer 接口来扩展
      public interface WebMvcConfigurer {default void configurePathMatch(PathMatchConfigurer configurer) {}default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}default void configureAsyncSupport(AsyncSupportConfigurer configurer) {}default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {}default void addFormatters(FormatterRegistry registry) {}default void addInterceptors(InterceptorRegistry registry) {}default void addResourceHandlers(ResourceHandlerRegistry registry) {}default void addCorsMappings(CorsRegistry registry) {}default void addViewControllers(ViewControllerRegistry registry) {}default void configureViewResolvers(ViewResolverRegistry registry) {}default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {}default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {}default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}@Nullabledefault Validator getValidator() {return null;}@Nullabledefault MessageCodesResolver getMessageCodesResolver() {return null;}
      }
  8. 在容器中注册视图控制器(请求转发):
    1. 创建一个 MyMvcConfig 实现 WebMvcConfigurer 接口,实现 addViewController 方法,完成通过 /tx 访问,转发到 success.html 的工作
      @Configuration
      public class MyMVCCofnig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/tx").setViewName("success");}
      }
  9. 注册格式化器:
    1. 用来可以对请求过来的日期格式化的字符串来做指定化
    2. 通过 application.properties 配置也可以办到
      @Override
      public void addFormatters(FormatterRegistry registry) {registry.addFormatter(new Formatter<Date>() {@Overridepublic String print(Date date, Locale locale) {return null;}@Overridepublic Date parse(String s, Locale locale) throws ParseException {return new SimpleDateFormat("yyyy-MM-dd").parse(s);}});
      }
  10. 消息转换器扩展 fastjson:
    1. 在 pom.xml 中引入 fastjson:
      <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version>
      </dependency>
    2. 配置消息转换器,添加 fastjson:
      @Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>>    FastJsonHttpMessageConverter fc = 
      converters) {new FastJsonHttpMessageConverter();    FastJsonConfig fastJsonConfig = new FastJsonConfig();   fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);    fc.setFastJsonConfig(fastJsonConfig);    converters.add(fc);
    3. 在实体类中控制:
      public class User {private String username;private String password;private int age;private int score;private int gender;@JSONField(format = "yyyy-MM-dd")private Date date;
      }
  11. 拦截器注册:
    1. 创建拦截器
      public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("前置拦截");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("后置拦截");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("最终拦截");}
      }
    2. 注册拦截器:
      @Override
      public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/hello2");
      }

相关文章:

SpringBoot 整合 SpringMVC:SpringMVC的注解管理

分类&#xff1a; 中央转发器(DispatcherServlet)控制器视图解析器静态资源访问消息转化器格式化静态资源管理 中央转发器&#xff1a; 中央转发器被 SpringBoot 自动接管&#xff0c;不需要我们在 web.xml 中配置&#xff1a; <servlet><servlet-name>chapter2&l…...

松灵机器人 scout ros2 驱动 安装

必须使用 ubuntu22 必须使用 链接的humble版本 #打开can 口 sudo modprobe gs_usbsudo ip link set can0 up type can bitrate 500000sudo ip link set can0 up type can bitrate 500000sudo apt install can-utilscandump can0mkdir -p ~/ros2_ws/srccd ~/ros2_ws/src git cl…...

使用 Numpy 自定义数据集,使用pytorch框架实现逻辑回归并保存模型,然后保存模型后再加载模型进行预测,对预测结果计算精确度和召回率及F1分数

1. 导入必要的库 首先&#xff0c;导入我们需要的库&#xff1a;Numpy、Pytorch 和相关工具包。 import numpy as np import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import accuracy_score, recall_score, f1_score2. 自定义数据集 …...

MapReduce简单应用(一)——WordCount

目录 1. 执行过程1.1 分割1.2 Map1.3 Combine1.4 Reduce 2. 代码和结果2.1 pom.xml中依赖配置2.2 工具类util2.3 WordCount2.4 结果 参考 1. 执行过程 假设WordCount的两个输入文本text1.txt和text2.txt如下。 Hello World Bye WorldHello Hadoop Bye Hadoop1.1 分割 将每个文…...

c语言(关键字)

前言&#xff1a; 感谢b站鹏哥c语言 内容&#xff1a; 栈区&#xff08;存放局部变量&#xff09; 堆区 静态区&#xff08;存放静态变量&#xff09; rigister关键字 寄存器&#xff0c;cpu优先从寄存器里边读取数据 #include <stdio.h>//typedef&#xff0c;类型…...

蓝桥杯思维训练营(一)

文章目录 题目总览题目详解翻之一起做很甜的梦 蓝桥杯的前几题用到的算法较少&#xff0c;大部分考察的都是思维能力&#xff0c;方法比较巧妙&#xff0c;所以我们要积累对应的题目&#xff0c;多训练 题目总览 翻之 一起做很甜的梦 题目详解 翻之 思维分析&#xff1a;一开…...

【C语言】结构体对齐规则

文章目录 一、内存对齐规则二、结构体的整体对齐&#xff1a; 一、内存对齐规则 1.第一个数据成员&#xff1a;结构体的第一个数据成员总是放置在其起始地址处&#xff0c;即偏移量为0的位置。 2.其他数据成员的对齐&#xff1a;每个后续成员的存储地址必须是其有效对齐值的整…...

2025-工具集合整理

科技趋势 github-rank &#x1f577;️Github China/Global User Ranking, Global Warehouse Star Ranking (Github Action is automatically updated daily). 科技爱好者周刊 制图工具 D2 D2 A modern diagram scripting language that turns text to diagrams 文档帮助 …...

快速提升网站收录:利用网站用户反馈机制

本文转自&#xff1a;百万收录网 原文链接&#xff1a;https://www.baiwanshoulu.com/59.html 利用网站用户反馈机制是快速提升网站收录的有效策略之一。以下是一些具体的实施步骤和建议&#xff1a; 一、建立用户反馈机制 多样化反馈渠道&#xff1a; 设立在线反馈表、邮件…...

图漾相机——Sample_V1示例程序

文章目录 1.SDK支持的平台类型1.1 Windows 平台1.2 Linux平台 2.SDK基本知识2.1 SDK目录结构2.2 设备组件简介2.3 设备组件属性2.4 设备的帧数据管理机制2.5 SDK中的坐标系变换 3.Sample_V1示例程序3.1 DeviceStorage3.2 DumpCalibInfo3.3 NetStatistic3.4 SimpleView_SaveLoad…...

如何使用C#的using语句释放资源?什么是IDisposable接口?与垃圾回收有什么关系?

在 C# 中,using语句用于自动释放实现了IDisposable接口的对象所占用的非托管资源,如文件句柄、数据库连接、图形句柄等。其使用方式如下: 基础用法 声明并初始化资源对象:在using关键字后的括号内声明并初始化一个实现了IDisposable接口的对象。使用资源:在using语句块内…...

HTML 字符实体

HTML 字符实体 在HTML中,字符实体是一种特殊的表示方式,用于在文档中插入那些无法直接通过键盘输入的字符。字符实体在网页设计和文档编写中扮演着重要的角色,尤其是在处理特殊字符、符号和数学公式时。以下是关于HTML字符实体的详细解析。 字符实体概述 HTML字符实体是一…...

Ubuntu 下 nginx-1.24.0 源码分析 - ngx_strerror_init()函数

目录 ngx_strerror_init()函数声明 ngx_int_t 类型声明定义 intptr_t 类型 ngx_strerror_init()函数实现 NGX_HAVE_STRERRORDESC_NP ngx_strerror_init()函数声明 在 nginx.c 的开头引入了: #include <ngx_core.h> 在 ngx_core.h 中引入了 #include <ngx_er…...

【c++】类与对象详解

目录 面向过程思想和面向对象思想类的定义引入类的关键字类定义的两种方式类的访问限定符类的作用域类大小的计算封装 this指针类的6个默认成员函数构造函数初步理解构造函数深入理解构造函数初始化列表单参数构造函数引发的隐式类型转换 析构函数拷贝构造函数赋值运算符重载运…...

nginx目录结构和配置文件

nginx目录结构 [rootlocalhost ~]# tree /usr/local/nginx /usr/local/nginx ├── client_body_temp # POST 大文件暂存目录 ├── conf # Nginx所有配置文件的目录 │ ├── fastcgi.conf # fastcgi相关参…...

MacBook Pro(M1芯片)Qt环境配置

MacBook Pro&#xff08;M1芯片&#xff09;Qt环境配置 1、准备 试图写一个跨平台的桌面应用&#xff0c;此时想到了使用Qt&#xff0c;于是开始了搭建开发环境&#xff5e; 在M1芯片的电脑上安装&#xff0c;使用brew工具比较方便 Apple Silicon&#xff08;ARM/M1&#xf…...

Kotlin 使用 Springboot 反射执行方法并自动传参

在使用反射的时候&#xff0c;执行方法的时候在想如果Springboot 能对需要执行的反射方法的参数自动注入就好了。所以就有了下文。 知识点 获取上下文通过上下文获取 Bean通过上下文创建一个对象&#xff0c;该对象所需的参数由 Springboot 自己注入 创建参数 因为需要对反…...

网络安全技术简介

网络安全技术简介 随着信息技术的迅猛发展&#xff0c;互联网已经成为人们日常生活和工作中不可或缺的一部分。与此同时&#xff0c;网络安全问题也日益凸显&#xff0c;成为全球关注的焦点。无论是个人隐私泄露、企业数据被盗取还是国家信息安全受到威胁&#xff0c;都与网络…...

nginx 报错404

404&#xff1a;服务器无法正常解析页面&#xff0c;大多是配置问题(路径配置错误)、或访问页面不存在 如果你也是用nginx来转接服务的话&#xff0c;那你有可能碰到过这种情况&#xff0c;当你启动服务后&#xff0c;在本地打开页面&#xff0c;发现404&#xff0c;然后你找遍…...

【1.安装ubuntu22.04】

目录 参考文章链接电脑参数安装过程准备查看/更改引导方式查看/更改磁盘的分区格式关闭BitLocker加密压缩分区关闭独显直连制作Ubuntu安装盘下载镜像制作启动盘 进入BIOS模式进行设置Secure Boot引导项顺序try or install ubuntu 进入安装分区启动引导器个人信息和重启 参考文章…...

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …...

安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件

在选煤厂、化工厂、钢铁厂等过程生产型企业&#xff0c;其生产设备的运行效率和非计划停机对工业制造效益有较大影响。 随着企业自动化和智能化建设的推进&#xff0c;需提前预防假检、错检、漏检&#xff0c;推动智慧生产运维系统数据的流动和现场赋能应用。同时&#xff0c;…...

Go 语言接口详解

Go 语言接口详解 核心概念 接口定义 在 Go 语言中&#xff0c;接口是一种抽象类型&#xff0c;它定义了一组方法的集合&#xff1a; // 定义接口 type Shape interface {Area() float64Perimeter() float64 } 接口实现 Go 接口的实现是隐式的&#xff1a; // 矩形结构体…...

IoT/HCIP实验-3/LiteOS操作系统内核实验(任务、内存、信号量、CMSIS..)

文章目录 概述HelloWorld 工程C/C配置编译器主配置Makefile脚本烧录器主配置运行结果程序调用栈 任务管理实验实验结果osal 系统适配层osal_task_create 其他实验实验源码内存管理实验互斥锁实验信号量实验 CMISIS接口实验还是得JlINKCMSIS 简介LiteOS->CMSIS任务间消息交互…...

在鸿蒙HarmonyOS 5中使用DevEco Studio实现录音机应用

1. 项目配置与权限设置 1.1 配置module.json5 {"module": {"requestPermissions": [{"name": "ohos.permission.MICROPHONE","reason": "录音需要麦克风权限"},{"name": "ohos.permission.WRITE…...

C++.OpenGL (14/64)多光源(Multiple Lights)

多光源(Multiple Lights) 多光源渲染技术概览 #mermaid-svg-3L5e5gGn76TNh7Lq {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-3L5e5gGn76TNh7Lq .error-icon{fill:#552222;}#mermaid-svg-3L5e5gGn76TNh7Lq .erro…...

LLMs 系列实操科普(1)

写在前面&#xff1a; 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容&#xff0c;原视频时长 ~130 分钟&#xff0c;以实操演示主流的一些 LLMs 的使用&#xff0c;由于涉及到实操&#xff0c;实际上并不适合以文字整理&#xff0c;但还是决定尽量整理一份笔…...

基于Springboot+Vue的办公管理系统

角色&#xff1a; 管理员、员工 技术&#xff1a; 后端: SpringBoot, Vue2, MySQL, Mybatis-Plus 前端: Vue2, Element-UI, Axios, Echarts, Vue-Router 核心功能&#xff1a; 该办公管理系统是一个综合性的企业内部管理平台&#xff0c;旨在提升企业运营效率和员工管理水…...

作为测试我们应该关注redis哪些方面

1、功能测试 数据结构操作&#xff1a;验证字符串、列表、哈希、集合和有序的基本操作是否正确 持久化&#xff1a;测试aof和aof持久化机制&#xff0c;确保数据在开启后正确恢复。 事务&#xff1a;检查事务的原子性和回滚机制。 发布订阅&#xff1a;确保消息正确传递。 2、性…...

android RelativeLayout布局

<?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"match_parent"android:layout_height"match_parent"android:gravity&…...