上一節我們講到了RestController,這節記錄下靜態資源的請求。
第一步:copy一個圖片到resource下面
第二步:在瀏覽器輸入http://127.0.0.1:8080/about_bg1.png訪問是404.這是因爲我們採用的spring boot 2* 所以需要進行靜態資源配置纔行。
第三步:新建一個WebConfig文件
內容:
package com.springboot.configWeb;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig2 extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
}
}
核心註解@Configuration
@Configuration標註在類上,相當於把該類作爲spring的xml配置文件中的,作用爲:配置spring容器(應用上下文)
繼承WebMvcConfigurationSupport 並重寫其中的addResourceHandlers方法
第四步:在瀏覽器輸入http://127.0.0.1:8080/about_bg1.png這時候就可以成功訪問到靜態資源了。
注意:新建的文件必須在主方法的掃描範圍之內,也就是必須在com.springboot下面,不然識別不到Configuration