vue2+springboot开发日记-部署到阿里云esc公网ip+宝塔面板+域名解析

环境:vue2+springboot3.2.5+jdk17+vsCode+idea2023
腾讯云Mysql5.7+阿里云ESC(Linux)-Centos7+宝塔面板+postman测试

前端打包  npm run build
后端打包  maven的package包-jar包,详见下方pom依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.******</groupId>
    <artifactId>*****</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>******</name>
    <description>******</description>
    <properties>
        <java.version>17</java.version>
        <spring-ai.version>0.8.1</spring-ai.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.******.******.LrbApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>

    </build>
</project>

axios示例:

import axios from 'axios';
export default {
  name: 'App',
  data() {
    return {
      title: '',
      url: '',
      response: '',
      deleteTitle: '',
      deleteResponse: '',
      users:[]
    };
  },
 methods: {
    sendData() {
      const data = {
        title: this.title,
        url: this.url
      };

      //本地开发服务器地址
      axios.post('http://localhost:8080/api/data', data)
      //上传服务器改为此地址
      // axios.post('http://***/api/data', data)

        .then(response => {
          this.response = response.data;
          this.findAllUsers();
        })
        .catch(error => {
          console.error('Error sending request:', error);
          this.response = 'Failed to send request!';
        });
    },
    sendDelData() {
      const data = {
        title: this.deleteTitle
      };

      //本地开发服务器地址
      axios.post('http://localhost:8080/api/delete', data)
      //上传服务器改为此地址
      // axios.post('http://***/api/delete', data)
        .then(response => {
          this.deleteResponse = response.data;
          this.findAllUsers();
        })
        .catch(error => {
          console.error('Error deleting user:', error);
          this.deleteResponse = 'Failed to delete user!';
        });
    },
    findAllUsers() {
      //本地开发服务器地址
      //上传服务器改为此地址
      axios.get('http://localhost:8080/api/allUsers', {
      // axios.get('http:/***/api/allUsers', {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error('Error fetching users:', error);
      });
},

  //钩子函数,页面启动时自动调用
  },
  mounted(){
    this.findAllUsers();
  }
};

前端模块示例:

    <div class="container">
      <div class="section">
        <h1>All Users</h1>
        <div v-if="users.length > 0" class="user-list">
          <div v-for="(user, index) in users" :key="index" class="user-item">
            <span>{{ user.title }}</span>
            <!-- 使用 v-bind 动态绑定链接地址 -->
            <a :href="user.url" target="_blank">{{ user.url }}</a>
          </div>
        </div>
        <p v-else>No users found.</p>
    </div>
      <div class="module-container">
        <h1>Send POST Request</h1>
        <form @submit.prevent="sendData" class="form">
          <div class="form-group">
            <label for="title">Title:</label>
            <input type="text" id="title" v-model="title" class="input-field">
          </div>
          <div class="form-group">
            <label for="url">URL:</label>
            <input type="text" id="url" v-model="url" class="input-field">
          </div>
          <button type="submit" class="btn primary">Send POST Request</button>
        </form>
        <p v-if="response" class="response">{{ response }}</p>
      </div>

问题1:数据库连接有问题,控制台有类似com.mysql.cj.jdbc.Driver相关错误时

· 应选用适合版本的连接包,mysql5.7版本应为,使用合适的jdbc包

· else:版本为8以后的connector连接应该为com.mysql.cj.jdbc.Driver,旧版本没有中间的“cj”,所以如果是5.x版本的Mysql,就去掉其中的“cj”,如果新版本的mysql就要用有“cj”的(在apllication.properties里改)。注意:pom.xml中应该符合各版本的包

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version> <!-- 选择与你的环境兼容的版本 -->
        </dependency>
import org.springframework.jdbc.core.JdbcTemplate;
private final JdbcTemplate jdbcTemplate;

application.properties格式:

spring.application.name=*****
server.port=8080
spring.datasource.url=jdbc:mysql://***************/dbname?useSSL=false
spring.datasource.username=**********
spring.datasource.password=************
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 · 额外一点:如果控制台总是报错SSL***什么的,但所有操作都能正常进行,就在url后加上?useSSL=false,详见上方代码

