程序员的资源宝库

网站首页 > gitee 正文

SpringBoot Vue nginx项目部署(零基础带你部署)

sanyeah 2024-04-01 11:12:32 gitee 22 ℃ 0 评论

一、环境、工具

jdk1.8

maven

spring-boot

idea

VSVode

vue

百度网盘(vue+springboot+nginx源码):

链接:https://pan.baidu.com/s/1m3ciEUmUsjqoQBnIJBR7Zw
提取码:6gi9 

二、搭建后台spring-boot框架

步骤:

1、new- project选择Spring Initializr  next

2、创建项目文件结构以及jdk版本

3、选择项目需要的依赖

next然后finish

4、创建完毕的文件结构如图

5、对pom.xml更改,信息如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.zks</groupId>
    <artifactId>myspringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>myspringboot</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
 
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
                <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>
    </dependencies>
 
        <build>
        <resources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
 
</project>
pom.xml

注意:本项目用是连接oracle,使用其他数据库的请自行使用数据库连接dependency

6、在resources文件夹下删除application.properties文件并添加新的application.yml文件,信息如下

server:
  port: 8080
spring:
  datasource:
#    url: jdbc:oracle:thin:@192.168.153.2:1521:orcl
    username: admin
    password: 123
    driver-class-name: oracle.jdbc.driver.OracleDriver
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp
mybatis:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    mapUnderscoreToCamelCase: true
    logImpl: org.apache.ibatis.logging.stdout.StdOutImpl

7、更改项目启动类(DemoApplication)

package com.zks.myspringboot;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("com.zks.dao")
public class MyspringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyspringbootApplication.class, args);
    }
 
}

右键运行启动类(DemoApplication),就可以成功启动

 

注意:可能会遇到一个问题:Unable to import maven project: See logs for details

maven版本过高3.6.2及以上可能也会出现该情况,就要降低版本了,我将3.6.3 -> 3.6.1版本重新编译,成功!

3.6.1下载:

链接:https://pan.baidu.com/s/1Q9yN-mS8TVZEn7y41IOsXw
提取码:l2fz

 

项目结构请模仿此图

为了证明成功启动springboot,我们在controller写个main类,return一个页面,然后浏览器看看

package com.example.jzcx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping(value = "/a/")
@Controller
public class Main {

    @RequestMapping(value = "index")
    public String main(){
        return "index";
    }
}

因为我们在application.yml文件设端口为8080,浏览器访问:localhost:8080/a/index,即可看到页面

到这里后端springboot就写完了!

三:前端vue搭建

1. 打开cmd:npm init webpack jzc

搭建起来的项目结构如图:

 

2. vue中axios跨域请求后端接口

一,首先在文件中下载axios

cnpm install axios --save-dev

二、在main.js中引入及获取对象

 import Vue from 'vue'

import Axios from 'axios'

Vue.prototype.$axios = Axios 

三、在config里面的index.js文件里设置proxyTable

const path = require('path')
 
module.exports = {
  dev: {
 
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/': {
        target: 'http://localhost:8080',//此处可以换成自己需要的地址
        changeOrigin: true,
        pathRewrite: {
          '^/': ''
        }
     }
    },

此处的8080对应application.yml文件中的

 四、main.js里添加host

 Vue.prototype.HOST = "/" 

五、数据请求

        
import qs from 'qs';

