2016-08-18 19 views
5

Tôi hiện đang làm việc trên một trang web nên sử dụng một trang duy nhất Phản hồi front-end. Đối với back-end, tôi đang sử dụng khung khởi động mùa xuân.SPA với Spring Boot - phục vụ index.html cho các yêu cầu không phải API

Tất cả cuộc gọi api phải sử dụng url được bắt đầu bằng /api và phải được xử lý bởi bộ điều khiển REST.

Tất cả các url khác chỉ cần phân phát tệp index.html. Làm thế nào tôi sẽ đạt được điều này với mùa xuân?

Trả lời

4

Cách dễ nhất để đạt được những gì bạn muốn là triển khai trình xử lý 404 tùy chỉnh.

Thêm các params để application.properties của bạn:

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

bất động sản đầu tiên loại bỏ tất cả các xử lý tài nguyên tĩnh mặc định, tài sản thứ hai vô hiệu hóa trang Nhãn trắng mặc định Spring (bởi Spring mặc định bắt NoHandlerFoundException và phục vụ trang Nhãn trắng tiêu chuẩn)

Thêm handler 404 đến bối cảnh ứng dụng của bạn:

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

Vào cuối bạn sẽ cần phải thêm cái nhìn thống xử lý tuỳ chỉnh của bạn để phục vụ nội dung tĩnh của bạn (index.html trong trường hợp này)

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

} 

bạn index.html nên được đặt trong thư mục /resources/static/.

Các vấn đề liên quan