由于springboot2.x中弃用了EmbeddedServletContainerCustomizer,在springboot2.x中使用的是WebServerFactoryCustomizer,
对于vue项目,有两种路由模式:hash,history,查看路由中的mode属性,若不是history,请忽略本博客。
hash模式中,访问地址栏会有#的出现,而history没有#,会更美观一些。在history模式中,项目打包后不能直接打开index.html,需要使用nginx或者集成在后端代码中,nginx请参考另一篇博客,当集成在springboot中,会有刷新或访问网址出现404报错,以下代码是解决方法。
vue中路由设置
const router = new VueRouter({
mode: 'history',
routes
})
springboot中 *****Application.java代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
@SpringBootApplication
public class MusicApplication {
public static void main(String[] args) {
SpringApplication.run(MusicApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> myWebServerFactoryCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
}
};
}
}