this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({ page:1, limit:2 })).then(res =>{ // console.log(res.data); this.totalNum = res.data.count; this.dataList = res.data.dataList; this.redOrBlack = res.data.redOrBlack; loading.close(); })

如果不加上qs.stringify,axios默认请求会带上花括号,后端就拿不到前端传过来的参数,使用qs库去掉花括号

qs使用:

 npm install qs --save-dev 

 import qs from 'qs'; 

注意:配置文件后,要重新启动哦!!!

到这里就可以使用axios

 3. vue中使用jquery库

 一、npm install jquery --save-dev 

还要在引入popper.js,不然jq引入报错,两者有一定的关联

 二、npm install popper.js --save-dev 还是 npm install popper --save-dev 

都试一下

三、配置main.js,引入所需组件

 import $ from 'jquery' 

 

 在webpack.base.conf.js最上面引入

 const webpack = require('webpack') 

 

结果配置好了,npm run dev,webpack报错引入jQ时发生“'$' is defined but never used”

 

 解决:注释掉webpack.base.conf.js里的这段:

 

 重新 npm run dev即可运行,这样jquery也可以使用了 

4.使用scss预编译

一、首先安装依赖

 npm install node-sass sass-loader --save-dev 

其中的sass-loader我安装的时候是8.0.0,但是安装完后报错,好像是说版本太高,和其他不兼容,于是我就降低版本sass-loader:7.3.1、node-sass:4.13.0。

 

如果出现错误,可以尝试使用淘宝镜像安装解决:

 npm install -g cnpm --registry=https://registry.npm.taobao.org (安装淘宝镜像) 

然后使用cnpm 代替npm 安装node-sass和sass-loader。
安装好之后就可以在你的.vue文件中使用了:

二、找到buildwebpack.base.conf.js,在rules中添加scss规则

 { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } 

 在vue文件中使用

  <style lang='scss'> </style> 

 4.1 在vue项目全局中引入scss

 全局引用时需要安装sass-resources-loader

  npm install sass-resources-loader --save-dev 

 修改build中的utils.js

 简单就是修改scss、sass使用的方法,将原本的generateLoaders方法换成自定义的generateSassResourceLoader方法即可

 

 然后添加一个方法generateSassResourceLoader()

 generateSassResourceLoader代码如下:

  function generateSassResourceLoader() {
    var loaders = [
      cssLoader,
      'sass-loader',
      {
        loader: 'sass-resources-loader',
        options: {
          // 多个文件时用数组的形式传入,单个文件时可以直接使用 path.resolve(__dirname, '../static/style/common.scss'
          resources: [resolveResource('theme.scss')]  
        }
      }
      ];
      if (options.extract) {
        return ExtractTextPlugin.extract({
          use: loaders,
          fallback: 'vue-style-loader'
          
        })
      } else {
        return ['vue-style-loader'].concat(loaders)
      }
    }

还要再修改样式的路径,如下:

 

 

然后在src下面新建style文件夹下再新建theme.scss即为全局scss文件

 

 到这里scss配置完成,还可以在vue文件引入我们theme.scss全局样式

5. 使用element-ui

因为要做分页,本来想使用layui的分页,但是好像vue要引入layui不能npm i的,vue对layui好像不是很支持,于是使用饿了么UI

安装: npm i element-ui --save-dev 

在main.js中引入

import ElementUI from 'element-ui' //element-ui的全部组件

import 'element-ui/lib/theme-chalk/index.css'//element-ui的css

Vue.use(ElementUI) //使用elementUI 

使用elementui的分页也很简单

<div class="block">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page.sync="currentPage"
                            :page-size="2"
                            layout="prev, pager, next"
                            :total="totalNum"
                            >
                        </el-pagination>
                    </div>

 

export default {
  name: 'RedOrBlack',
  data () {
    return {
        currentPage: 1,
        totalNum:1,
        dataList:[],
        fullscreenLoading: false
    }
  },
  created(){
      const loading = this.$loading({
          lock: true,
          text: '拼命加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({
              page:1,
              limit:2
          })).then(res =>{
            //   console.log(res.data);
              this.totalNum = res.data.count;
              this.dataList = res.data.dataList;
              this.redOrBlack = res.data.redOrBlack;
              loading.close();
          })

        $('.list-group').css('display','block');
        $('.content-table').css('display','none');
  },
  methods:{
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
// 点击上下页都会触发这个函数,所以在此函数写请求后端返回数据
        const loading = this.$loading({
          lock: true,
          text: '拼命加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$axios.post(this.HOST +'Jzcx/redOrBlack/second',qs.stringify({
            redOrBlack:this.redOrBlack,
            corpName:this.corpName,
            page:val-1,
            limit:2
        })).then(res =>{
            // console.log(res.data);
            this.totalNum = res.data.count;
            this.dataList = res.data.dataList;
            this.redOrBlack = res.data.redOrBlack;
            this.currentPage = val;
            loading.close();
        })
    }

建议直接观看官网,讲的很详细:https://element.eleme.cn/#/zh-CN/component/pagination

因为我要自定义饿了么的分页样式,于是有个坑要踩一下(饿了么的element-ui修改样式后不生效)

不能直接在组件中直接写饿了么样式,因为单组件有scoped,所以需要在app.vue中直接定义饿了么分页样式写,注意<style>不能加scope!

开发中在App.vue上写全局样式,饿了么分页可以修改,但我打包部署后,在app.vue上修改的样式(饿了么分页)无效,于是只能修改内部插件的样式,

在node_modules\element-ui\lib\theme-chalk\index.css下修改,其他文件修改了无效的,再次打包部署样式已发生变化。$message提示框修改也是在index.css下修改,同个道理

6. vue中引入echarts,柱形图没有显示数据(图已经出来了,就是没数据)

把this.drawBarChart(); 写在created生命周期中请求后端拿数据成功时加上,然后drawBarChar()方法就写在methords方法中,echarts要注意异步的问题,数据还没请求成功 图表已经初始化完了 所以图表渲染不了获取到的数据,也可以试一下把ajax和初始化图标都放在mounted里;也有一些情况是this的指向有问题,所以数据undefined。

最后发现我图已经出来了,但是没显示数据,是因为option.series.[0].data接收的是数组,而我却给他传个字符串,最后转为数组就正常显示了,大家传数据千万要看清楚接收的参数类型,不要像我一样,搞了很久才发现类型不对。

到这里我们的开发就开发完成了,现在进行项目的部署,使用nginx部署服务器

7. nginx

一、nginx下载:http://nginx.org/download/nginx-1.12.2.zip

二、vue项目打包,拷贝dist下的static和index.html到/usr/local/nginx/html目录下

三、打开/usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
        
         # 静态资源目录,即vue打包后的dist里的静态资源
        root  /usr/local/nginx/html;
        index  index.html index.htm;
        
        # 后端服务的配置
        
        location /Jzcx/ {
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                # 后端服务地址
                 proxy_pass http://localhost:8080;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }



}
nginx.conf

四、Java项目打包上传到 服务器,开启服务

因为springboot是基于manev,所以生成jar包

打开cmd,先进入后端项目目录,执行mvn clean先清除一下编译文件,再重新生成mvn package,在target文件夹下有个jar包

java -jar *****.jar --server.port=8080

后端服务成功开启

五、打开cmd,先进入nginx目录下,执行nginx.exe

注:执行nginx.exe可能会报错,unknown directive "锘? in F:\nginx/conf/nginx.conf:3,因为改nginx.conf这个文件配置的时候用记事本改的,于是记事本会自动在文件中添加BOM头,所以我们使用notepad++去除BOM头

 

 

这样就部署好了,前端用的是8081,在nginx下配置的

server {   listen       8081;}

后端在jar包那执行用的是8080,在nginx下也要请求后端的接口,要一一对应。

注:若想关闭nginx.exe,直接关闭cmd是关不掉的,需要再打开cmd窗口,进入nginx下执行nginx -s stop停止服务。

前端8081,后端8080,浏览器输入localhost:8081即可看到页面。

8. elementUI图标打包部署后404

结果启动项目之后发现饿了么的图标不显示,说404找不到这个资源,dev下正常,build图片显示不出来,

查看网络请求可以看到如下两个字体文件加载不到:

 http://localhost:59090/static/css/static/fonts/element-icons.535877f.woff

 http://localhost:59090/static/css/static/fonts/element-icons.732389d.ttf 

问题原因

查看 /build/webpack.base.conf.js 文件可以发现,woff 或 ttf 这些字体会经由 url-loader 处理后在 static/fonts 目录下生成相应的文件。

 也就是说实际应该通过 /static/fonts/** 路径来获取字体图标,而实际却是请求 /static/css/static/fonts/**,自然报 404 错误。

解决办法

打开 build/utils.js 文件,在如下位置添加 publicPath: '../../';

 

修改完毕后重新 build 发布,可以发现图标已经可以正常显示了。

到目前为止,访问localhost:8081/#/index即可看到页面

1)路由url上必须带上#号

2)刷新可以继续留在当前访问的页面

3)域名后面可以加路由

 

因为我的vue的路由是有个#号的,也就是router并不是history模式,所以只要设置模式为history模式就可以去除#

 

问题所在:但是你刷新子路由页面,你会发现报404?

分析:前端路由找不到,然后就跑去后端的接口请求,结果也是404,这个404是后端发送的,并非前端发送,

很简单你在浏览器没有加载js的时候直接输入这个带路由的url会被发送到服务器端,服务器又不认识这个路由,所以就出现404了。

一般的解决方案都是在服务器把找不到的路由指到index.html(vue页面)。这样在vue-router初始化好之后就会跳到相应的路由页面。

这个带来的问题就是404页面不会出现了,所以可能要在前端处理好404.

官方文档:https://router.vuejs.org/zh-cn/essentials/history-mode.html

所以刷新子路由报404,因为在nginx部署那里修改配置文件

nginx下增加try_files $uri $uri/ /index.html;

 location / {

    root html;

    index index.html index.htm;

    try_files $uri $uri/ /index.html;

}

# 静态资源目录,即vue打包后的dist里的静态资源

root /usr/local/nginx/html;

index index.html index.htm; 

重新运行nginx,现在在子路由刷新已不会报404错误。

现在修改后访问:localhost:8081

1)去除#号

2)刷新可以继续留在当前访问的页面

3)域名后面不可以加路由

 

 

能把springboot+vue+nginx部署上线,非常感谢以下文章作者

搭建spring-boot+vue前后端分离框架并实现登录功能:https://blog.csdn.net/zks_4826/article/details/81603865

vue中axios跨域请求解决:https://blog.csdn.net/srttina/article/details/83309512

webpack构建Vue项目引入jQ时发生“'$' is defined but never used”的处理:https://www.cnblogs.com/chig/p/10432210.html

在vue项目中使用scss:https://www.jianshu.com/p/0b604429b0d5

nginx安装及使用:https://www.cnblogs.com/jiangwangxiang/p/8481661.html、https://blog.csdn.net/qq_22027637/article/details/81777562

vue项目在linux中,springboot项目在本地,使用nginx部署:https://blog.csdn.net/weixin_40331613/article/details/81329277

启动nginx.ex错误:unknown directive "锘? in F:\nginx/conf/nginx.conf:3:https://www.cnblogs.com/jstarseven/p/4683679.html、解决方案(notepad++设置默认为UTF-8无BOM格式):https://jingyan.baidu.com/article/335530da87451819cb41c3da.html

Vue.js - 解决部署到服务器后Element UI图标不显示问题(404错误):https://www.hangge.com/blog/cache/detail_2473.html#

vue开发,在子路由里的时候刷新页面,页面就找不到了:https://segmentfault.com/q/1010000008771041/a-1020000008771211

vue 除去#符号,并部署后浏览器刷新不出现404错误处理:https://blog.csdn.net/laozhong110/article/details/80999429、https://blog.csdn.net/bocongbo/article/details/81670072

 

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表