2016-08-18 3 views
5

現在、1ページのリアクションフロントエンドを使用するWebページで作業しています。バックエンドについては、私は春のブートフレームワークを使用しています。SPA with Spring Boot - API以外のリクエストに対してindex.htmlを配信します。

すべてのapi呼び出しは、接頭辞が/apiのURLを使用するものとし、RESTコントローラで処理する必要があります。

他のすべてのURLは、index.htmlファイルを提供するだけです。私は春にどのようにこれを達成するでしょうか?

答えて

4

あなたが望むものを達成する最も簡単な方法は、カスタム404ハンドラを実装することです。

はこれらのparamsをごapplication.propertiesに追加:

spring.resources.add-mappings=false 
spring.mvc.throw-exception-if-no-handler-found=true 

最初のプロパティは、すべてデフォルトの静的リソースの取り扱いを削除し、第二の特性は、(デフォルトの春でNoHandlerFoundExceptionをキャッチし、標準のホワイトレーベルのページを用意しています)Springのデフォルトのホワイトレーベルのページを無効にします

アプリケーションコンテキストに404ハンドラを追加します。

あなたは(このケースではindex.html)あなたの静的なコンテンツを提供するためにカスタムビューリゾルバを追加する必要があります終わり

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.ViewResolver; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 
import org.springframework.web.servlet.view.InternalResourceView; 
import org.springframework.web.servlet.view.UrlBasedViewResolver; 

@Configuration 
@EnableWebMvc 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/index.html").addResourceLocations("classpath:/static/index.html"); 
     super.addResourceHandlers(registry); 
    } 

    @Bean 
    public ViewResolver viewResolver() { 
     UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); 
     viewResolver.setViewClass(InternalResourceView.class); 
     return viewResolver; 
    } 

} 

あなたindex.html/resources/static/ディレクトリに配置する必要があります。

関連する問題