说在前面的话:css
因为 Spring Boot 采用了”约定优于配置”这种规范,因此在使用静态资源的时候也很简单。
SpringBoot本质上是为微服务而生的,以JAR的形式启动运行,可是有时候静态资源的访问是必不可少的,好比:image、js、css 等资源的访问html
简单了解便可,感受实用性不大,java
public class WebMvcAutoConfiguration { public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } } }
代码分析: 全部 /webjars/**
,都去 classpath:/META-INF/resources/webjars/
找资源;webjars:以jar包的方式引入静态资源; webjars提供的依赖官网jquery
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.12.4</version> </dependency>
启动服务,测试访问静态地址http://127.0.0.1:8001/hp/webjars/jquery/1.12.4/jquery.js
web
@ConfigurationProperties( prefix = "spring.resources", ignoreUnknownFields = false ) public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; private String[] staticLocations; private boolean addMappings; private final ResourceProperties.Chain chain; private final ResourceProperties.Cache cache; public ResourceProperties() { this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS; this.addMappings = true; this.chain = new ResourceProperties.Chain(); this.cache = new ResourceProperties.Cache(); } public String[] getStaticLocations() { return this.staticLocations; } }
摘抄了部分源码,算是为了增长篇幅,从上述代码中咱们能够看到,提供了几种默认的配置方式spring
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources 备注说明: "/"=>当前项目的根路径
咱们在src/main/resources目录下新建 public、resources、static 、META-INF等目录目录,并分别放入 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 五张图片。跨域
注意:须要排除webjars的形式,将pom.xml中的代码去掉,在进行测试结果结果以下springboot
咱们在spring.resources.static-locations
后面追加一个配置classpath:/os/
:mvc
# 静态文件请求匹配方式 spring.mvc.static-path-pattern=/** # 修改默认的静态寻址资源目录 多个使用逗号分隔 spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/os/
在实际开发中,咱们可能须要自定义静态资源访问以及上传路径,特别是文件上传,不可能上传的运行的JAR服务中,那么能够经过继承WebMvcConfigurerAdapter来实现自定义路径映射。app
application.properties 文件配置:
# 图片音频上传路径配置(win系统自行变动本地路径) web.upload.path=D:/upload/attr/
Demo05BootApplication.java 启动配置:
package com.hanpang; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { private final static Logger LOGGER = LoggerFactory.getLogger(Demo05BootApplication.class); @Value("${web.upload.path}") private String uploadPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/uploads/**").addResourceLocations( "file:" + uploadPath); LOGGER.info("自定义静态资源目录、此处功能用于文件映射"); } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args); } }
依然从源码出手来解决这个问题
public class WebMvcAutoConfiguration { private Optional<Resource> getWelcomePage() { String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations()); return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst(); } private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); } }
欢迎页; 静态资源文件夹下的全部index.html页面,被"/**"映射;
新增模版引擎的支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置核心文件application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
没有去设置后缀名
设置增长路由
@Controller public class IndexController { @GetMapping({"/","/index"}) public String index(){ return "default"; } }
http://127.0.0.1:8001/hp/
新增模版引擎的支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置核心文件application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
没有去设置后缀名
启动文件的修改以下
@SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("default"); registry.addViewController("/index1").setViewName("default"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args); } }
@Configuration @ConditionalOnProperty( value = {"spring.mvc.favicon.enabled"}, matchIfMissing = true ) public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; private ResourceLoader resourceLoader; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(-2147483647); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler.setLocations(this.resolveFaviconLocations()); return requestHandler; } private List<Resource> resolveFaviconLocations() { String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations()); List<Resource> locations = new ArrayList(staticLocations.length + 1); Stream var10000 = Arrays.stream(staticLocations); ResourceLoader var10001 = this.resourceLoader; var10001.getClass(); var10000.map(var10001::getResource).forEach(locations::add); locations.add(new ClassPathResource("/")); return Collections.unmodifiableList(locations); } }
SpringBoot 默认是开启Favicon,而且提供了一个默认的Favicon,若是想关闭Favicon,只须要在application.properties中添加
spring.mvc.favicon.enabled=false
若是想更改Favicon,只须要将本身的Favicon.ico(文件名不能改动),放置到类路径根目录、类路径META_INF/resources/下、类路径resources/下、类路径static/下或者类路径public/下。
在Springboot中配置WebMvcConfigurerAdapter的时候发现这个类过期了。因此看了下源码,发现官方在spring5弃用了WebMvcConfigurerAdapter,由于springboot2.0使用的spring5,因此会出现过期。
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);
@Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }
@Configuration public class WebMvcConfg extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }
其实,源码下WebMvcConfigurerAdapter是实现WebMvcConfigurer接口,因此直接实现WebMvcConfigurer接口也能够;WebMvcConfigurationSupport与WebMvcConfigurerAdapter、接口WebMvcConfigurer处于同一个目录下WebMvcConfigurationSupport包含WebMvcConfigurer里面的方法,由此看来版本中应该是推荐使用WebMvcConfigurationSupport类的,WebMvcConfigurationSupport应该是新版本中对WebMvcConfigurerAdapter的替换和扩展
// 能够直接使用addResourceLocations 指定磁盘绝对路径,一样能够配置多个位置,注意路径写法须要加上file: registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");
// 访问myres根目录下的fengjing.jpg 的URL为 http://localhost:8080/fengjing.jpg (/** 会覆盖系统默认的配置) registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");