这篇文章将为大家详细讲解有关如何解决springboot 2.x 里面访问静态资源的问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径
classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
不生效。
这是因为在 springboot的web自动配置类 WebMvcAutoConfiguration 上有条件注解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
这个注解的意思是在项目类路径中 缺少 WebMvcConfigurationSupport类型的bean时改自动配置类才会生效,所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。
又要按自己的需要重写某些方法,比如增加 viewController ,则可以自己的配置类可以继承 WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter ,虽然还可以用,但是看起来不好。
/**
* 原来是这么写的:
* public class BeanConfiguration extends WebMvcConfigurationSupport
* 导致默认配置的静态资源不生效了
*/
@Configuration
public class BeanConfiguration implements WebMvcConfigurer {
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);
converter.setObjectMapper(mapper);
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//将我们定义的时间格式转换器添加到转换器列表中,
//这样jackson格式化时候但凡遇到Date类型就会转换成我们定义的格式
converters.add(jackson2HttpMessageConverter());
// 添加字符串转换,否认如果返回字符串,则会报异常,其他converter
// 参考:org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#addDefaultHttpMessageConverters
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
converters.add(stringHttpMessageConverter);
}
}
package com.example.thymeleaf.commons;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置静态资源映射
*
* @author sunziwen
* @version 1.0
* @date 2018-11-16 14:57
**/
@Component
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加静态资源文件,外部可以直接访问地址
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
关于“如何解决springboot 2.x 里面访问静态资源的问题”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。