项目情况概述
后端服务
- SpringBoot3
- Tomcat10
前端服务
- vite
- react
- react-router-dom
需求
前端项目访问的地址为http://ip:port/financial/view/*****
后端项目访问的地址为http://ip:port/finacial/api/******
项目为前后端分离的项目。现在想要将前端和后端部署到tomcat的同一个应用中。
前端项目改造
- 设置base: 在vite.config.js中,设置
base选项为/financial,这样Vite在构建时会根据这个基础路径来加载资源(如JS、CSS等)。
export default defineConfig(
{
base: "/financial",
build:{
outDir: "view",
rollupOptions:{ // 配置rollup的一些配置策略
output:{ // 控制输出
assetFileNames:"[hash].[name].[ext]",
manualChunks: (id: string) => {
if (id.includes("node_modules")) {
return "vendor";
}
},
sourcemap: true //源码调试功能
}
}
},
}
)
- 设置React Router的basename:在BowserRouter的路由组件总设置basename=‘/financial’
- 修改路由定义:确保所有路由都在这个basename下。
<BrowserRouter basename={'/financial'}>
<App/>
</BrowserRouter>
- 修改打包输出路径:在vite.config.js中,设置
build.outDie选项为view
export default defineConfig(
{
build:{
outDir: "view",
rollupOptions:{ // 配置rollup的一些配置策略
output:{ // 控制输出
assetFileNames:"[hash].[name].[ext]",
manualChunks: (id: string) => {
if (id.includes("node_modules")) {
return "vendor";
}
},
sourcemap: true //源码调试功能
}
}
},
}
)
- 执行
npm run build的命令前端打包
后端项目改造
- 在SpringBoot的项目的配置文件(
application.properties)中配置静态资源的位置spring.web.resources.static-locations=classpath:/static/view/ - 配置路由重定向的功能
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import java.io.IOException;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/view/**")
.addResourceLocations("classpath:/static/view/")
.setCachePeriod(3600)
.resourceChain(true)
// 添加自定义资源解析器
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
// 1. 检查请求的资源是否存在
if (requestedResource.exists() && requestedResource.isReadable()) {
return requestedResource;
}
// 2. 否则返回index.html(处理前端路由)
return new ClassPathResource("/static/view/index.html");
}
});
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 仅设置根路径重定向
registry.addRedirectViewController("/", "/view/dashboard");
}
}
- 拷贝前端打包生成的view整个文件夹到
src/main/resource/static的目录中去 - 检查打成的war包的文件名称是否为
financial.war。如果名称不对部署后启动会访问报404 - 运行
bootWar的命令将项目达成war包部署到外部的Tomcat的webapps的目录下 - 启动tomcat,访问``http://ip:port/financial`
评论区