Spring Boot映射静态资源

在Spring Boot项目中,新建项目时,默认可以访问resource下的静态资源。但启用@EnableWebMvc并继承WebMvcConfigurerAdapter后,静态资源无法访问。问题在于这改变了默认静态资源配置。解决方案是重新添加默认静态资源路径,使得静态资源能够正常访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发配置:

  • IntelliJ Idea
  • JDK 1.8.0.131 64-bit
  • spring boot 1.5.8

1.新建项目

使用Idea新建项目,默认情况下,resource下:META-INF/resources、resources,static、public下的静态文件可直接访问,如下所示:

文件路径

访问地址:
http://localhost:8080/desert1.jpg
http://localhost:8080/desert2.jpg
http://localhost:8080/desert3.jpg
http://localhost:8080/desert4.jpg

2.使用@EnableWebMvc并继承WebMvcConfigurerAdapter类之后,无法访问静态资源

这里写图片描述

WebConfig

package com.example.demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Aaron
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

}

这里写图片描述

原因:
@EnableWebMvc配合WebMvcConfigurerAdapter修改了默认的静态资源范围配置,参考:http://blog.youkuaiyun.com/pinebud55/article/details/53420481

解决:
将默认的静态资源范围路径加回来:

package com.example.demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Aaron
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }

}

再次访问静态资源,ok!

参考:https://stackoverflow.com/questions/24661289/spring-boot-not-serving-static-content


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值