Spring捕获index.html的所有路由 [英] Spring catch all route for index.html

查看:181
本文介绍了Spring捕获index.html的所有路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为基于React的单页应用程序开发一个Spring后端,其中我在使用React-Router进行客户端路由.

I'm developing a spring backend for a react-based single page application where I'm using react-router for client-side routing.

在index.html页面旁边,后端在路径/api/**上提供数据.

Beside the index.html page the backend serves data on the path /api/**.

为了在我的应用程序的根路径/上从src/main/resources/public/index.html提供我的index.html,我添加了一个资源处理程序

In order to serve my index.html from src/main/resources/public/index.html on the root path / of my application I added a resource handler

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/").addResourceLocations("/index.html");
}

我想要的是在没有其他路由匹配时(例如,当我呼叫/api以外的路径时.

What I want to is to serve the index.html page whenever no other route matches, e.g. when I call a path other than /api.

如何在春季配置这样的全包式路线?

How do I configure such catch-all route in spring?

推荐答案

由于我的react应用可以将根用作转发目标,因此最终对我有用

Since my react app could use the root as forward target this ended up working for me

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/{spring:\\w+}")
            .setViewName("forward:/");
      registry.addViewController("/**/{spring:\\w+}")
            .setViewName("forward:/");
      registry.addViewController("/{spring:\\w+}/**{spring:?!(\\.js|\\.css)$}")
            .setViewName("forward:/");
  }
}

说实话,我不知道为什么必须严格按照这种特定格式来避免无限转发循环.

To be honest I have no idea why it has to be exactly in this specific format to avoid infinite forwarding loop.

这篇关于Spring捕获index.html的所有路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