问题2:打包上传后,服务器日志显示找不到Main启动类

· 在pom.xml导入打包工具,并在其中的<build>里指定Main启动类

<plugins>
     <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
        <mainClass>com.******.********.LrbApplication</mainClass>
        </configuration>
        <executions>
        <execution>
        <goals>
        <goal>repackage</goal>
        </goals>
        </execution>
        </executions>
        </plugin>
</plugins>

问题3:页面前后端联调时,数据出不来,F12显示"has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."错误,此为"跨域资源共享(CORS)"问题,要在Controller里面进行跨域处理。解决不了就复制错误信息问AI

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://*********.com"); // 允许指定来源
        config.addAllowedOrigin("http://localhost:8081"); // 允许指定来源

        config.addAllowedMethod("*"); // 允许所有请求方法
        config.addAllowedHeader("*"); // 允许所有请求头
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

问题4:页面前后端联调时数据出不来,F12显示" *** GET **........ "什么的问题,可能是后端没有对请求方法进行放行,可能只放行了其他如POST等请求方法,解决方法如问题3,允许所有请求方法

问题5:页面在PC端正常显示,在手机上有三分之一显示不出来

· 横置手机后页面正常。。。此为前端页面样式问题,重新设计前端页面即可

问题6:宝塔更新前端/后端的文件、jar包后,联调仍然是旧页面旧响应

· 重启前端/后端服务后正常

问题7:在宝塔面板中服务器启动弹出“启动成功”的提示,但是状态栏显示服务仍然是红色“未启动”状态

· 检查服务的jdk,宝塔自动提供的openjdk8可能用不了,要在宝塔里下载自己项目需要的jdk版本,重新选择后再次启动即可

49df30595f574e009b13bfc3022be6ab.png

更新次数( 1 ):2024/5/13 20:17

问题8:使用vue-router组件时才发现忘记在vue ui里勾选下载了,于是在终端中输入下载指令,但出现诸多错误,包括但不限于:下载完成但没有自动添加到package.json中、下载了但程序检测不到包、下载报错与vue版本冲突、识别不到vue-router包、链接框能正确跳转但页面不变、启动主页面时报错之类的许多bug,所以重新创建了两次vue项目并在vue ui里勾选vue-router、vue2版本、npm包管理工具等操作,重新处理代码后成功实现vue-router跳转。耗费1~2小时
然后重新编辑了页面和css样式、编写更多js逻辑,如跳转页面后隐藏跳转按钮等。优化了页面布局排版颜色背景等。将链接隐藏,把标题改为可点击跳转的形式。右上角加入登录按钮,具体功能为完善,后续加入登录账号密码验证,以进入管理员模式,对数据进行快速编辑,增删查改等。
将新的前端代码打包后发布,功能测试成功。

更新次数(2):2024/5/14 04:41

对登录操作进行后端处理:

public int loginCheck(String username, String password) {
            String sql = "SELECT * FROM administor WHERE username = ? AND password = ?";
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, username, password);
            return result.isEmpty() ? 0 : 1;
        }
    @CrossOrigin(origins = "http://localhost:8081")
    @PostMapping(value = "/api/checkLogin",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public int checkLogin(@RequestBody Admin adminData){
        //从接收到的登录请求信息中获取发来的账号密码
        String username = adminData.getUsername();
        String password = adminData.getPassword();
        int c = userService.loginCheck(username,password);
        return c;
    }

前端处理:增加login页面,供用户输入账号密码,匹配则跳转admin页面,可以对数据进行操作

 methods: {
      tryLogin() {
        const data = {
          username: this.username,
          password: this.password
        };
        axios.post('http://localhost:8080/api/checkLogin', data)
          .then(response => {
            if (response.data === 1) {
              this.isAuthenticated = 1;
              this.$router.push('/admin');
            } else {
              alert("没有匹配的管理员账号");
            }
          })
          .catch(error => {
            console.error('发送请求时出错:', error);
            this.response = '发送请求失败!';
          });
      }
    }

通过路由守卫防止用户在浏览器直接访问admin页面

更新次数(3):2024/5/14 20.36

通过requests尝试获取最新热点消息,通过目标网站地址、xpath等对关键信息进行提取

import requests
from lxml import etree
import mysql.connector
import traceback
from datetime import datetime, timedelta

# 连接到数据库
conn = mysql.connector.connect(
    host="************",
    port="******",
    user="*****",
    password="******",
    database="****"
)

# 创建游标对象
cursor = conn.cursor()

url = 'http://www.todayhot.cn/zixun/xinwen/'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}
# 发送请求并获取响应内容
rq = requests.get(url=url, headers=headers)
rq.encoding='gbk'
# print(rq.status_code)
data = etree.HTML(rq.text)
print('------')
titles = data.xpath('**************/a/text()')
links = data.xpath('***************/a/@href')

