背景
Vue 作为数据驱动的前端框架,目前比较流行,因此我们公司最新的项目开发都选择 “SpringBoot 后台 + Vue 前端” 这个技术组合。如果一开始就选择这个技术组合,完全没问题。
但是,如果前端技术最初是传统的 html ,加上 Vue 后,旧的 web.xml 配置的欢迎页面为 ../index.html
,导致访问首页报错,本文来分析下这个问题。
SpringBoot + 传统 webapp
一个基于 SpringBoot 的 web 应用,工程最初选择的前端技术是 html 和 jsp 所以有 webapp 目录,且指定了 web.xml 文件:
webapps 目录下有默认首页 index.html
SpringBoot+ Vue 新组合
前端使用 Vue ,配置 vue.config.js 中 build 目录为
module.exports = {
outputDir: './src/main/resources/static',
publicPath: './',
devServer: {
port: 8080, // 端口
},
};
maven 打包时,执行前端打包命令,完成前后台内容统一打包:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>exec-npm-install</id>
<phase>prepare-package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
<workingDirectory>./</workingDirectory>
</configuration>
</execution>
<execution>
<id>exec-npm-run-build</id>
<phase>prepare-package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
<workingDirectory>./</workingDirectory>
</configuration>
</execution>
</executions>
新旧叠加产生的打包问题
使用了 webapp 目录,同时又有 vue 时,打包生成的 xxx.war 包部署到 Tomcat 后,直接访问应用,由于 web.xml 中指定了路径 ../index.html
,后台报错:
catalina.out 异常:
22-Nov-2020 07:36:52.993 严重 [http-nio-8080-exec-5]
org.apache.coyote.http11.Http11Processor.service 错误的处理请求
java.lang.IllegalArgumentException:
资源路径[/../index.html]已规范化为无效的[null]
首页静态文件检索路径如何
第一种,static/index.html
删掉 webapps 目录下的 index.html 和 web.xml 这两个文件后,重启应用,能正常访问到 static 目录下的 index.html 页面:
第二种,如果保留 webapp 下的 index.html 和 web.xml 文件后,SpringBoot 默认的 web.xml 配置文件失效。此时,修改自定义的 web.xml 修正路径为 index.html
去掉相对路径后,再次访问,能正常:
第三种, 编辑 web.xml 配置文件路径为 ./index.html
效果和 index.html 一样。这就会走 SpringBoot 默认的静态文件查找逻辑。
启示录
第一点,自定义的 web.xml 会覆盖掉 SpringBoot 的默认配置。
第二点,web.xml 中指定了相对路径 ./index.html
或 index.html
,相对查找顺序是先 /static
,再是 /
,所以都能成功查到首页。
第三点,web.xml 中只指定一个 welcome-file 文件 ../index.html
文件,访问报错,但是如果再随便加一行配置,就能走默认查找到 static 的文件。
通过各种配置测试,发现没有办法通过自定义的 web.xml 修改 SpringBoot 的应用的首页,这点也挺让笔者捉摸不透的!