SpringBoot默认的打包方式是jar(Java归档),那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的
我们先来看一下这个静态资源映射规则,SpringBoot中,SpringMVC的web配置都在org.springframework.boot.autoconfigure.web.servlet包下的WebMvcAutoConfiguration 这个配置里面,我们找到addResourceHandlers这个方法,该方法用于处理webjars方式的静态资源映射
- @Override
- protected void addResourceHandlers(ResourceHandlerRegistry registry) {
- super.addResourceHandlers(registry);
- if (!this.resourceProperties.isAddMappings()) {
- logger.debug("Default resource handling disabled");
- return;
- }
- ServletContext servletContext = getServletContext();
- addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
- addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
- registration.addResourceLocations(this.resourceProperties.getStaticLocations());
- if (servletContext != null) {
- registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
- }
- });
- }
阅读一下源码,所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源,那什么是webjars呢?
webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。使用SpringBoot可以使用webjars,官网:WebJars - Web Libraries in Jars
只需导入相应pom依赖即可使用

自定义一个WebMvcConfig继承WebMvcConfigurationSupport
- @Configuration
- public class WebMvcConfig extends WebMvcConfigurationSupport {
- /**
- * 添加静态资源映射
- * @param registry
- */
- @Override
- protected void addResourceHandlers(ResourceHandlerRegistry registry) {
- // "/backend/**" 表示/backend下的所有文件夹及其子文件夹
- registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
- registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
- }
- }
输入http://localhost:8080/backend/index.html即可访问
- # 自定义静态资源访问路径,可以指定多个,之间用逗号隔开
- spring.resources.static-locations=classpath:/myabc/,classpath:/myhhh
正如上面注释所描述的一样,自定义静态资源访问路径,可以指定多个,之间用逗号隔开,其中使用这种方式特别要注意:自定义静态资源后,SpringBoot默认的静态资源路径将不再起作用!