# 准备SQL语句
sql_insert = "INSERT INTO link1 (title, t_url, created_at) VALUES (%s, %s, %s)"
sql_delete = "DELETE FROM link1 WHERE created_at < %s"
try:
    # 获取当前时间
    now = datetime.now()
    
    # 执行SQL语句插入新数据
    for i in range(len(titles)):
        cursor.execute(sql_insert, (titles[i], links[i], now))
    
    # 提交事务
    conn.commit()
    print("数据成功写入数据库!")

except Exception as e:
    # 记录异常信息
    print("写入数据库时发生异常:", e)

    # 发生异常时回滚事务
    conn.rollback()

# 删除三天前的数据
try:
    three_days_ago = now - timedelta(days=3)
    cursor.execute(sql_delete, (three_days_ago,))
    conn.commit()
    print("删除了三天前的数据!")
except Exception as e:
    # 记录异常信息
    print("删除数据时发生异常:", e)
    traceback.print_exc()  # 打印异常堆栈信息
    conn.rollback()

finally:
    # 关闭游标和连接
    cursor.close()
    conn.close()

问题9:访问网站返回200成功信息,但是空内容
· 网站的反爬手段,换个网站吧

问题10:怎么让程序自动执行,即丢到服务器里自动运行的步骤
· 上传py文件到宝塔面包的文件中,然后在计划任务里选择Shell脚本,粘贴刚才的py文件路径,设置执行周期,添加任务后程序就会在云服务器自动运行

问题11:自动程序运行时执行日志报错,找不到包、找不到环境等
·
sudo yum install python3
pip3 install requests
pip3 install lxml
pip3 install mysql-connector-python
安装相关包和环境
问题12:执行日志报错/www/lrb/python/todayhot.py: line 1: import: command not found /www/lrb/python/todayhot.py: line 2: from: command not found /www/**/python/***.py: line 3: import: command not found /www/***/python/***.py: line 4: import: command not found /www/***/***/***.py: line 5: from: command not found /www/***/python/***.py: line 6: $'\r': command not found /www/lrb/python/todayhot.py: line 8: syntax error near unexpected token `(' /www/lrb/python/todayhot.py: line 8: `conn = mysql.connector.connect( '
· 这个错误提示表明系统无法识别 Python 脚本,并尝试将其作为 shell 脚本来执行。这通常是因为脚本文件的格式不正确导致的。尝试使用文本编辑器将脚本文件转换为使用 Unix 风格的换行符,或者  在你的脚本的第一行添加  #!/usr/bin/env python3  其中的路径为你在服务器中安装的python安装目录,可以通过命令 which python3 来查找正确的路径

问题13:继续报错Traceback (most recent call last): File "/www/***/python/***.py", line 5, in <module> import mysql.connector File "/usr/local/lib/python3.6/site-packages/mysql/connector/__init__.py", line 32, in <module> from .connection_cext import CMySQLConnection File "/usr/local/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 40, in <module> from .abstracts import MySQLConnectionAbstract File "/usr/local/lib/python3.6/site-packages/mysql/connector/abstracts.py", line 33 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined
· 表明你的 Python 环境不支持 Python 3.7 中的 Future Annotations 特性。
一种可能的替代方案是尝试在当前的 Python 环境中使用另一个 MySQL 连接器,比如 PyMySQL,它是一个纯 Python 实现的 MySQL 连接器,不会依赖于 C 扩展,因此不会出现 Future Annotations 的问题。
你可以通过以下命令安装 PyMySQL:pip3 install pymysql,然后在你的 Python 代码中将 mysql.connector 替换为 pymysql,并相应调整连接方式。
 

import requests
from lxml import etree
import pymysql
import traceback
from datetime import datetime, timedelta

# 连接到数据库
conn = pymysql.connect(
    host="**************",
    port=*******,
    user="**********",
    password="************",
    database="**********"
)

# 创建游标对象
cursor = conn.cursor()

url = '**********'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}
# 发送请求并获取响应内容
rq = requests.get(url=url, headers=headers)
rq.encoding='gbk'
# print(rq.status_code)
data = etree.HTML(rq.text)
print('------')
titles = data.xpath('**************/a/text()')
links = data.xpath('********************/a/@href')

