Spring Boot将提供静态资源或我的404重定向处理程序,但不会同时提供两者

时间:2019-08-05 23:47:55

标签: spring spring-boot

我有一个与React捆绑在一起的Spring Boot应用程序,我想将所有未作为静态资源找到的请求重定向到索引(以便React可以处理单页路由)。

当前,我可以提供静态资源或404重定向,但不能同时提供这两种服务。

有人看到我的配置有问题吗?

静态资源位于我的Jar中,位于:

classes/static/index.html (etc)

Spring Boot application.yaml配置

spring:
  main:
    allow-bean-definition-overriding: true
  mvc:
    throw-exception-if-no-handler-found: true
    static-path-pattern: /**
  resources:
    static-locations: classpath:/static

NotFoundResourceHandler.java:

@ControllerAdvice
public class NotFoundHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<String> renderDefaultPage() {
        try {
            InputStream inputStream = new ClassPathResource("/static/index.html").getInputStream();
            String body = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(body);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("There was an error completing the action.");
        }
    }
}

以上配置将很好地服务于静态资源。我还能够使用404处理程序(当我从/和其他配置提供资源时)-但在那种情况下,它正在对所有资源(包括JS / CSS / Media文件)使用它)。

感谢您提供的任何帮助!

更新: 现在解决了。我现在知道它不起作用,因为它会将每个请求(/ )映射到静态处理程序,因此正在处理所有404。我通过将静态处理程序映射到特定路径(/ subdirectory / )使它起作用,并且对于该/ subdirectory路径之外的任何请求,都应该抛出404处理程序(/ brokenpath应该导致404处理程序触发) -然后我将404处理程序设置为重定向到/subdirectory/index.html。

1 个答案:

答案 0 :(得分:0)

更新:现在已解决。我现在知道它不起作用,因为它将每个请求(/)映射到静态处理程序,因此正在处理所有404。我通过将静态处理程序映射到特定路径(/ subdirectory /)使其工作,并且对于该/ subdirectory路径之外的任何请求,都应该抛出404处理程序(/ brokenpath应该导致404处理程序触发)-然后我设置404处理程序以重定向到/subdirectory/index.html。