Spring Mvc和Angular2运行在Tomcat服务器上。

9 浏览
0 Comments

Spring Mvc和Angular2运行在Tomcat服务器上。

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

我已经尝试将Angular dist文件夹复制到web目录中,


    index.html

这是我的文件夹结构,

enter image description here

我得到了HTTP状态404-错误

有人可以帮我吗?

提前感谢!

0
0 Comments

问题的原因是,当加载主页时,URL变为http://host:port/myUrl/dist/,当重新加载页面时,无法在该URL上找到任何内容。因此,最好将dist文件夹中的内容复制到web目录中。

解决方法是将dist文件夹中的内容复制到web目录中,或者按照更新的答案进行操作。

如果确实希望将Angular构件保留在/web/dist目录中,则需要进行以下操作:

1. 在web.xml文件中添加以下内容:

<welcome-file-list>
    <welcome-file>dist/index.html</welcome-file>
</welcome-file-list>

2. 在index.html文件中设置base href:

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

3. 定义一个端点:

("/dist")
public void forward(HttpServletResponse response) throws IOException {
    response.sendRedirect("/myUrl/dist/index.html");
}

然后,您可以使用以下任何URL访问您的Angular应用程序:

http://host:port/myUrl
http://host:port/myUrl/dist
http://host:port/myUrl/dist/index.html

重新加载页面也不会有任何问题。

如果以上端点无法重新加载html5的Angular路由URL,则可以使用下面的过滤器进行处理。

    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/.*");
                   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)
        .... 

如果您真的希望将Angular构件保留在/web/dist目录中,请按照上述更新的答案操作。

总结起来,如果您希望在Tomcat服务器上运行Spring MVC和Angular 2,请注意以下两点:

1. 将Angular构件复制到web目录中,而不是WEB-INF目录。

2. 确保index.html文件中的base href正确设置。

0