最常用的跨域和静态资源代理


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//Windows下registry.addResourceHandler("/uploads2/**").addResourceLocations("file:D:/uploads2/");//Mac或Linux下(没有CDEF盘符)registry.addResourceHandler("/uploads/**").addResourceLocations("file:/Users/uploads/");}/*** 开启跨域*/@Overridepublic void addCorsMappings(CorsRegistry registry) {// 设置允许跨域的路由registry.addMapping("/**")// 设置允许跨域请求的域名.allowedOriginPatterns("*")// 是否允许证书(cookies).allowCredentials(true)// 设置允许的方法.allowedMethods("*")// 跨域允许时间.maxAge(3600);}}

1、什么是WebMvcConfigurerAdapter

Spring内部的一种配置方式
采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制html

2、WebMvcConfigurerAdapter经常使用的方法

/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;/** 添加拦截器 **/
void addInterceptors(InterceptorRegistry registry);/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);/** 配置内容裁决的一些选项 **/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);/** 视图跳转控制器 **/
void addViewControllers(ViewControllerRegistry registry);/** 静态资源处理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);/** 默认静态资源处理器 **/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);

一、addInterceptors:拦截器

  • addInterceptor:须要一个实现HandlerInterceptor接口的拦截器实例
  • addPathPatterns:用于设置拦截器的过滤路径规则

excludePathPatterns:用于设置不须要拦截的过滤规则java

@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");super.addInterceptors(registry);
}

二、addCorsMappings:跨域

@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE").maxAge(3600).allowCredentials(true);}

三、addViewControllers:跳转指定页面

/*** 之前要访问一个页面须要先建立个Controller控制类,在写方法跳转到页面* 在这里配置后就不须要那么麻烦了,直接访问http://localhost:8080/toLogin就跳转到login.html页面了** @param registry*/@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/toLogin").setViewName("login");registry.addViewController("/").setViewName("/index");registry.addViewController("/login").setViewName("forward:/index.html");super.addViewControllers(registry);}

四、resourceViewResolver:视图解析器

/*** 配置请求视图映射* @return*/
@Bean
public InternalResourceViewResolver resourceViewResolver()
{InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();//请求视图文件的前缀地址internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");//请求视图文件的后缀internalResourceViewResolver.setSuffix(".jsp");return internalResourceViewResolver;
}/*** 视图配置* @param registry*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {super.configureViewResolvers(registry);registry.viewResolver(resourceViewResolver());/*registry.jsp("/WEB-INF/jsp/",".jsp");*/
}

五、configureMessageConverters:信息转换器

