关于angular:Spring Mvc和Angular2在Tomcat服务器上运行

Spring Mvc and Angular2 run on Tomcat server

我希望Angular 2项目中的index.html作为Spring MVC应用程序的欢迎页面运行。我们不能使用maven项目,只能创建spring MVC项目。

我尝试将angular dist文件夹复制到Web目录中,

1
2
3
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

这是我的文件夹结构,

enter image description here

我收到了HTTP状态404-错误

有什么可以帮助我的吗?

谢谢!!!


您需要注意以下两点:

第一-您需要将angular伪影保持在WEB-INF目录之外。您应该将dist文件夹的内容直接复制到您的web目录中。

引用-/ WEB-INF中的JSP返回" HTTP状态404请求的资源不可用",以获取更多详细信息。

第二个-您的index.html应该包含正确的base href,而不仅仅是默认的"/"。您的base href应该是

1
<base href="/myUrl/">

其中myUrl是您的Web应用程序上下文。

您可以在index.html中手动修改基本href,也可以在构建这样的angular应用程序时提供它。

1
ng build --base-href /myUrl/

参考-动态设置基本href-Angular 2/4/5了解更多详细信息。

更新

如果您真的想将棱角伪影保留在/web/dist目录中,请

您的web.xml应该具有以下内容

1
2
3
<welcome-file-list>
    <welcome-file>dist/index.html</welcome-file>
</welcome-file-list>

,并且您的index.html应该包含

1
<base href="/myUrl/dist/">

,您应该定义一个端点

1
2
3
4
@GetMapping("/dist")
public void forward(HttpServletResponse response) throws IOException {
    response.sendRedirect("/myUrl/dist/index.html");
}

然后,您可以使用以下任意网址访问您的angular应用程序

1
2
3
http://host:port/myUrl
http://host:port/myUrl/dist
http://host:port/myUrl/dist/index.html

并重新加载也不会造成任何问题。

更新-2

以上端点可能无法重新加载html5Angular Routingurl。因此,可以使用下面的过滤器代替上面的终结点,该过滤器将能够处理重新加载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
             ....
             .addFilterAfter(new OncePerRequestFilter() {
                   // add the values you want to redirect for
                   private Pattern patt = Pattern.compile("/dist/.*");

                   @Override
                   protected void doFilterInternal(HttpServletRequest request,
                                                   HttpServletResponse response,
                                                   FilterChain filterChain)
                                    throws ServletException, IOException {
                        if(this.patt.matcher(request.getRequestURI()).matches()) {
                            RequestDispatcher rd = request.getRequestDispatcher("/dist/index.html");
                            rd.forward(request, response);
                        } else {
                            filterChain.doFilter(request, response);
                        }
                 }
        }, FilterSecurityInterceptor.class)
        ....

参考-https://github.com/spring-guides/tut-spring-security-and-angular-js/issues/68#issuecomment-187675742了解更多详细信息。