WebMvcConfigurerAdapter配置类是spring提供的一种配置方式,采用javabean的方式替代传统的基于xml的配置来对spring框架进行自定义的配置。因此,在springboot提倡的基于注解的配置 && 采用约定大于配置的风格下,当需要进行自定义配置的时候,便可以继承WebMvcConfigurerAdapter这个抽象类,通过javabean来实现需要的配置。

WebMvcConfigurerAdapter是一个抽象类,只提供一些空的接口让用户去重写。其提供的接口如下:

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {/*配置路径匹配参数*/public void configurePathMatch(PathMatchConfigurer configurer) {}/*配置Web Service或REST API设计中内容协商,即根据客户端的支持内容格式情况来封装响应消息体,如xml,json*/public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}/*配置路径匹配参数*/public void configureAsyncSupport(AsyncSupportConfigurer configurer) {}/* 使得springmvc在接口层支持异步*/public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {}/* 注册参数转换和格式化器*/public void addFormatters(FormatterRegistry registry) {}/* 注册配置的拦截器*/public void addInterceptors(InterceptorRegistry registry) {}/* 自定义静态资源映射*/public void addResourceHandlers(ResourceHandlerRegistry registry) {}/* cors跨域访问*/public void addCorsMappings(CorsRegistry registry) {}/* 配置页面直接访问,不走接口*/public void addViewControllers(ViewControllerRegistry registry) {}/* 注册自定义的视图解析器*/public void configureViewResolvers(ViewResolverRegistry registry) {}/* 注册自定义控制器(controller)方法参数类型*/public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {}/* 注册自定义控制器(controller)方法返回类型*/public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {}/* 重载会覆盖掉spring mvc默认注册的多个HttpMessageConverter*/public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}/* 仅添加一个自定义的HttpMessageConverter,不覆盖默认注册的HttpMessageConverter*/public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}/* 注册异常处理*/public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {}/* 多个异常处理,可以重写次方法指定处理顺序等*/public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {}
}

使用WebMvcConfigurerAdapter提供的接口实现自定义配置项示例:

1、注册拦截器

首先编写拦截器类

public class LoginInterceptor extends HandlerInterceptorAdapter {private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//拦截器相关处理代码logger.info("*********我是拦截器************");return true;}
}

