Spring Boot 设置静态资源访问

问题描述

当使用spring Boot来架设服务系统时,有时候也须要用到前端页面,固然就不可或缺地须要访问其余一些静态资源,好比图片、css、js等文件。那么如何设置Spring Boot网站能够访问获得这些静态资源,以及静态资源如何布局?css

解决方案

这里引用stackoverflow网站的问题截图:[http://stackoverflow.com/questions/27381781/java-spring-boot-how-to-map-my-my-app-root-to-index-html] 
这里写图片描述 
以及config/WebConfig.Java的内容以下:html

@Configuration @EnableWebMvc @ComponentScan public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("/"); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

常见问题

官方的解说

最多见的就是官方给出的方案:http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html 
具体位置在26.1.4 Static Content 
可是通过检验 src/main/resources目录下的资源文件不能被直接访问到。图片说明以下: 
这里写图片描述前端

解释

其实官方解释没有说起一点,就是不能使用@EnableWebMvc,固然若是Spring Boot在classpath里看到有 spring webmvc 也会自动添加@EnableWebMvc (http://spring.io/guides/gs/rest-service/)java

若是@EnableWebMvc了,那么就会自动覆盖了官方给出的/static/publicMETA-INF/resources/resources等存放静态资源的目录。而将静态资源定位于src/main/webapp。当须要从新定义好资源所在目录时,则须要主动添加上述的那个配置类,来Override addResourceHandlers方法。web

相关文章
相关标签/搜索