2016-08-18 8 views
5

Aktualnie pracuję nad stroną, która powinna korzystać z jednej strony React front-end. W przypadku back-endu używam framugi sprężynowej.SPA ze Spring Boot - służy do obsługi index.html dla żądań innych niż API

Wszystkie wywołania interfejsu API powinny zawierać adres URL z prefiksem /api i powinny być obsługiwane przez kontrolery REST.

Wszystkie inne adresy URL powinny po prostu służyć do pliku index.html. Jak to osiągnąć wiosną?

Odpowiedz

4

Najprostszym sposobem na osiągnięcie tego, co chcesz, jest zaimplementowanie niestandardowego programu obsługi 404.

Dodaj te params do application.properties:

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

Pierwsza nieruchomość usuwa wszystkie domyślne obsługę zasobów statycznych, druga właściwość wyłącza domyślną stronę Whitelabel Wiosny (domyślnie Wiosna łapie NoHandlerFoundException i służy standardowej strony Whitelabel)

obsługi 404 Dodaj do kontekstu aplikacji:

import org.springframework.web.bind.annotation.ControllerAdvice; 
import org.springframework.web.bind.annotation.ExceptionHandler; 
import org.springframework.web.servlet.NoHandlerFoundException; 
import javax.servlet.http.HttpServletRequest; 

@ControllerAdvice 
public class PageNotFoundController { 
    @ExceptionHandler(NoHandlerFoundException.class) 
    public String handleError404() { 
      return "redirect:/index.html"; 
    } 
} 

Na koniec trzeba będzie dodać niestandardowy widok rozpoznawania nazw dla obsługujących zawartość statyczną (index.html w tym przypadku)

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; 
    } 

} 

Twój index.html powinny być umieszczone w /resources/static/ katalogu.