使用SpringBoot服务部署Vue

3,454 阅读3分钟

SpringBoot + Vue前后端合并部署

将Vue项目整合到SpringBoot项目中,使用SpringBoot服务带动前端的资源访问,也可以直接用jar包的方式进行整合部署

前端Vue配置

  1. 配置默认路由方式,使用hash模式,建议不要使用history

    使用history会出现前端能够路由到的地址,无法使用连接直接访问(但是也可以自行进行访问资源控制)

    export default new Router({
      // mode: 'history', // 去掉url中的#
      mode: 'hash', // 使用hash值作为路由
      // ...
    })
    
  2. 配置在npm run buildyarn build时,在vue.config.js文件中指定输出后打包后文件路径,默认为dist,下面前端打包好的文件都以dist名代替

    如果不改动vue.config.js文件,后续需要将dist就手动复制到SpringBoot项目资源文件里

    正式环境可以直接配置到SpringBoot项目中,编写Shell脚本,进行自动化打包部署

    ==注意==:如果指定前端生成文件目录,不是覆盖,是删除文件夹后,再创建,如果填写的目录存在文件,会被删除

    module.exports = {
      // ......
      // 在npm run build 或 yarn build 时 ,生成文件的目录
      outputDir: '/data/xxxx/src/main/resources/static',
      // ......
      },
    
  3. 使用npm run build命令进行打包,打包好的前端默认在dist文件里面

image-20220804100558841.png

image-20220804091851318.png

  1. 打包后的资源文件,如果需要自定义修改请求前缀(比如需要自定义接口请求地址),可添加config.js文件在public目录下

    • 默认build会将环境配置文件的接口请求前缀直接打包,后续无法修改,如果想修改,直接修改环境配置文件后重新打包

      .env.development.env.staging.....

    • public下的文件资源会原封不动的保留在打包后文件中

    window.global_config = {
      BASE_URL: 'http://192.168.1.254:8083',
    }
    

image-20220804105901463.png

  1. 【可选】如果添加了config.js配置文件,修改所有文件中的process.env.VUE_APP_BASE_API改为window.global_config.BASE_URL

    process.env.VUE_APP_BASE_API改为window.global_config.BASE_URL

    index.html添加<script type="text/javascript" src="./config.js"></script>

      <body>
        <div id="app">
    	    // ......
    	</div>
         // 引入 config.js
    	<script type="text/javascript" src="./config.js"></script>
      </body>
    

后端项目配置

  1. 将打包好的前端dist文件,放置到SpringBoot资源文件resources/static

    注意SpringBoot项目resources/static必须是static,如果想放在其它名称的文件下,请自行修改SpringBoot静态资源配置

image-20220804100853630.png

  1. 将前端Vue打包好的静态资源设置为可匿名访问

    以Spring Security为例,设置静态资源,可匿名访问

    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        // ......
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            // 只放展示了需要修改的地方代码
            httpSecurity
                    // ......
                    .antMatchers(
                            HttpMethod.GET,
                            "/",
                            "/*.html",
                            "/**/*.html",
                            "/**/*.css",
                            "/**/*.js",
                            "/profile/**",
                		   // 将vue打包好的资源文件,设置为可匿名访问
                            "/static/**",
                            "/html/**",
                            "/favicon.ico"
                    ).permitAll()
            // .....
        }
        // ......
    }
    
  2. 在WebMvcConfigurer配置中,配置请求路径映射请求 / 映射到 /static/index.html

    当前这个项目本身就有ResourcesConfig配置类,直接添加

    @Configuration
    public class ResourcesConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            /* 请求 / 映射到 /static/index.html */
            registry.addResourceHandler("/")
                    .addResourceLocations("classpath:/static/index.html");
        }
    }
    
  3. 定义错误404 500 错误视图的跳转页面

    请求报错的时候,可以正确的跳转错误页面

    Spring boot 默认的错误视图解析器可以查看 org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController

    @Configuration
    public class ResourcesConfig implements WebMvcConfigurer {
    
        private static final ModelAndView FORBIDDEN_VIEW = new ModelAndView("redirect:/#/403");
    
        private static final Map<HttpStatus.Series, String> SERIES_VIEWS;
        // ......
        static {
            Map<HttpStatus.Series, String> views = new EnumMap<>(HttpStatus.Series.class);
            views.put(HttpStatus.Series.CLIENT_ERROR, "/#/404");
            views.put(HttpStatus.Series.SERVER_ERROR, "/#/500");
            SERIES_VIEWS = Collections.unmodifiableMap(views);
        }
        // 只放展示了需要修改的地方代码
        /**
         * 自定义错误请求处理
         *
         * @return 错误视图
         */
        @Bean
        public ErrorViewResolver customErrorViewResolver() {
            return (request, status, model) -> {
                if (status.value() == HttpStatus.FORBIDDEN.value()) {
                    return FORBIDDEN_VIEW;
                }
                String view = SERIES_VIEWS.getOrDefault(status.series(), SERIES_VIEWS.get(HttpStatus.Series.SERVER_ERROR));
                return new ModelAndView("redirect:" + view);
            };
        }
        // ......
    }
    
  4. 将SpringBoot项目打包成jar包,使用java -jar启动项目,成功运行,撒花

image-20220804123143157.png