我正在尝试通过springboot Web应用程序提供Angular2应用程序。我已经找到了很多如何做到这一点的例子:
https://github.com/zouabimourad/angular2-spring/tree/master/front
https://github.com/ehirsch/spring-angular2
但是,这些示例非常简单,它们基本上只显示了如何显示恰好是Angular的静态内容。
它们都没有显示如何处理Angular2应用程序使用的任何不会映射到“真实”资源的URL(我认为它们被称为路由)。
EG。我们在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。
答案 0 :(得分:2)
作为一个循环工作,我在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
。