自定义配置类继承WebMvcConfigurerAdapter接口实现接口的addInterceptors方法来配制我们自定义的拦截器

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {/** 拦截器配置*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");//注册拦截器,并配置拦截路径
}

2.配置CORS跨域

只需要在上面的webConfig里重写WebMvcConfigurerAdapter的addCorsMappings方法就可以获得基于spring的跨域支持。

/*** 跨域CORS配置* @param registry*/@Overridepublic void addCorsMappings(CorsRegistry registry) {super.addCorsMappings(registry);registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST","GET").allowedOrigins("http://...").allowCredentials(true);}

3.配置ViewController

当首页或者登陆页的页面对外暴露,不需要加载任何的配置的时候,这些页面将不通过接口层,而是直接访问,这时,就需要配置ViewController指定请求路径直接到页面。

/*** 视图控制器配置* @param registry*/@Overridepublic void addViewControllers(ViewControllerRegistry registry) {super.addViewControllers(registry);registry.addViewController("/").setViewName("forward:/index.html");}

4.配置Formatter

当请求的参数中带有日期的参数的时候,可以在此配置formatter使得接收到日期参数格式统一

@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addFormatter(new Formatter<Date>() {@Overridepublic Date parse(String date, Locale locale) {return new Date(Long.parseLong(date));}@Overridepublic String print(Date date, Locale locale) {return Long.valueOf(date.getTime()).toString();}});}

以上应用只适用于spring boot 2.0,Spring 5.0之前的版本,spring boot 2.0,Spring 5.0 以后WebMvcConfigurerAdapter会取消掉,高版本也提供了两种解决方案:

方案1:直接实现WebMvcConfigurer

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/index").setViewName("index");}}

方案2: 直接继承WebMvcConfigurationSupport

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/index").setViewName("index");}}

其实,源码下WebMvcConfigurerAdapter是实现WebMvcConfigurer接口,所以直接实现WebMvcConfigurer接口也可以;WebMvcConfigurationSupport与WebMvcConfigurerAdapter、接口WebMvcConfigurer处于同一个目录下,WebMvcConfigurationSupport包含WebMvcConfigurer里面的方法,高版本中推荐使用WebMvcConfigurationSupport类,其实,源码下WebMvcConfigurerAdapter是实现WebMvcConfigurer接口,所以直接实现WebMvcConfigurer接口也可以;WebMvcConfigurationSupport与WebMvcConfigurerAdapter、接口WebMvcConfigurer处于同一个目录下,WebMvcConfigurationSupport包含WebMvcConfigurer里面的方法,高版本中推荐使用WebMvcConfigurationSupport类,其禁止了SpringBoot对mvc的自动配置,完全由用户自己实现配置(不注意的话会遇到坑:springboot2.0、spring5.0 拦截器配置WebMvcConfigurerAdapter过时使用WebMvcConfigurationSupport来代替 新坑)。

参考资料:

Spring MVC 配置类 WebMvcConfigurerAdapter
spring boot拦截器WebMvcConfigurerAdapter,以及高版本的替换方案
@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter区别

SpringMVC配置类WebMvcConfigurerAdapter学习总结相关推荐

  1. SpringMVC配置静态资源加载, 中文乱码处理,注解驱动

    常规配置(Controller加载控制) SpringMVC的处理器对应的bean必须按照规范格式开发,未避免加入无效的bean可通过bean加载过滤器进行包含设定或排除设定,表现层bean标注通常设 ...

  2. Spring框架学习笔记04:初探Spring——采用Java配置类管理Bean

    文章目录 一.课程引入 二.采用Java配置类管理Bean (一)打开项目[SpringDemo2021] (二)创建net.hw.spring.lesson04包 (三)创建杀龙任务类 (四)创建勇 ...

  3. springboot的WebMvcConfigurerAdapter学习(现在常用实现webmvcConfigurer接口和继承WebMvcConfigurationSupport类)

    1.定义 是Spring内部的一种配置方式 采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制 2.使用 /** 解决跨域问题 **/ public void addCor ...

  4. 扩展springmvc组件——当页面跳转时,需要在Controller里面创建一个空方法去跳转或者是创建一个配置类  ||日期格式化说明||自定义格式化器||消息转化器扩展fastjson

    在容器中注册视图控制器 当页面跳转时,我们需要在Controller里面创建一个空方法去跳转,那么有没有别的配置方法呢 创建一个WebMvcConfig的配置类   实现WebMvcConfigure ...

  5. Spring框架学习笔记03:初探Spring——利用注解配置类取代Spring配置文件

    文章目录 一.课程引入 二.利用注解配置类取代Spring配置文件 (一)打开项目[SpringDemo2021] (二)创建net.hw.spring.lesson03包 (三)移植上一讲的接口和类 ...

  6. ssm注解配置连接mysql_基于注解和配置类的SSM(Spring+SpringMVC+Mybatis)项目详细配置...

    在上一篇文章中介绍了使用注解和xml配置文件对项目进行配置,在这篇文章中将xml配置文件中的配置信息都改成使用注解或者配置类的形式. 第一步.配置pom.xml 在一个ssm项目中,可能需要用到的依赖 ...

  7. Shiro学习(3)shiroConfig配置类

    一.Shiro配置类创建流程 创建shiro配置函数ShiroConfig可以分为四大块: 1.创建realm 2.创建安全管理器 3.配置shiro过滤器工厂 4.开启对shiro注解的支持 1.创 ...

  8. 第9步 spring 配置 springmvc配置

    spring配置 有5个网址   springboot 再讲一遍  spring的学习最好的方法是运行  官方demo  学习它里面的配置   . 我们不可能一下子理解spring里面的源码 spri ...

  9. springMVC 配置和使用

    springMVC相对于Struts2学习难度较为简单,并且更加灵活轻便. 第一步:导入jar包 spring.jar.spring-webmvc.jar.commons-logging.jar.sp ...

最新文章

  1. 【JS基础】Array数组的创建与操作方法
  2. 超图桌面版区分不同类型数据源的图标
  3. 岗位内推 | 微软亚洲互联网工程院自然语言处理组招聘算法研究实习生
  4. JAVA15.JDK15.7 HiddenClass
  5. 分布式锁的三种实现方式_分布式锁的几种实现方式~
  6. 漫画 | 苦逼项目是如何诞生的?
  7. 再读阿朱的《走出软件作坊》摘抄整理——20140617
  8. CentOS6修改/etc/fstab文件造成系统无法启动的问题
  9. 以太坊智能合约部署与交互
  10. 02325《计算机系统结构》自考复习重点目录
  11. VBA常用实例 | OUTLOOK批量下载选中邮件中的附件
  12. 风之王纳什,言念君子,温其如玉
  13. C#字符串与ASII16(HEX)进制相互转换
  14. 买个云服务器搭建自己的ngrok做微信公众号开发
  15. Java基础之泛型简单讲解(通俗易懂)
  16. 深度linux 挂载硬盘,Deepin 深度磁盘挂载
  17. 骑行,因人和美景而精彩
  18. Cocos Creator发布微信小游戏包内体积过大问题
  19. 2021华为校园招聘算法题
  20. 引用wps进行word转pdf操作

热门文章

  1. 【多图】近距离接触甲骨文总裁马克赫德,Oracle在上海香格里拉酒店数据中心优化专题研讨会...
  2. 漫谈数据库索引 | 脚印 footprint(转载)
  3. 麦当劳员工称缺乏归属感 长期重复劳动像个机器
  4. 进程内存信息 /proc/[pid]/maps /proc/[pid]/smaps /proc/[pid]/status
  5. WebKit DOM Event (二)
  6. Oracle 11g R2手动配置EM(转)
  7. Docker Toolbox在window 10 home 下挂载宿主机目录到容器的正确操作
  8. Mybatis-数据插入
  9. (面试题)删除在另一个字符串中出现的字符
  10. (021) Linux之正则表达式