如何使Angular 6路由在Java WAR包中完美运行(部署至Wildfly等服务器)
我之前在把Angular 6应用打包成WAR部署到Wildfly的时候,也踩过路由的坑,尤其是刷新页面404的问题。结合你的情况,已经用了ng build --base-href=/my/app/,接下来只需要调整Angular路由配置和服务器端的重定向规则,就能完美运行了,具体步骤如下:
首先确保你的路由模块使用默认的PathLocationStrategy(这是Angular的默认策略,能生成干净的URL,比如/my/app/about而不是带#的哈希路由),同时配置通配路由处理无效路径:
在src/app/app-routing.module.ts中修改如下:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; // 导入你的组件 import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: '', component: HomeComponent }, // 根路径对应首页 { path: 'about', component: AboutComponent }, // 示例路由 { path: '**', redirectTo: '' } // 通配路由,把所有无效路径重定向到首页 ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
因为Angular是单页应用,所有路由都是客户端处理的。当用户刷新/my/app/about这类URL时,Wildfly会误以为这是一个服务器端的资源路径,从而返回404。我们需要让服务器把所有非静态资源的请求都转发到Angular的index.html,让客户端路由来处理。
这里有两种常用方案:
方案一:通过web.xml配置错误页面重定向
在WAR包的WEB-INF/web.xml文件中添加以下配置:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 设置Angular的index.html为欢迎页 --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- 把404错误请求重定向到index.html,由Angular路由处理 --> <error-page> <error-code>404</error-code> <location>/index.html</location> </error-page> </web-app>
这个方案简单直接,适合大多数场景。
方案二:使用RewriteValve(更灵活)
如果需要更精细的URL规则控制,可以用Wildfly的RewriteValve:
- 在WAR包的
WEB-INF/jboss-web.xml中添加Valve配置:
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd"> <valve> <class-name>org.apache.catalina.valves.rewrite.RewriteValve</class-name> </valve> </jboss-web>
- 在WAR包的
WEB-INF目录下创建rewrite.config文件,添加重写规则:
RewriteEngine On # 排除静态资源(assets、JS、CSS、图片等),这些直接返回服务器资源 RewriteCond %{REQUEST_URI} !^/my/app/(assets|favicon\.ico|.*\.js|.*\.css|.*\.png|.*\.jpg|.*\.svg)$ # 所有其他请求转发到index.html RewriteRule ^/my/app/(.*)$ /my/app/index.html [L]
注意:这里的/my/app/要和你ng build时指定的base-href完全一致
确保你用正确的命令构建Angular应用,建议加上--prod参数做生产环境优化:
ng build --base-href=/my/app/ --prod
构建完成后,把dist目录下的所有文件复制到WAR包的根目录(或者对应base-href的路径下),然后正常部署WAR到Wildfly即可。
部署完成后,测试以下场景:
- 访问
http://your-server:port/my/app/,能正常加载首页 - 点击路由链接跳转到子页面(比如
/my/app/about),页面正常渲染 - 刷新子页面URL,不会出现404,而是正确加载对应组件
- 输入不存在的路径(比如
/my/app/unknown),会被通配路由重定向到首页
内容的提问来源于stack exchange,提问作者Socrates

