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



我有一个带有react的弹簧启动应用程序,我想重新指导所有作为静态资源回到索引的所有请求(因此React可以处理单个请求-Page路由(。

目前,我可以提供静态资源或进行404重定向,但不能同时进行。

有人看到我的配置有任何问题?

静态资源在我的罐子中:

classes/static/index.html (etc)

Spring Boot Application.yaml config

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 Files(。

感谢您提供的任何帮助!

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

更新:现在已经解决。我现在知道它不起作用,因为它将每个请求(/(映射到静态处理程序,因此正在处理所有404。我通过将静态处理程序映射到特定的路径(/subdirectory/(来工作,并且应该为该/子目录路径以外的任何请求抛出404处理程序(/swarkpath应该导致404处理程序发射(将404处理程序设置为重定向到/subdirectory/index.html。

相关内容

最新更新