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

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

创建Spring Boot项目

【微信小程序独立开发 5】后端搭建联调_第1张图片

【微信小程序独立开发 5】后端搭建联调_第2张图片

配置maven仓库

使用自己下载的maven版本

【微信小程序独立开发 5】后端搭建联调_第3张图片

添加pom文件

  
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.projectlombok
            lombok
            true
        
        
            mysql
            mysql-connector-java
            runtime
            5.1.47
        
        
        
            com.alibaba
            druid
            1.1.17
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.2.0
        


        
        
            org.apache.httpcomponents
            httpclient
            4.5.13
        
        
            com.alibaba
            fastjson
            1.2.79
        
        
        
        
        
            com.auth0
            java-jwt
            4.2.2
        


        
            io.jsonwebtoken
            jjwt
            0.7.0
        
        
            jdom
            jdom
            1.0
        
        
            dom4j
            dom4j
            1.1
        
        
            commons-io
            commons-io
            2.5
        
        
            junit
            junit
            test
        
        
            org.junit.jupiter
            junit-jupiter
            test
        

        
            org.springframework.boot
            spring-boot-starter-test
        
    

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

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

apply后刷新maven

【微信小程序独立开发 5】后端搭建联调_第4张图片

配置成功! 

【微信小程序独立开发 5】后端搭建联调_第5张图片

配置数据库

【微信小程序独立开发 5】后端搭建联调_第6张图片【微信小程序独立开发 5】后端搭建联调_第7张图片

连接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: 8080
  servlet:
    context-path: /
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/petRecord?serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis-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.StdOutImpl
  mapper-locations: classpath:mybatis/mapper/*.xml

创建项目目录结构

【微信小程序独立开发 5】后端搭建联调_第8张图片

创建返回工具类到entity中

package com.petrecord.petrecord.entity;

import java.util.HashMap;
import java.util.Map;

/**
 * 页面响应entity
 */
public class R extends HashMap {
    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 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 {

    @Autowired
    private 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 {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Override
    public 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





    
        
        
        
        
        
        
        
    

    
        insert into wx_user
        values (#{id},#{nickName},#{avatarUrl},#{birthday},#{sex},#{region},#{phoneNumber})
    


启动类加上注解扫描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请求工具

【微信小程序独立开发 5】后端搭建联调_第9张图片

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.value
    let 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.detail
    app.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



    
    
    
    

修改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() {

  }
})

完成效果:

【微信小程序独立开发 5】后端搭建联调_第10张图片【微信小程序独立开发 5】后端搭建联调_第11张图片【微信小程序独立开发 5】后端搭建联调_第12张图片

【微信小程序独立开发 5】后端搭建联调_第13张图片

你可能感兴趣的:(微信小程序,微信小程序,小程序)