# 准备SQL语句
sql_insert = "INSERT INTO link1 (title, t_url, created_at) VALUES (%s, %s, %s)"
sql_delete = "DELETE FROM link1 WHERE created_at < %s"
try:
    # 获取当前时间
    now = datetime.now()
    
    # 执行SQL语句插入新数据
    for i in range(len(titles)):
        cursor.execute(sql_insert, (titles[i], links[i], now))
    
    # 提交事务
    conn.commit()
    print("数据成功写入数据库!")

except Exception as e:
    # 记录异常信息
    print("写入数据库时发生异常:", e)

    # 发生异常时回滚事务
    conn.rollback()

# 删除三天前的数据
try:
    three_days_ago = now - timedelta(days=3)
    cursor.execute(sql_delete, (three_days_ago,))
    conn.commit()
    print("删除了三天前的数据!")
except Exception as e:
    # 记录异常信息
    print("删除数据时发生异常:", e)
    traceback.print_exc()  # 打印异常堆栈信息
    conn.rollback()

finally:
    # 关闭游标和连接
    cursor.close()
    conn.close()

这样你就无需更新 Python 版本,而是直接使用 PyMySQL 来连接 MySQL 数据库了

更新次数(4):2024/5/15 5:20

很抱歉,我无法提供具体的免费源码。但是,我可以为你提供一些指导来帮助你搭建基于Vue2、Element、Spring Boot、MyBatis-Plus和MySQL的商城系统。 首先,你可以按照以下步骤进行开发: 1. 设置前端项目:使用Vue CLI创建一个新的Vue项目并安装Element UI库,这将为你提供用户界面组件和样式。 2. 开发前端页面:根据商城的需求,设计和开发前端页面,包括商品列表、购物车、订单等功能。使用Element UI的组件和样式来构建用户友好的界面。 3. 创建后端项目:使用Spring Initializr创建一个新的Spring Boot项目,并添加必要的依赖,如Spring Web、MyBatis-Plus和MySQL驱动程序。 4. 配置数据库:在MySQL中创建一个数据库,并配置Spring Boot应用程序的数据库连接。使用MyBatis-Plus来简化数据库操作,包括数据表映射、CRUD操作等。 5. 开发后端接口:根据商城的需求,设计和开发后端接口,包括商品查询、购物车管理、订单处理等功能。使用Spring Boot的注解来定义RESTful API,并调用MyBatis-Plus进行数据库操作。 6. 前后端交互:通过HTTP请求将前端页面与后端接口连接起来。在Vue项目中使用Axios库来发送和接收数据,并处理响应结果。 7. 测试和部署:对商城系统进行测试,确保功能正常运行。使用适当的工具和平台,将前端和后端部署到生产环境中。 请注意,这只是一个大致的指导,具体的实现细节可能会因项目需求和个人偏好而有所不同。你需要根据自己的情况进行适当的调整和扩展。如果你在具体实现中遇到问题,可以随时向我提问,我会尽力帮助你。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值