-
SpringBoot系列——WebMvcConfigurer介绍
2020-09-15 20:34:14WebMvcConfigurer是一个接口,提供很多自定义的拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,...为什么要使用WebMvcConfigurer?
WebMvcConfigurer是一个接口,提供很多自定义的拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer继承了WebMvcConfigurerAdapter大部分内容。
WebMvcConfigurer方法介绍
由于内容太多,只展示3个关键的接口,用的比较少的,只是阐述下含义,不再详解,用的更少的,就不看了,毕竟十多个方法呢...
1.configurePathMatch(PathMatchConfigurer configurer)
这个用到的比较少,这个是和访问路径有关的。举个例子,比如说PathMatchConfigurer 有个配置是setUseTrailingSlashMatch(),如果设置为true的话(默认为true),后面加个斜杠并不影响路径访问,例如“/user”等同于“/user/"。我们在开发中很少在访问路径上搞事情,所以这个方法如果有需要的请自行研究吧。
2.configureContentNegotiation(ContentNegotiationConfigurer configurer)
这个东西直译叫做内容协商机制,主要是方便一个请求路径返回多个数据格式。ContentNegotiationConfigurer这个配置里面你会看到MediaType,里面有众多的格式。此方法不在多赘述。
3.configureAsyncSupport(AsyncSupportConfigurer configurer)
顾名思义,这是处理异步请求的。只能设置两个值,一个超时时间(毫秒,Tomcat下默认是10000毫秒,即10秒),还有一个是AsyncTaskExecutor,异步任务执行器。
4.configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
这个接口可以实现静态文件可以像Servlet一样被访问。
5.addFormatters(FormatterRegistry registry)
增加转化器或者格式化器。这边不仅可以把时间转化成你需要时区或者样式。还可以自定义转化器和你数据库做交互,比如传进来userId,经过转化可以拿到user对象。
6.addInterceptors(InterceptorRegistry registry)
盼望着,盼望着,你一个常用的方法来了。这个方法可以自定义写拦截器,并指定拦截路径。来,咱们写一个拦截器。
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle,ok,假设给你一个true,运行去吧"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle,ok,看看我什么时候运行的。"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion,ok,看完不点个赞再走吗?"); } }
然后配置一下:
@Configuration public class MyConfigurer implements WebMvcConfigurer { @Bean public MyInterceptor getMyInterceptor(){ return new MyInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.getMyInterceptor()) .addPathPatterns("/abc","/configurePathMatch"); } }
可以看出addPathPatterns()里面可以尝试添加多个路径,或者写成”/**“,包含所有路径都需要尝试拦截一下。
测试一下,输出:
preHandle,ok,假设给你一个true,运行去吧 ===》执行业务逻辑===》 postHandle,ok,看看我什么时候运行的。 afterCompletion,ok,看完不点个赞再走吗?
7.addResourceHandlers(ResourceHandlerRegistry registry)
自定义资源映射。这个东西也比较常用,业务场景就是自己的服务器作为文件服务器,不利用第三方的图床,就需要一个虚拟路径映射到我们服务器的地址。值得一提的是,如果你的项目是war包启动,一般都是再Tomcat中配置一下(配置方法请百度);如果是jar包启动(SpringBoot经常用这种方式启动),就可以用到这个方法了。例如:
public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/my/**") .addResourceLocations("file:E:/my/"); super.addResourceHandlers(registry); }
真实路径,wndows当服务器的情况下,前面一定要加上一个file:。
8.addCorsMappings(CorsRegistry registry)
这个是设置跨域问题的,几乎是每个后台服务器都需要配置的东西。我曾写过一篇文章,专门讲跨域问题和SpringBoot怎么配置的,请查询:
https://juejin.im/post/5cfe6367f265da1b9163887f9.addViewControllers(ViewControllerRegistry registry)
这个方法可以实现,一个路径自动跳转到一个页面。不过现在多为前后端分离的项目,是不是可以把跳转路由的问题直接扔给前端。
后面还有七个:configureViewResolvers、addArgumentResolvers、addReturnValueHandlers、configureMessageConverters、extendMessageConverters、configureHandlerExceptionResolvers、extendHandlerExceptionResolvers。是在用的太少了,就不再看了。
小结
本篇先大概知道下这些都是什么方法,最重要的是知道了WebMvcConfigurer为我们再拦截层做了一些通用拦截器,方便开发者使用。当然也可以自己实现拦截器。最常用的是还是6、7、8。其他的以后有机会研究好了再更新。
-
拦截器WebMvcConfigurer和HandlerInterceptorAdapter
2019-01-11 17:10:36WebMvcConfigurer:拦截...拦截组件HandlerInterceptorAdapter可以有多个,需要注册到WebMvcConfigurer里面,在WebMvcConfigurer里面拦截器是按顺序执行的。 @SpringBootConfiguration public class InterceptorC...WebMvcConfigurer:拦截器的注册类
HandlerInterceptorAdapter:拦截组件
拦截组件HandlerInterceptorAdapter可以有多个,需要注册到WebMvcConfigurer里面,在WebMvcConfigurer里面拦截器是按顺序执行的。
@SpringBootConfiguration
public class InterceptorConfig implements WebMvcConfigurer {
/** 拦截器配置,与业务相关,有着强烈的前后依赖顺序
请不要在datasourceInterceptor这个拦截器之后再添加,这个拦截器preHandler是进入业务代码最后一个拦截器
@Override
public void addInterceptors(InterceptorRegistry registry){
WebMvcConfigurer.super.addInterceptors(registry);
registry.addInterceptor(loggerInterceptor());
registry.addInterceptor(authenticateInterceptor());
registry.addInterceptor(datasourceInterceptor());
}
//日志拦截
@Bean("loggerInterceptor")
public LoggerInterceptor loggerInterceptor(){
LoggerInterceptor interceptor = new LoggerInterceptor ();
return interceptor;
}
//认证拦截,安全校验相关的拦截操作
@Bean("authenticateInterceptor")
public AuthenticateInterceptor authenticateInteceptor(){
AuthenticateInterceptor interceptor =new AuthenticateInterceptor();
return interceptor;
}
}
------------------------------------------------------------------------------------------------------------
public class AuthenticateInterceptor implements HandlerInterceptor {
//无需拦截的url
private HashSet<String> set =new HashSet<>();
public AuthenticateInterceptor (){
set .add("/test/login.do");
.......
}
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throw Exception{
//具体拦截业务
}
}
-
Spring统一配置WebMvcConfigurer 接口
2020-01-08 22:41:20WebMvcConfigurer 接口 ...这个接口还是非常常用的,可以对 Spring 的很多配置和行为进行定制。下面对一些常用的方法进行解释: public interface WebMvcConfigurer { /** * 匹配路由请求规则 */ default...WebMvcConfigurer 接口
Spring 的 WebMvcConfigurer 接口提供了很多方法让我们来定制 Spring MVC 的配置。这个接口还是非常常用的,可以对 Spring 的很多配置和行为进行定制。下面对一些常用的方法进行解释:
public interface WebMvcConfigurer { /** * 匹配路由请求规则 */ default void configurePathMatch(PathMatchConfigurer configurer) { } /** * 注册自定义的 Formatter 和 Convert */ default void addFormatters(FormatterRegistry registry) { } /** * 添加静态资源处理器 */ default void addResourceHandlers(ResourceHandlerRegistry registry) { } /** * 配置消息转换器 */ default void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } /** * 添加自定义视图控制器 */ default void addViewControllers(ViewControllerRegistry registry) { } /** * 添加自定义方法参数处理器 */ default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { } }
-
十一、springboot WebMvcConfigurer与HandlerInterceptorAdapter使用
2019-03-22 10:42:44springboot WebMvcConfigurer与HandlerInterceptorAdapter使用 简介 WebMvcConfigurer:拦截...拦截组件HandlerInterceptorAdapter可以有多个,需要注册到WebMvcConfigurer里面,在WebMvcConfigurer里面拦截器是按顺...springboot WebMvcConfigurer与HandlerInterceptorAdapter使用
简介
WebMvcConfigurer:拦截器的注册类 HandlerInterceptorAdapter:拦截组件
拦截组件HandlerInterceptorAdapter可以有多个,需要注册到WebMvcConfigurer里面,在WebMvcConfigurer里面拦截器是按顺序执行的。
- 在Spring Boot 2.0后都是靠重写WebMvcConfigurer的方法来添加自定义拦截器,消息转换器等。
- 在SpringBoot2.0及Spring 5.0前,该类WebMvcConfigurerAdapter被标记为@Deprecated,已被废弃。
WebMvcConfigurer的作用
修饰符和类型 方法 描述 default void addArgumentResolvers(java.util.List resolvers) 添加解析器以支持自定义控制器方法参数类型。 default void addCorsMappings(CorsRegistry registry) 配置跨源请求处理。 default void addFormatters(FormatterRegistry registry) 添加Converters和Formatters除了默认注册的那些。 default void addInterceptors(InterceptorRegistry registry) 添加Spring MVC生命周期拦截器,用于控制器方法调用的预处理和后处理。 default void addResourceHandlers(ResourceHandlerRegistry registry) 添加处理程序以提供静态资源,例如来自Web应用程序根目录下的特定位置的图像,js和css文件,类路径等。 default void addReturnValueHandlers(java.util.List handlers) 添加处理程序以支持自定义控制器方法返回值类型。 default void addViewControllers(ViewControllerRegistry registry) 配置预配置了响应状态代码的简单自动控制器和/或视图以呈现响应主体。 default void configureAsyncSupport(AsyncSupportConfigurer configurer) 配置异步请求处理选项。 default void configureContentNegotiation(ContentNegotiationConfigurer configurer) 配置内容协商选项。 default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) 配置处理程序以通过转发到Servlet容器的“默认”servlet来委派未处理的请求。 default void configureHandlerExceptionResolvers(java.util.List resolvers) 配置异常解析器。 default void configureMessageConverters(java.util.List<HttpMessageConverter<?>> converters) 配置HttpMessageConverters用于读取或写入请求或响应的正文。 default void configurePathMatch(PathMatchConfigurer configurer) 帮助配置HandlerMappings路径匹配选项,例如尾部斜杠匹配,后缀注册,路径匹配器和路径助手。 default void configureViewResolvers(ViewResolverRegistry registry) 配置视图解析器以将从控制器返回的基于字符串的视图名称转换为具体View 实现以执行渲染。 default void extendHandlerExceptionResolvers(java.util.List resolvers) 扩展或修改默认配置的异常解析器列表。 default void extendMessageConverters(java.util.List<HttpMessageConverter<?>> converters) 用于在配置转换器列表后扩展或修改转换器列表的挂钩。 default MessageCodesResolver getMessageCodesResolver() 提供MessageCodesResolver用于根据数据绑定和验证错误代码构建消息代码的自定义。 default Validator getValidator() 提供自定义Validator而不是默认创建的自定义。 准备工作
1.创建一个WebMvcConfig类
package com.honghh.bootfirst.config; import com.honghh.bootfirst.interceptor.AccessSignAuthInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Resource; /** * MVC配置 * * @author honghh * @date 2018/8/7 23:01 */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Resource private AccessSignAuthInterceptor accessSignAuthInterceptor; /** * Description : * Group : * <p> * 实现自定义拦截器只需要3步 * 1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。 * 2、创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。 * 3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。 * * @param registry * @author honghh * @date 2019/3/22 0022 10:08 * @author honghh * @date 2018/8/13 13:56 */ @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration registration = registry.addInterceptor(accessSignAuthInterceptor); // 拦截配置 registration.addPathPatterns("/api/**"); // 排除配置 registration.excludePathPatterns("/api/word"); } }
2.创建一个ApiController
package com.honghh.bootfirst.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ClassName: ApiController * Description: * * @author honghh * @date 2019/03/22 9:36 */ @RestController @RequestMapping("api") public class ApiController { @RequestMapping("hello") public String hello() { return "Hello Spring Boot!"; } @RequestMapping("word") public String word() { return "Hello word!"; } }
3.定义一个AccessSignAuthInterceptor类
package com.honghh.bootfirst.interceptor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * description: * * @author: hh * @date: 2018/8/13 11:03 */ @Slf4j @Component public class AccessSignAuthInterceptor extends HandlerInterceptorAdapter { /** * 只有返回true才会继续向下执行,返回false取消当前请求 * * @param request * @param response * @param handler * @return * @throws Exception * @author honghh * @date 2018/8/13 13:58 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("preHandle:请求前调用"); String url = request.getRequestURI(); log.info("请求url:{}",url); //返回 false 则请求中断 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("postHandle:请求后调用"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调"); } }
4.启动项目分别对api/hello,api/word发起请求
该项目是基于上一节 十、springboot注解式AOP(@Aspect)统一日志管理 实现。主要添加了以上几个类,获取源码增加上即可。
代码获取
https://gitee.com/honghh/boot-demo.git [boot-aspect]
参考文献
-
WebMvcConfigurer的介绍以及两种配置方式
2020-08-12 22:35:46前言 公司的“僵尸项目”(好几年没...WebMvcConfigurer是一个接口,提供很多自定义的拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring -
WebMvcConfigurer的实现以及内部方法详解
2019-11-29 11:41:12背景:最近有个项目需要发表在websphere应用服务器上,但是was的版本不支持spring5.0。所以在使用springboot搭建项目的时候使用了springboot1.5.13版本,降级...WebMvcConfigurer是一个接口,提供很多自定义的拦截... -
微服务技术系列教程(48)-SpringBoot WebMvcConfigurer接口
2020-08-12 09:21:48SpringBoot 确实为我们做了很多事情, 但有时候我们想要自己定义一些Handler,Interceptor,ViewResolver,MessageConverter,该怎么做呢。在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加... -
Spring Boot MVC中的代码配置--WebMvcConfigurer
2020-10-28 15:29:09SpringFramework原本使用的是如下面代码显示的xml配置,这种xml配置曾经让很多程序员头疼,由于一个字符不对而产生一大堆不知道原因的错误,尤其是xmlns种约束文件的引入更是繁杂。 <?xml version="1.0" ... -
SpringCloud - WebMvcConfigurer & @EnableFeignClients 冲突之 getApplicationContext() 为 null 解决(二...
2021-01-28 19:27:18如果看过SpringCloud - WebMvcConfigurer & @EnableFeignClients 冲突之 getApplicationContext() 为 null 解决方案(一)的人,我相信你看完这篇解决方案,会更推荐此篇方案,废话不多说,如下~ 分析 其实... -
webmvcconfigurer不拦截_如何快速在 Springboot 中集成拦截器? | 原力计划
2020-12-08 10:41:48作者 | 才疏学浅责编 | 夕颜出品 | CSDN(ID:CSDNnews)话不多说,直接上货!拦截器的作用拦截器提供了一种机制,在访问action前后进行一些操作,因为拦截器的这个特性,那么我们就可以利用拦截器做一些事情,比如... -
webmvcconfigurer配置跨域_为什么加了 Spring Security 会导致 Spring Boot 跨域失效呢?...
2021-01-16 01:04:50点击上方IT牧场,选择置顶或者星标技术干货每日送达作者:欧阳我去链接:...而在 Spring 中,我们见过很多种CORS的配置,很多资料都只是告诉我们可以这样配置、可以那样配... -
springboot2 虚拟路径设置_SpringBoot-虚拟路径配置+加载多个本地图片图片
2020-12-29 02:50:41SpringBoot-虚拟路径配置实现WebMvcConfigurer接口,并且重写addResourceHandlers方法@Componentpublic classMyConfiguration implements WebMvcConfigurer{/*** 虚拟路径配置* @param registry*/@Overridepublic ... -
springboot拦截器的拦截配置和添加多个拦截器
2019-05-11 19:00:00在spring2.0之前的版本大部分都采用extends ...而在spring2.0之后,这个extends WebMvcConfigurerAdapter方法就过时了,官方推荐用implements WebMvcConfigurer。其他的还和以前一样。特别注意的是spring2.... -
如何配置多个静态资源映射?
2020-12-13 14:52:18public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //静态资源映射关系 registry.addResourceHandler("/... -
springboot怎么设置多个路径全部跳转首页_SpringBoot(四)—Web开发(二)
2021-01-06 16:48:17这篇文章准备来记录一下一个restful风格小项目的流程,上篇文章为它做了一个基础,如果有什么错误希望大家能够指出。目录首页国际化登录拦截器CRUD一、首页在访问localhost:8080/的时候,默认访问首页在自己配置的... -
springboot 写个token登录验证
2020-05-26 16:19:121.@Configuration 一下WebMvcConfigurer 来弄一个拦截器 @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //... -
Spring Boot中只能有一个WebMvcConfigurationSupport配置类
2020-04-20 14:40:51首先将结论写文章的最前面,一个项目中只能有一个继承WebMvcConfigurationSupport的@Configuration类(使用@EnableMvc效果相同),如果存在多个这样的类,只有一个配置可以生效。推荐使用 implements ... -
SpringBoot返回字符串,多双引号
2019-06-12 15:49:37这个原因是因为,有一个json的MessageCoverter的缘故,会给字符串外面再包一层双引号,解决办法如下 @Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Bean public ... -
springboot 问题集锦
2018-11-15 15:55:35springboot 程序只能有一个 WebMvcConfigurer 存在,如果存在多个,之后的配置不会生效 -
springboot+springsecurity跨域配置完整版(俺被坑了一个上午,特此前来用爱发电)
2021-02-05 15:56:19springboot跨域配置不必多说,网上很多: 首先配置好,我用的是继承WebMvcConfigurer配置,还可以通过过滤器配置,我觉得这样应该是最方便了,缺点就是这种配置不能在interceptor中再配置header。 @Configuration ... -
Spring Boot 2 @EnableWebMvc 注解和@EnableSpringDataWebSupport 注解使用说明
2018-08-22 16:10:591. @EnableWebMvc使用说明 @EnableWebMvc 只能添加到一个@... 可以有多个@Configuration类来实现WebMvcConfigurer,以定制提供的配置。 WebMvcConfigurer 没有暴露高级设置,如果需要高级设置 需要 删除@... -
ngnix 映射路径配置_详解Springboot中自定义SpringMVC配置
2021-01-08 23:10:22 这个接口可以自定义拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer... -
SpringBoot拦截器未生效解决方案
2020-08-30 16:09:03是否有多个配置类同时继承了WebMvcConfigurationSupport类,或实现了WebMvcConfigurer, 多个配置类只会生效前一个配置类,后一个配置类不会生效 ; 例: swagger的配置类: @Configuration public class ... -
详解Springboot中自定义SpringMVC配置
2020-04-08 09:00:17 这个接口可以自定义拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer...