【微信小程序独立开发 5】后端搭建联调

前言:上节我们完成了个人信息页的编写,本节完成将个人信息发给后端,并由后端存储

创建Spring Boot项目

配置maven仓库

使用自己下载的maven版本

添加pom文件

  <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope><version>5.1.47</version></dependency><!-- 连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.17</version></dependency><!-- mybatis-plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!-- 添加Httpclient支持 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency><!-- JWT --><!-- JWT --><!-- https://mvnrepository.com/artifact/com.auth0/java-jwt --><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.2.2</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency><dependency><groupId>jdom</groupId><artifactId>jdom</artifactId><version>1.0</version></dependency><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies>

注:如果依赖引入错误,可参照以下办法进行处理

Idea Maven 项目Dependency not found 问题 - 知乎

apply后刷新maven

配置成功! 

配置数据库

连接mysql数据库并新建数据库petRecord

创建表

CREATE TABLE `wx_user` (`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',`nick_name` varchar(20) DEFAULT NULL COMMENT '昵称',`avatar_url` varchar(50) DEFAULT NULL COMMENT '头像地址',`birthday` datetime DEFAULT NULL COMMENT '生日',`sex` varchar(10) DEFAULT NULL COMMENT '性别',`region` varchar(20) DEFAULT NULL COMMENT '地区',`phone_number` varchar(20) DEFAULT NULL COMMENT '电话号码',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

后端配置数据库连接

application.yaml

# 应用服务 WEB 访问端口
server:port: 8080servlet:context-path: /
spring:datasource:driver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceurl: jdbc:mysql://localhost:3306/petRecord?serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mybatis-plus:global-config:db-config:id-type: auto #id生成规则:数据库id自增configuration:map-underscore-to-camel-case: false # 开启驼峰功能auto-mapping-behavior: full # 自动映射任何复杂的结果log-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath:mybatis/mapper/*.xml

创建项目目录结构

创建返回工具类到entity中

package com.petrecord.petrecord.entity;import java.util.HashMap;
import java.util.Map;/*** 页面响应entity*/
public class R extends HashMap<String, Object> {private static final long serialVersionUID = 1L;public R() {put("code", 0);}public static R error() {return error(500, "未知异常,请联系管理员");}public static R error(String msg) {return error(500, msg);}public static R error(int code, String msg) {R r = new R();r.put("code", code);r.put("msg", msg);return r;}public static R ok(String msg) {R r = new R();r.put("msg", msg);return r;}public static R ok(Map<String, Object> map) {R r = new R();r.putAll(map);return r;}public static R ok() {return new R();}public R put(String key, Object value) {super.put(key, value);return this;}
}

创建用户实体类

package com.petrecord.petrecord.entity;import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;import java.util.Date;/*** 微信用户*/
@Getter
@Setter
public class WxUser {/** 主键 */private int id;/** 昵称 */private String nickName;/** 头像 */private String avatarUrl;/** 生日 */@DateTimeFormat(pattern="yyyy-MM-dd")private Date birthday;/** 性别 */private String sex;/** 地区 */private String region;/** 手机号 */private String phoneNumber;
}

创建视图层

package com.petrecord.petrecord.controller;import com.petrecord.petrecord.entity.R;
import com.petrecord.petrecord.entity.WxUser;
import com.petrecord.petrecord.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** 微信用户视图*/
@RestController
@RequestMapping("/wxUser")
public class WxUserController {@Autowiredprivate WxUserService wxUserService;/*** 保存用户* @param wxUser* @return*/@PostMapping("/save")public R save(@RequestBody WxUser wxUser){System.out.println(wxUser);return wxUserService.save(wxUser);}
}

创建Service

package com.petrecord.petrecord.service;import com.petrecord.petrecord.entity.R;
import com.petrecord.petrecord.entity.WxUser;/*** 微信用户Service*/
public interface WxUserService {/*** 保存用户* @param wxUser* @return*/R save(WxUser wxUser);
}

创建Service实现类

package com.petrecord.petrecord.service.impl;import com.petrecord.petrecord.entity.R;
import com.petrecord.petrecord.entity.WxUser;
import com.petrecord.petrecord.mapper.WxUserMapper;
import com.petrecord.petrecord.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class WxUserServiceImpl implements WxUserService {@Autowiredprivate WxUserMapper wxUserMapper;@Overridepublic R save(WxUser wxUser) {int count = wxUserMapper.save(wxUser);if(count <= 0){return R.error("保存失败");}return R.ok("保存成功");}
}

创建mapper接口

package com.petrecord.petrecord.mapper;import com.petrecord.petrecord.entity.WxUser;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface WxUserMapper {/*** 保存用户* @param wxUser* @return*/int save(WxUser wxUser);
}

创建mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.petrecord.petrecord.mapper.WxUserMapper"><resultMap id="wxUserResult" type="com.petrecord.petrecord.entity.WxUser"><id column="id" property="id"/><result column="nick_name" property="nickName"/><result column="avatar_url" property="avatarUrl"/><result column="birthday" property="birthday"/><result column="sex" property="sex"/><result column="region" property="region"/><result column="phone_number" property="phoneNumber"/></resultMap><insert id="save" keyProperty="id" useGeneratedKeys="true">insert into wx_uservalues (#{id},#{nickName},#{avatarUrl},#{birthday},#{sex},#{region},#{phoneNumber})</insert></mapper>

启动类加上注解扫描mapper接口

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

微信小程序前端修改

添加reques请求工具

const baseUrl = 'http://localhost:8080'export const getBaseUrl = ()=>{return baseUrl;
}// 后端request请求工具类
export const requestUtil = (params)=>{return new Promise((resolve,reject)=>{wx.request({...params,url: baseUrl + params.url,success: (res)=>{resolve(res)},fail: (err)=>{reject(err)}})});
}

修改userInfo.js

// pages/userInfo/userInfo.js
import {requestUtil,getBaseUrl} from '../../utils/requestUtil.js'const app = getApp()
Page({/*** 页面的初始数据*/data: {userInfo: {nickName: '',avatarUrl: '',userId: '',birthday: '',region: [],phoneNumber: '',sex: ''},date: '2000-09-01',dateStatus: false,sexStatus: false,regionStatus: false,array: ['男', '女', '未知'],region:  ['广东省', '广州市', '海珠区'],customItem: '全部',baseUrl: ''},/*** 生命周期函数--监听页面加载*/onLoad(options) {const baseUrl = getBaseUrl();let userInfo = wx.getStorageSync('userInfo') || ''if(userInfo === ''){this.setData({userInfo: {nickName: app.globalData.userInfo.nickName,avatarUrl: app.globalData.userInfo.avatarUrl,userId: app.globalData.userInfo.userId},baseUrl})}else{this.setData({userInfo})}},async saveUserInfo(){const res = await requestUtil({url: '/wxUser/save',method: 'POST',data: this.data.userInfo})if(res.data.code === 0){//修改全局变量中的用户信息,将其存入缓存中wx.setStorageSync('userInfo', this.data.userInfo)wx.switchTab({url: '/pages/Ta/Ta',})}else{wx.showToast({title: '保存失败,请重新输入',icon: 'none'})}},phoneNumberMethod(e){const data = e.detail.value;if(data.length == 0){wx.showToast({title: '请输入手机号',icon:'none'})}if(data.length != 11 || !/^1[3456789]\d{9}$/.test(data)){wx.showToast({title: '请输入正确的手机号',icon:'none'})}this.setData({userInfo: {phoneNumber: data,nickName: this.data.userInfo.nickName,avatarUrl: this.data.userInfo.avatarUrl,userId: this.data.userInfo.userId,birthday: this.data.userInfo.birthday,sex: this.data.userInfo.sex,region: this.data.userInfo.region}})},bindRegionChange: function (e) {let region = e.detail.valuelet regionStr = ""+region[0] +" " +region[1] +" "+ region[2]this.setData({userInfo: {region: regionStr,nickName: this.data.userInfo.nickName,avatarUrl: this.data.userInfo.avatarUrl,userId: this.data.userInfo.userId,phoneNumber: this.data.userInfo.phoneNumber,birthday: this.data.userInfo.birthday,sex: this.data.userInfo.sex},regionStatus: true})},bindSexChange(e){console.log(e.detail.value);this.setData({userInfo: {nickName: this.data.userInfo.nickName,avatarUrl: this.data.userInfo.avatarUrl,userId: this.data.userInfo.userId,region: this.data.userInfo.region,phoneNumber: this.data.userInfo.phoneNumber,birthday: this.data.userInfo.birthday,sex: this.data.array[e.detail.value]},sexStatus: true})},bindDateChange(e){console.log('picker发送选择改变,携带值为', e.detail.value)this.setData({userInfo: {nickName: this.data.userInfo.nickName,avatarUrl: this.data.userInfo.avatarUrl,userId: this.data.userInfo.userId,region: this.data.userInfo.region,phoneNumber: this.data.userInfo.phoneNumber,sex: this.data.userInfo.sex,birthday: e.detail.value,},dateStatus: true})},onChooseAvatar(e) {const { avatarUrl } = e.detailapp.globalData.userInfo.avatarUrl = avatarUrl this.setData({userInfo: {avatarUrl: avatarUrl,nickName: this.data.userInfo.nickName,userId: this.data.userInfo.userId,region: this.data.userInfo.region,birthday: this.data.userInfo.birthday,sex: this.data.userInfo.sex,phoneNumber: this.data.userInfo.phoneNumber,}})},/*** 生命周期函数--监听页面初次渲染完成*/onReady() {},/*** 生命周期函数--监听页面显示*/onShow() {},/*** 生命周期函数--监听页面隐藏*/onHide() {},/*** 生命周期函数--监听页面卸载*/onUnload() {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh() {},/*** 页面上拉触底事件的处理函数*/onReachBottom() {},/*** 用户点击右上角分享*/onShareAppMessage() {}
})

修改Ta.wxml

<!--pages/Ta/Ta.wxml-->
<view class="pet_wrapper"><!-- 用户信息 --><view class="user_info_wrapper"><view class="user_info"><image src="{{userInfo.avatarUrl}}" mode="widthFix" /><view class="user"><view class="user_id">ID:{{userInfo.userId}}</view><view class="user_name">{{userInfo.nickName}}</view></view><button class="edit_user_info" bind:tap="editUserInfo">编辑个人信息</button></view></view><!-- 功能栏 -->
</view>

修改Ta.js

// pages/Ta/Ta.js
const app = getApp()
Page({/*** 页面的初始数据*/data: {userInfo: {userId: '',nickName: '',avatarUrl: ''}},/*** 生命周期函数--监听页面加载*/onLoad(options) {let userInfo = wx.getStorageSync('userInfo') || ''console.log(userInfo);if(userInfo === ''){this.setData({userInfo: {nickName: app.globalData.userInfo.nickName,avatarUrl: app.globalData.userInfo.avatarUrl,userId: app.globalData.userInfo.userId}})}else{this.setData({userInfo})}},editUserInfo(){wx.navigateTo({url: '/pages/userInfo/userInfo',})},/*** 生命周期函数--监听页面初次渲染完成*/onReady() {},/*** 生命周期函数--监听页面显示*/onShow() {let userInfo = wx.getStorageSync('userInfo') || ''if(userInfo === ''){this.setData({userInfo: {nickName: app.globalData.userInfo.nickName,avatarUrl: app.globalData.userInfo.avatarUrl,userId: app.globalData.userInfo.userId}})}else{this.setData({userInfo})}},/*** 生命周期函数--监听页面隐藏*/onHide() {},/*** 生命周期函数--监听页面卸载*/onUnload() {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh() {},/*** 页面上拉触底事件的处理函数*/onReachBottom() {},/*** 用户点击右上角分享*/onShareAppMessage() {}
})

完成效果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/639669.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【服务器】Xshell与Xftp软件的使用指南

目录 【Xshell软件】 1.1 Xshell软件的功能 1.2 Xshell软件的使用 【Xftp软件】 2.1 Xftp软件的功能 2.2 Xftp软件的使用 可替代产品【FinalShell】 3.1 FinalShell软件的使用 3.2 FinalShell连接服务器失败解决方法 可替代产品【FileZilla】

Java网络编程——UDP通信原理

一、TCP和UDP概述 传输层通常以TCP和UDP协议来控制端点与端点的通信 TCPUDP协议名称传输控制协议用户数据包协议是否连接面向连接的协议。数据必须要建立连接无连接的协议&#xff0c;每个数据报中都给出完整的地址信息&#xff0c;因此不需要事先建立发送方和接受方的连接是…

Java面试题50道

文章目录 1.谈谈你对Spring的理解2.Spring的常用注解有哪些3.Spring中的bean线程安全吗4.Spring中的设计模式有哪些5.Spring事务传播行为有几种6.Spring是怎么解决循环依赖的7.SpringBoot自动配置原理8.SpringBoot配置文件类型以及加载顺序9.SpringCloud的常用组件有哪些10.说一…

toad 库中 iv 计算逻辑

merge 函数默认为决策树合并 决策树叶子结点默认值DEFAULT_BINS 10&#xff0c;可通过 n_bins 人为设置叶子结点数

Eureka整合seata分布式事务

文章目录 一、分布式事务存在的问题二、分布式事务理论三、认识SeataSeata分布式事务解决方案1、XA模式2、AT模式3、SAGA模式4.SAGA模式优缺点&#xff1a;5.四种模式对比 四、微服务整合Seata AT案例Seata配置微服务整合2.1、父工程项目创建引入依赖 2.2、Eureka集群搭建2.3、…

19万9的小米SU7已经彻底被否了

文 | AUTO芯球 作者 | 李诞 雷总 您是真不听劝啊 还要准备和米粉“干一架”啊 我和大家一样啊 这下好了 19万9的小米SU7已经彻底被否了 说实话 我心理真不是滋味 毕竟大家都说了&#xff0c; 9.9是雷爹&#xff0c;9万9是雷帝&#xff0c;15w是雷神 19万是雷总&#x…

Java开发工具:IntelliJ IDEA 2023 for Mac中文激活

IntelliJ IDEA 2023是一款由JetBrains开发的强大的集成开发环境&#xff08;IDE&#xff09;软件&#xff0c;适用于多个编程语言。它旨在提高开发人员的生产力和代码质量。 软件下载&#xff1a;Java开发工具&#xff1a;IntelliJ IDEA 2023 for Mac中文激活 IntelliJ IDEA 20…

[Java面试]JavaSE知识回顾

&#x1f384;欢迎来到边境矢梦的csdn博文&#x1f384; &#x1f384;本文主要梳理Java面试中JavaSE中会涉及到的知识点 &#x1f384; &#x1f308;我是边境矢梦&#xff0c;一个正在为秋招和算法竞赛做准备的学生&#x1f308; &#x1f386;喜欢的朋友可以关注一下&#x…

设计螺栓长度的基本原理和细节考虑——SunTorque智能扭矩系统

螺栓长度通常是指从螺栓头部到底部的整体长度。在选择或设计螺栓长度时&#xff0c;需要考虑多个因素&#xff0c;如被连接件的材料、厚度、螺栓间距以及预紧力等。设计螺栓长度应注意哪些原则和细节&#xff0c;SunTorque智能扭矩系统和大家一起来了解。设计螺栓长度的基本原则…

每日一题——LeetCode1304.和为零的N个不同整数

方法一 个人方法 n为偶数&#xff0c;只要同时放入一个数的正数和负数&#xff0c;那么和总为0&#xff0c;n是奇数就放入一个0&#xff0c;剩下的当偶数看待 var sumZero function(n) {let res[]if(n%2!0){res.push(0)n--}nn/2for(let i1;i<n;i){res.push(i)res.push(-i…

Sci Transl Med | 自体中和抗体在早期抗逆转录病毒治疗中增加

今天给同学们分享一篇实验文章“Autologous neutralizing antibodies increase with early antiretroviral therapy and shape HIV rebound after treatment interruption”&#xff0c;这篇文章发表在Sci Transl Med期刊上&#xff0c;影响因子为17.1。 结果解读&#xff1a; …

vue3自定义按钮点击变颜色实现(多选功能)

实现效果图&#xff1a; 默认选中第一个按钮&#xff0c;未选中按钮为粉色&#xff0c;点击时颜色变为红色 利用动态类名&#xff0c;当定义isChange数值和下标index相同时&#xff0c;赋予act类名&#xff0c;实现变色效果 <template><div class"page"&…

Elastic Search 8.12:让 Lucene 更快,让开发人员更快

作者&#xff1a;来自 Elastic Serena Chou, Aditya Tripathi Elastic Search 8.12 包含新的创新&#xff0c;可供开发人员直观地利用人工智能和机器学习模型&#xff0c;通过闪电般的快速性能和增强的相关性来提升搜索体验。 此版本的 Elastic 基于 Apache Lucene 9.9&#xf…

re:从0开始的HTML学习之路 2. HTML的标准结构说明

1. <DOCTYPE html> 文档声明&#xff0c;用于告诉浏览器&#xff0c;当前HTML文档采用的是什么版本。 必须写在当前HTML文档的首行&#xff08;可执行代码的首行&#xff09; HTML4的此标签与HTML5不同。 2. <html lang“en”> 根标签&#xff0c;整个HTML文档中…

如何本地部署虚VideoReTalking

环境&#xff1a; Win10专业版 VideoReTalking 问题描述&#xff1a; 如何本地部署虚VideoReTalking 解决方案&#xff1a; VideoReTalking是一个强大的开源AI对嘴型工具&#xff0c;它是我目前使用过的AI对嘴型工具中效果最好的一个&#xff01;它是由西安电子科技大学、…

数据结构学习1 初识泛型

装箱和拆箱 装箱/装包: 把一个基本数据类型转变为包装类型 拆箱/拆包: 把一个包装类型转变为一个基本数据类型 int a 1;Integer i a;// 自动装箱int b i;// 自动拆箱Integer ii Integer.valueOf(a);// 手动装箱&#xff0c;推荐使用 Integer.valueOf() 而不是 new Integer(…

本地读取Excel文件并进行数据压缩传递到服务器

在项目开发过程中&#xff0c;读取excel文件&#xff0c;可能存在几百或几百万条数据内容&#xff0c;那么对于大型文件来说&#xff0c;我们应该如何思考对于大型文件的读取操作以及性能的注意事项。 类库&#xff1a;Papa Parse - Powerful CSV Parser for JavaScript 第一步…

springboot116基于java的教学辅助平台

简介 【毕设源码推荐 javaweb 项目】基于springbootvue 的基于java的教学辅助平台 适用于计算机类毕业设计&#xff0c;课程设计参考与学习用途。仅供学习参考&#xff0c; 不得用于商业或者非法用途&#xff0c;否则&#xff0c;一切后果请用户自负。 看运行截图看 第五章 第四…

基于光口的以太网 udp 回环实验

文章目录 前言一、系统框架整体设计二、系统工程及 IP 创建三、UDP回环模块修改说明四、接口讲解五、顶层模块设计六、下载验证前言 本章实验我们通过网络调试助手发送数据给 FPGA,FPGA通过光口接收数据并将数据使用 UDP 协议发送给电脑。 提示:任何文章不要过度深思!万事万…

从白子画到东方青苍,你选择谁来守护你的修仙之旅?

从白子画到东方青苍,你选择谁来守护你的修仙之旅? 在繁花似锦的修仙世界中&#xff0c;每一位追梦者都渴望有那么一位守护者&#xff0c;与你共患难&#xff0c;共成长。热血与浪漫交织的《花千骨》与《苍兰诀》&#xff0c;给我们带来了两位风华绝代的守护者&#xff1a;白子…