/**
* 消息内容转换配置* 配置fastJson返回json转换* @param converters*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {//调用父类的配置super.configureMessageConverters(converters);//建立fastJson消息转换器FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();//建立配置类FastJsonConfig fastJsonConfig = new FastJsonConfig();//修改配置返回内容的过滤fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);fastConverter.setFastJsonConfig(fastJsonConfig);//将fastjson添加到视图消息转换器列表内converters.add(fastConverter);}

六、addResourceHandlers:静态资源

@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//自定义项目内目录//registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");//指向外部目录registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");super.addResourceHandlers(registry);}

3、使用WebMvcConfigurerAdapter
一、过期方式:继承WebMvcConfigurerAdapter
 该方法在spring boot 2.0,Spring 5.0 以后,已经被废弃 spring

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {//TODO
}

二、代替方案
 ①直接实现WebMvcConfigurerjson

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {//TODO
}

②直接继承WebMvcConfigurationSupport跨域

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {//TODO
}

查看源码发现: WebMvcConfigurerAdapter只是对WebMvcCofigurer的空实现app

WebMvcConfigurationSupport与WebMvcConfigurerAdapter、接口WebMvcConfigurer处于同一个目录下框架

WebMvcConfigurationSupport包含WebMvcConfigurer里面的方法,且WebMvcConfigurationSupport的实现的方法更全面jsp

可是继承WebMvcConfigurationSupport会发现Spring Boot的WebMvc自动配置失效(WebMvcAutoConfiguration自动化配置),致使没法视图解析器没法解析并返回到对应的视图。

springboot自定义静态资源代理WebMvcConfigurerAdapter详解和过期后的替代方案WebMvcConfigurer相关推荐

  1. 干货,springboot自定义注解实现分布式锁详解

    背景 在互联网的很多场景下,会产生资源竞争,如果是单机环境,简单加个锁就能解决问题:但是在集群环境下(分布式环境),多个客户端在一个很短的时间内竞争同一服务端资源(如抢购场景),或者同一客户端重复提交 ...

  2. 玩转springboot:默认静态资源和自定义静态资源实战

    点个赞,看一看,好习惯!本文 GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了3个月总结的一线大厂Java面试总结,本人已拿腾 ...

  3. cglib动态代理jar包_代理模式详解:静态代理+JDK/CGLIB 动态代理实战

    1. 代理模式 代理模式是一种比较好的理解的设计模式.简单来说就是 我们使用代理对象来代替对真实对象(real object)的访问,这样就可以在不修改原目标对象的前提下,提供额外的功能操作,扩展目标 ...

  4. 【Spring AOP】静态代理设计模式、Spring 动态代理开发详解、切入点详解(切入点表达式、切入点函数)

    AOP 编程 静态代理设计模式 1. 为什么需要代理设计模式 2. 代理设计模式 名词解释 代理开发的核心要素 静态代理编码 静态代理存在的问题 Spring 动态代理开发 搭建开发环境 Spring ...

  5. 代理模式详解(静态代理和动态代理的区别以及联系)

    原文链接:https://www.cnblogs.com/takumicx/p/9285230.html 1. 前言 代理模式可以说是生活中处处可见.比如说在携程上定火车票,携程在这里就起到了一个代理 ...

  6. SpringBoot之静态资源访问

    SpringBoot之静态资源访问 1.springboot访问静态资源的几种方式 (1)在src/main/resources/目录下创建 static文件夹 (2)在src/main/resour ...

  7. springboot设置静态资源不拦截的方法

    springboot设置静态资源不拦截的方法 springboot不拦截静态资源需配置如下的类: import org.springframework.context.annotation.Confi ...

  8. SpringBoot使用AOP,PointCut表达式详解以及使用

    SpringBoot使用AOP,PointCut表达式详解以及使用 1.相关注解 2.PointCut 表达式详解 2.1 execution: 2.1 within: 2.3. this: 2.4. ...

  9. SpringBoot访问静态资源(图片)

    SpringBoot中的静态资源访问 springboot访问静态资源的几种方式 (优先级从高到低) (1)在src/main/resources/目录下创建 META-INF/resources文件 ...

最新文章

  1. ddr3ddr4 lpddr4速率_金泰克LPDDR3/LPDDR4内存新增特性解读
  2. sql server 2000 数据库。 怎样用sql语句,在没有主键的情况下删除数据库中多条......
  3. 使用Sniffer截获流经本机网卡的IP数据包
  4. 更新Svn客户端后,右键菜单中没有TortoiseSVN了
  5. redis接口的二次封装
  6. css 关闭按钮实现,CSS做的关闭按钮动效
  7. Thinkphp 数据库配置参数
  8. linux下日志晒选打包,Linux 文件日志筛选操作
  9. [Android]BaseExpandableListAdapter实现可折叠列表
  10. 新手做头条影视混剪怎么解决侵权问题
  11. windows系统 ping Telnet等系统自带命令无法使用原因及解决方法
  12. wonderware配置-Intouch读取Historian数据 8
  13. 为什么华为a1路由器网速变慢_华为a1路由器wifi经常掉线怎么办
  14. 从excel文件xlsx中特定单元格中提取图片
  15. i5 10400f和i7 8700k哪个好
  16. Chrome浏览器隐藏彩蛋
  17. 老张和小梁的求职之旅
  18. 因果系列文章(1):因果推断及相关论文
  19. kafka中副本数据同步策略 ,acknowledge的发送策略,kafka的数据可靠性保证
  20. 常见问题:try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候执行?

热门文章

  1. Windows 7 Ultimate x64 (7600) update failed with error code 8024402F (更新失败)
  2. C++编写发送自定义TCP数据包程序
  3. 重读《三国》,我总结了管理失败的10个细节
  4. python实现lfm_LFM
  5. 数据存储之SQLCipher数据库解密访问踩坑:net.sqlcipher.database.SQLiteException: file is not a databaseAndroid
  6. label的基本用法
  7. Js弹出框代码,头像选择工具
  8. 中间件---Binlog传输同步---Maxwell
  9. 人物专属道具--战国二
  10. windows10下python开发spark应用的环境搭建