【问题标题】:Redirect unknown requests to index.html in springboot在 Spring Boot 中将未知请求重定向到 index.html
【发布时间】:2017-08-09 10:58:56
【问题描述】:

我正在尝试通过 springboot Web 应用程序提供 Angular2 应用程序。我找到了很多非常简单的示例:

https://spring.io/blog/2015/01/12/spring-and-angular-js-a-secure-single-page-application#using-spring-boot-cli

https://github.com/zouabimourad/angular2-spring/tree/master/front

https://github.com/ehirsch/spring-angular2

但是,这些示例非常简单,它们基本上只是展示了如何显示恰好是 Angular 的静态内容。

它们都没有展示如何处理 Angular2 应用使用的任何不映射到“真实”资源的 URL(我认为它们被称为路由)。

例如。我们在 Angular 应用程序中有一个“/login”路由,但我们没有 @Controller/@RequestMapping("/login") 用于此,我希望 Spring 在看到对“/”的请求时呈现 index.html登录”。

一般来说 - 我希望 Spring 在它不能成为实际资源时呈现“index.html”。有没有办法为所有无法映射或找到的请求设置默认视图?

我之前使用 htaccess 文件解决了这个问题,并让 apache 处理这个问题:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule . index.html [L]
   ErrorDocument 404 /index.html
</IfModule>

但在这种情况下我不能使用 apache 或 nginx。

【问题讨论】:

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


    【解决方案1】:

    作为一个循环工作,我在RequestMapping 注释中添加了Angular Routes,并将它们全部指向index.html:

    @RequestMapping({"/login", "/logout"})
    public String index() { return "index.html"; }
    

    编辑:作为一个更好的工作循环,您可以让控制器实现ErrorController,覆盖getErrorPath 方法,然后为/error 添加一个映射,它将作为一个包罗万象(或映射缺少)方法。

    @Controller
    public class TheOneController implements ErrorController {
    
        @RequestMapping("/error")
        public String index() {
            return "index.html";
        }
    
        @Override
        public String getErrorPath() {
            return "index.html";
        }
    }
    

    现在index 方法将处理任何无法找到的内容并呈现index.html。

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 2018-02-27
      • 2020-01-22
      • 2020-11-08
      • 1970-01-01
      • 2020-03-18
      • 2018-11-16
      • 2015-09-27
      • 2016-10-15
      相关资源
      最近更新 更多