2014-09-22 102 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。