gpt4 book ai didi

angularjs - 在 Spring Boot 中将未知请求重定向到 index.html

转载 作者:行者123 更新时间:2023-12-04 03:13:50 24 4
gpt4 key购买 nike

我正在尝试通过 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”。有没有办法为所有无法映射到某物或找不到的请求设置默认 View ?

我之前通过使用 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。

最佳答案

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

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

编辑:作为更好的解决方案,您可以让 Controller 实现 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 .

关于angularjs - 在 Spring Boot 中将未知请求重定向到 index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com