2014-09-22 101 views
1

我正在使用角框架的春季啓動應用程序。我已經結構化的項目如下:春季啓動Web應用程序不提供靜態內容

  • 的src/main/java的:彈簧引導文件,控制器,持久性
  • 的src/main /資源:application.properties中
  • 的src/main /應用程序:「 web應用」的文件,有角的,CSS,模塊

爲了具有彈簧提供靜態內容下/應用我已經通過重寫addResourceHandlers方法擴展的類WebMvcConfigurerAdapter:

@EnableWebMvc 
@Configuration 
@ComponentScan(basePackages = { "com.myapp.controller" }) 
public class WebMvcConfig extends WebMvcConfigurerAdapter { 

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", 
     "classpath:/resources/", "/" }; //src/main/webapp works by default 

private static final String[] RESOURCE_LOCATIONS = { "classpath:/src/main/app/", "classpath:/src/main/app/" }; 

@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).setCachePeriod(0); 
    } 

    if (!registry.hasMappingForPattern("/app/**")) { 
     registry.addResourceHandler("/app/**").addResourceLocations(RESOURCE_LOCATIONS).setCachePeriod(0); 
    } 
}} 

當嘗試使用 http://localhost:8080/app/app.html 如果我重新命名成/ webapp的我能夠針對http://localhost:8080/app.html/app文件夾,我得到一個HTTP錯誤404由於某些原因要訪問角度主文件。我肯定錯過了一些東西,但無法弄清楚它是什麼。謝謝

+1

您在應用程序下有'src/main/app'。你是否配置了Maven或Gradle來包含該目錄?此外,爲什麼不遵循標準的Spring Boot約定來實現靜態內容? – geoand 2014-09-22 10:33:19

+1

我建議閱讀spring引用參考指南(尤其是那些默認已經映射的引用)和使用webjars。基本上你的WebMvcConfig類中有什麼是Spring Boot已經完成的,所以你只是複雜的事情。 – 2014-09-22 13:01:27

+0

@geoand是的,我使用build-helper-maven-plugin將源目錄的'src/main/app'添加到maven。使用標準的src/main/static和評論WebMvcConfig類我仍然有同樣的問題。 – user3278795 2014-09-22 13:28:49

回答

2

您需要在類路徑中提供資源的位置,而不是它們在源代碼中的位置。例如,src/main/resources/static中的資源由資源位置classpath:/static/提供,因爲Maven構建將導致src/main/resources中的所有內容都位於類路徑的根目錄中。簡而言之,classpath:/src/main/app的資源位置幾乎肯定是錯誤的:您需要配置Spring Boot以從您配置Maven的任何地方加載資源來構建和打包它們。

1

添加此文件。它爲我工作。假設靜態資源文件位於文件夾:src/main/webapp下。

@Configuration 公共類WebMappingConfig延伸WebMvcConfigurerAdapter {

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    // 1. when put angularjs under src/main/resources/static. 
    // String[] myExternalFilePath = {"classpath:/static/app/build/"}; 
    // 2. when put angularjs under src/main/webapp. 
    String[] staticResourceMappingPath = { "/app/build/", 
      "classpath:/static/", "classpath:/static/app/build/" }; 

    registry.addResourceHandler("/**").addResourceLocations(
      staticResourceMappingPath); 
} 

}

嘗試: 1.坎德拉/ SRC /主/ web應用 2. GIT中克隆https://github.com/ngbp/ngbp.git應用 3. CD應用 4. npm install
5.涼亭安裝 6. grunt手錶

但是,安裝時,靜態資源不會被複制到* .jar文件中,您需要將app/build /文件夾下的所有文件複製到src/main/resource/static。