其實,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,即可在瀏覽器中看到圖片。