在Weblogic Server部署带Vue/Vite前端的Spring Boot应用遇静态资源404
核心原因是Vite构建时默认使用绝对根路径加载资源,而你的应用部署在Weblogic的/myapp上下文路径下,导致资源请求路径错误(从/weblogicurl/assets而非/weblogicurl/myapp/assets获取)。以下是具体修复步骤:
1. 修正Vite的资源基础路径配置
在Vue项目的vite.config.js(或.ts)中,设置base属性为你的Weblogic应用上下文路径:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], base: '/myapp/' // 与Weblogic部署的上下文根保持一致 })
如果不确定固定上下文路径,也可以设置为相对路径'./',但需注意后续Vue Router的路由模式适配。
修改后重新执行npm run build,将新生成的dist目录下的文件替换到Spring Boot项目的src/main/resources/static目录。
2. 确认Spring Boot静态资源配置
确保Spring Boot未覆盖默认静态资源映射规则。如果自定义了WebMvc配置,需保证包含static目录的映射:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); } }
默认情况下Spring Boot会自动识别src/main/resources/static作为静态资源目录,若无自定义配置可跳过此步。
3. 核对Weblogic部署上下文根
在Weblogic控制台中,确认你的应用部署时的**上下文根(Context Root)**设置为/myapp,与Vite配置的base完全一致。若部署时上下文根变更,需同步修改Vite的base配置并重新构建。
4. Vue Router路由适配(若使用路由)
如果项目使用Vue Router,需避免history模式下的路径冲突:
- 推荐使用hash模式:
import { createRouter, createWebHashHistory } from 'vue-router' const router = createRouter({ history: createWebHashHistory(), // hash模式无需依赖服务器路径配置 routes: [/* 你的路由配置 */] })
- 若坚持使用history模式,需将路由的
base设置为上下文路径:
import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory('/myapp/'), routes: [/* 你的路由配置 */] })
完成以上步骤后,重新打包Spring Boot为war包部署到Weblogic,访问weblogicurl/myapp/index.html即可正常加载静态资源。
内容的提问来源于stack exchange,提问作者Magitrix Alyxra

