2017-09-01 71 views
0

我在使用Spring Boot提供靜態內容時遇到問題。彈簧引導靜態內容

我使用的默認配置位置是:src/main/resources/static/csssrc/main/resources/static/js

當頁面加載時,我得到所有靜態內容的404。我甚至在我的安全設置中添加了permitAll

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
    .authorizeRequests()  
     .antMatchers("/css/**","/js/**").permitAll() 
     .antMatchers("/services/**").hasRole("PREAUTH_USER") 
     .antMatchers("/", "/dashboard").permitAll() 
     .anyRequest().authenticated() 
    .and() 
     .formLogin().loginPage("/login") 
     .permitAll() 
    .and() 
     .logout() 
     .permitAll(); 
} 

我的資源處理程序:

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

...當我打我的login CSS是returing一個404http://localhost:8080/login

這裏是響應頭:

Request URL:http://localhost:8080/css/preauth.css 
Request Method:GET 
Status Code:404 
Remote Address:[::1]:8080 
Referrer Policy:no-referrer-when-downgrade 
Response Headers 
view source 
Cache-Control:no-cache, no-store, max-age=0, must-revalidate 
Content-Type:application/json;charset=UTF-8 
Date:Fri, 01 Sep 2017 17:04:59 GMT 
Expires:0 
Pragma:no-cache 
Transfer-Encoding:chunked 
X-Content-Type-Options:nosniff 
X-Frame-Options:DENY 
X-XSS-Protection:1; mode=block 
Request Headers 
view source 
Accept:text/css,*/*;q=0.1 
Accept-Encoding:gzip, deflate, br 
Accept-Language:en-US,en;q=0.8 
Connection:keep-alive 
Cookie:JSESSIONID=D1399529A7AD61D0FA67ECF0343D3A03 
Host:localhost:8080 
Referer:http://localhost:8080/login 
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36 
+0

您是否將它作爲jar運行? – harshavmb

+0

如果您使用的是默認資源文件夾,則不需要配置addresource處理程序。您可以將其刪除並重試。 SpringBoot將配置靜態文件夾並設置資源消耗 –

+0

也訪問https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot查看如何配置資源處理程序。 –

回答

0

這個問題似乎是在我擴展WebMvcConfigurationSupport時我的appConfig類(我需要配置messageconverters),WebMvcAutoConfiguration被禁用。所以,我不得不添加

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
     "classpath:/META-INF/resources/", "classpath:/resources/", 
     "classpath:/static/", "classpath:/public/" }; 

而且

@Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
if (!registry.hasMappingForPattern("/webjars/**")) { 
    registry.addResourceHandler("/webjars/**").addResourceLocations(
      "classpath:/META-INF/resources/webjars/"); 
} 
if (!registry.hasMappingForPattern("/**")) { 
    registry.addResourceHandler("/**").addResourceLocations(
      CLASSPATH_RESOURCE_LOCATIONS); 
} 

編輯: 不需要上面的代碼。我改變了我的配置類來擴展WebMvcConfigurerAdapter,並且上述更改不是必需的。請參閱下面的@AndyWilkinson註釋

+0

你爲什麼要擴展'WebMvcConfigurationSupport'?在Spring Boot應用程序中這是一件很不尋常的事情。推薦的方法是擴展'WebMvcConfigurerAdapter'。這使您可以自定義Spring MVC的自動配置,同時還可以保持Spring Boot的默認設置。 –

+0

@AndyWilkinson,謝謝安迪你是正確的..我修改了我的代碼,一切工作正常,我最初預期 –