其实,SpringBoot把类路径下的/static,/public,/resources和META-INF/resources文件下的静态文件映射为了“/”,可以直接访问,我们可以根据下面的方法自定义静态文件的存放位置。
package com.ghb.study.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("classpath:/img/");
super.addResourceHandlers(registry);
}
}
这样,我们就定义了一个和static平级的文件夹img用来存放图片,在该文件夹中放入图片,然后带上路径访问:
http://localhost:8680/img/???.jpg,即可在浏览器中看到图片。