【问题标题】:Spring Boot will serve static resources or my 404 redirection Handler, but not bothSpring Boot 将提供静态资源或我的 404 重定向处理程序,但不能同时提供
【发布时间】:2019-12-13 11:44:45
【问题描述】:

我有一个与 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。

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 1970-01-01
      • 2014-09-15
      • 2019-09-20
      • 2023-03-31
      • 1970-01-01
      • 2018-03-16
      • 2021-10-11
      • 2015-05-24
      相关资源
      最近更新 更多