【问题标题】:Hosting a single page application with spring boot使用 Spring Boot 托管单页应用程序
【发布时间】:2019-06-19 00:58:46
【问题描述】:

所以我正在尝试使用 spring 托管一个单页应用程序以及一个普通的 REST API。

这意味着所有到达普通/api/端点的请求都应该由各自的控制器处理,所有其他请求都应该被定向到文件夹/static/built中的资源

我已经通过捕获所有NoHandlerFoundExceptions 并重定向到js 文件或html 文件来实现此功能。然后使用WebMvcConfigurer 映射静态内容。

但这一切对我来说似乎都是一种 hack,那么有没有一种不那么 hacky 的方法呢?

【问题讨论】:

  • 您只需将构建的前端文件复制到 Spring boot static/ 目录(您可以使用 maven 前端插件来自动化)。然后 Spring Boot 会将它们作为静态文件提供,您无需担心重定向到 html 或 js。您是否在 SPA (so.com/#/route/...) 中使用基于哈希的 URL?如果是这样,您在春季无事可做

标签: spring spring-boot spring-mvc single-page-application


【解决方案1】:

通过添加以下映射管理 React+ReactRouter 应用程序工作:

@Controller
public class RedirectController {

  @GetMapping(value = {"/{regex:\\w+}", "/**/{regex:\\w+}"})
  public String forward404() {
    return "forward:/";
  }

}

这是受到https://stackoverflow.com/a/42998817/991894的启发

【讨论】:

  • 连字符不是\w 正则表达式字符,但可以在端点中,因此将\\w 替换为[\\w-](正则表达式方括号以捕获额外的连字符字符)。 . 期间相同,但作为端点名称不太常见,可能指的是静态文件资源,所以我不会包含它。
【解决方案2】:

让我的 SPA 使用 Spring 后端 API 的最简单方法是使用 2 个不同的控制器:一个用于 SPA 的根索引页面,另一个控制器用于管理各种 RESTful API 端点:

这是我的两个控制器:

MainController.java

@Controller
public class MainController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}

MonitoringController.java

@RestController
@RequestMapping(value = "api")
public class MonitoringEndpoints {

    @GetMapping(path = "/health", produces = "application/hal+json")
    public ResponseEntity<?> checkHealth() throws Exception {
        HealthBean healthBean = new HealthBean();
        healthBean.setStatus("UP");

        return ResponseEntity.ok(healthBean);
    }
}

请注意 API 端点控制器如何使用“@RestConroller”注解,而主控制器如何使用“@Conroller”注解。这是因为 Thymeleaf 如何利用它的 ViewResolver。见:

Spring Boot MVC, not returning my view

现在继续把你的 index.html 页面放在 src/main/resources/templates/index.html 因为 Spring 默认在这个位置寻找你的 html 页面。

我的 index.html 页面如下所示:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head lang="en">
        <meta charset="UTF-8"/>
        <title>EDP Monitoring Tool</title>
    </head>
    <body>
        <!-- Entry point to our ReactJS single page web application -->
        <div id="root"></div>

        <script type="text/javascript" src="built/bundle.js"></script>
    </body>
</html>

不确定您是如何连接前端的,无论是 ReactJS 应用还是其他什么,但我相信这些信息会对您有所帮助。让我知道我是否可以为您回答其他问题。

另外,如果你使用 Webpack,你可以通过 entry 键下的 webpack.config.js 文件来设置你的 JS 文件的入口点,如下所示:

entry: ['./src/main/js/index.js']

【讨论】:

    【解决方案3】:

    我认为您正在寻找术语 URL 重写。

    例如https://getpostcookie.com/blog/url-rewriting-for-beginners/

    【讨论】:

    • 这个问题与Apache .htaccess无关
    猜你喜欢
    • 2018-09-05
    • 2015-12-15
    • 1970-01-01
    • 2020-04-28
    • 2021-11-22
    • 2020-01-08
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多