SpringBoot 靜態資源訪問不到的問題

    現在很多人都在用SpringBoot來搭建微服務,記錄下遇到的資源訪問的問題。

    在SpringBoot 1.x.x 版本中問題很好解決。但是在2.x.x版本中會發現 以前的不起效了。resources/static 下面放置的

css ,js ,圖片等靜態資源無法訪問了。解決方法如下面這個類即可

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {


    /**
     *  視圖跳轉控制器
     * 無業務邏輯的跳轉 均可以以這種方法寫在這裏
     * @param registry
     */
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("wes");
        registry.addViewController("/home").setViewName("wes");
        registry.addViewController("/login").setViewName("login");
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //告知系統static 當成 靜態資源訪問
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

   按照上面的第二個方法進行配置 那麼static文件夾下的靜態資源就可以訪問了,在頁面中引用的時候

<link href="/static/css/bootstrap.min.css" rel="stylesheet">  這樣就可以了

     當然還有一個問題, 如果各位在項目中引入了 spring-boot-starter-security  那麼你會發現上面的配置又不起作用了。所以如果配置了SpringSecurity 除了上面的方法 還需要如下操作:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
       //解決靜態資源被攔截的問題的
        web.ignoring().antMatchers("/static/**");
    }
}

      

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章