2017-01-20 7 views
1

私は単純なAngularJSシングルページアプリケーションとバックエンド用のSpring Bootを持っています。異なるURLにindex.htmlを返す必要があります。 localhost:8080/sample/pages戻り状況へ春のブートで別のURLの同じディレクトリからファイルを返す方法は?

@Controller 
public class WebResourcesController { 

    @RequestMapping(value = {"/sample", "/sample/pages"}, method = RequestMethod.GET) 
    public String index() { 
     return "index"; 
    } 

} 

が、要求:私は、コントローラのこの種を作成しました。それでも私は要求を送るときlocalhost:8080/sample私は適切なhtmlファイルとページを読み込みます。私はindex.htmlresources/publicというフォルダに持っています。私は考えますlocalhost:8080/sample/pages要求は/の代わりにsample/pagesフォルダのリソースを検索しようとします。このような問題をどうやって解決するのですか?

+0

。同じコンテンツを扱う複数のURLを持つことは可能です。 "index"は、index.htmlをロードすることを意味します... requestMappingはファイルに対して何も処理を行いません。 –

答えて

1

私は、カスタムPathResourceResolverでWebMvcConfigurerAdapterを構成します:あなたは、クラスファイル(クラスの注釈@RequestMapping)の頭を与えることができる

@Configuration 
public class SinglePageAppWebMvcConfigurer extends WebMvcConfigurerAdapter 
{ 
    @Autowired 
    private ResourceProperties resourceProperties; 

    private String apiPath; 

    public SinglePageAppWebMvcConfigurer() 
    { 
    } 

    public SinglePageAppWebMvcConfigurer(String apiPath) 
    { 
     this.apiPath = apiPath; 
    } 

    protected String getApiPath() 
    { 
     return apiPath; 
    } 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) 
    { 
     registry.addResourceHandler("/**") 
      .addResourceLocations(resourceProperties.getStaticLocations()) 
      .setCachePeriod(resourceProperties.getCachePeriod()).resourceChain(true) 
      .addResolver(new SinglePageAppResourceResolver()); 
    } 

    private class SinglePageAppResourceResolver extends PathResourceResolver 
    { 
     @Override 
     protected Resource getResource(String resourcePath, Resource location) throws IOException 
     { 
      Resource resource = location.createRelative(resourcePath); 
      if (resource.exists() && resource.isReadable()) { 
       return resource; 
      } else if (getApiPath() != null && ("/" + resourcePath).startsWith(getApiPath())) { 
       return null; 
      } else { 
       LoggerFactory.getLogger(getClass()).info("Routing /" + resourcePath + " to /index.html"); 
       resource = location.createRelative("index.html"); 
       if (resource.exists() && resource.isReadable()) { 
        return resource; 
       } else { 
        return null; 
       } 
      } 
     } 
    } 
} 
+0

これは素晴らしいことですが、再利用可能です。それを任意のプロジェクトに '@インポート 'することができます。 –

+0

他のリソースを取得する際にこれに問題はありませんか?たとえば、 'index.module.js'、' index.controller.js'や、indexが置かれているメインディレクトリにない他のファイル – GROX13

+0

いいえ、それらは正常に取得されているためです。これは、解決可能なリソースを持たないパスのindex.htmlの内容を返します。 –

関連する問題