如果不在意浏览器访问链接时需要在后面添加#,则以hash模式打包放入SpringBoot项目中即可,具体可参考:https://blog.csdn.net/animalcoder/article/details/104900561
以下为vue以history模式打包到SpringBoot中的操作步骤:
一、前端配置
1. index.js路由配置
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Login",
component: () =>import(/* webpackChunkName: "about" */ "@/views/login/login.vue")
},
{
path: '/index',
name: 'Index',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '@/views/home/index.vue'),
redirect: { name: 'OrganExamine' },
children:[
{
path:"/organexamine",
name:"OrganExamine",
component:()=>import("@/views/organexamine/index.vue")
},{
path:"/lookpapers",
name:"LookPapers",
component:()=>import("@/views/lookpapers/index.vue")
},{
path:"/studentresult",
name:"StudentResult",
component:()=>import("@/views/studentresult/index.vue")
}
]
},
{
path: "/home",
name: "Home",
component: () =>import("@/views/home/home.vue"),
redirect: { name: 'WaitExamine' },
children:[
{
path:"/waitexamine",
name:"WaitExamine",
component:()=>import("@/views/waitexamine/index.vue")
},
{
path:"/studentpapers/:id",
name:"StudentPapers",
component:()=>import("@/views/waitexamine/studentpapers.vue")
}
]
}
];
const router = new VueRouter({
mode: "history",
base: "/whteach",
routes,
});
export default router;
2. vue.config.js配置
const path = require('path')
module.exports = {
publicPath: "/whteach", // 基本路径
outputDir: 'dist', // 输出文件目录
assetsDir: "static", //静态资源文件名称
lintOnSave:false,
// productionSourceMap: false, //去除打包后js的map文件
devServer: {
open: false,// 自动启动浏览器
host: 'localhost',
port: 8080,// 端口号
https: false,
hotOnly: false,// 热更新
overlay: {
// 当出现编译器错误或警告时,在浏览器中显示全屏覆盖层
warnings: true,
errors: true
}
},
configureWebpack: (config) => {
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
} // 别名配置
}
})
if (process.env.NODE_ENV === 'production') {// 为生产环境修改配置...
config.mode = 'production';
config["performance"] = {//打包文件大小配置
"maxEntrypointSize": 10000000,
"maxAssetSize": 30000000,
//只给出 js 文件的性能提示, 提供资源文件名的断言函数
// assetFilter: function(assetFilename) {
// return assetFilename.endsWith('.js') || assetFilename.endsWith('.css');
// }
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = '训练系统';
return args
})
},
// 第三方插件配置
pluginOptions: {}
}
重点来了,我和前端同事折腾了好几天,就是因为base、publicPath这两个值导致的,这两个值需要和SpringBoot中的项目别名一致,如下图所示
二、后端
1.将前端打包的dist文件,按下图所示放入SpringBoot项目中(static直接放入resources下,而index.html则放入一个新建的templates文件夹下)
2.在MVC中添加静态资源配置
@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
// Spring容器
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 静态资源配置
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
/**
* 创建viewResolver
*
* @return
*/
@Bean(name = "viewResolver")
public ViewResolver createViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// 设置Spring容器
viewResolver.setApplicationContext(applicationContext);
// 取消缓存
viewResolver.setCache(false);
// 设置解析的前缀
viewResolver.setPrefix("/WEB-INF/html/");
// 设置视图解析的后缀
viewResolver.setSuffix(".html");
return viewResolver;
}
}
3.配置index主页路由
@Controller
public class PageController {
/**
* 主页路由
*
* @return
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
private String index() {
return "index";
}
}
4.pom.xml中添加thymeleaf依赖
<!--thymeleaf 访问静态资源templates文件下所需配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
5.为避免SpringBoot项目本地运行时F5刷新页面404错误,在启动类中配置404错误跳转
@SpringBootApplication
public class WhteachApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(WhteachApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
}
6.为避免SpringBoot项目在服务器的Tomcat运行时F5刷新页面404错误,在WEB-INF添加web.xml配置
web.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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_3_1.xsd"
version="3.1" metadata-complete="true">
<!-- 参考链接:https://blog.csdn.net/g631521612/article/details/82835518 -->
<!-- Vue项目部署tomcat,刷新报错404解决办法 -->
<display-name>Router for Tomcat</display-name>
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
</web-app>