导读:

    首先本人的小程序全程基本都是自己写的,后端的框架用了spring boots集成的mybatis plus。当然如果使用的是spring mvc框架也是基本的这个原理,这里讲解下如何使用封装特别好的框架达成成就一天一个小程序。


选用工具:

                                   数据库:mysql           

                                   java版本:jdk1.80

                                   微信开发工具:微信Web开发工具

                                   后端框架:spring boots + mybatis plus+maven(很好的一个管理资源包的工具)


   第一步:微信小程序的页面布局                

                                            

这里我做一个最最最简单的例子,现在我们有如上的表,我们思考一下:如果现在要注入信息,没有任何条件的情况下,我们现在只需要执行Insert into 表 value(值)即可。但是在mybatis plus框架中拥有很好的数据库管理集成,所以我们基本上是不需要进行数据库语句的编写的,只需要知道如何去使用这样查询即可。


微信小程序页面代码:

  <view class='main'>
      <view>

        <!--注册信息 -->
        <form  bindsubmit="bindinguser" bindreset="formReset">
        <view>
        <view class="adj">  </view>
        <text class="add_user">
            完善个人信息
        </text>
                  <input placeholder='请输入姓名' class="username" name="nickName" id="nickName"    style="margin-top:90px;">
          </input>


          <input placeholder='请输入性别' class="username"name="gender" id="gender" style="margin-top:145px;">
          </input>
          <input placeholder='请输入语言' class="username"name="language" id="language" style="margin-top:200px;">
          </input>
          <input placeholder='请输入城市' class="username" name="city" id="city" style="margin-top:255px;">
          </input>
          <input placeholder='请输入省份' class="username" name="province"id="province" style="margin-top:310px;">          </input>
           <input placeholder='请输入备注' class="remarks"name="remarks" id="remarks" style="margin-top:365px;">          </input>
  <view class="viw_button">
          <button form-type="submit" class="ad"style="margin-top:430px;" type="primary" bindtap='bindinguser'  >提交
          </button>
          </view>
        </view>
          </form>
      </view>
  </view>


/* pages/setting/setting.wxss */
page{
  background: #efefef;
}

.add_user{
  text-align: center;
  position: absolute;
  margin-left:34%;
  font-size: 20px;
  z-index: 15px;
}
.viw_button button{
  background-color: #39c9ff;
}
.username{
  position: absolute;
  width:86%;
  height:35px;
  margin-left:7%;
  border:none;
  border-radius:4px;
  border: 1px solid #efefef;
  font-size:15px;
}

.remarks{
    position: absolute;
  width:86%;
  height:35px;
  margin-left:7%;
  border:none;
  border-radius:4px;
  border: 1px solid #efefef;
  font-size:15px;
}

.ad{
position: absolute;
width:86%;
margin-left:7%;
color:white;
background-color:#1296db;
}

.adj{
  width:100%;
  height:542px;
  background-color:white;
  position: absolute;
  margin-top: 13px;
    z-index: 0px;
}

第二步:前端请求后端的js

在这里请求后端采用的是ajax的json数据传输方式,这样局部请求的信息相对于准确和容易去维护和修改。

// pages/setting/setting.js
const app = getApp()
const WeValidator = require('we-validator')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: '',
    gender: '',
    language: '',
    city: '',
    province: '',
    remarks:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.userInfo);
    this.setData({
      userInfo: app.globalData.userInfo
    });
  },
  bindinguser: function (e) {
    if (app.globalData.userInfo) {
      let val = wx.getStorageSync("openId");
      let { value } = e.detail
     if (!this.validatorInstance.checkData(value)) return
      let info = e.detail.value
     // console.log(info.name)
      wx.request({
        url: app.globalData.host + '/updateUserinfo',
        data: {
          openId: val,
          nickName: e.detail.value.nickName,
          gender: e.detail.value.gender,
          language: e.detail.value.language,
          city: e.detail.value.city,
          province: e.detail.value.province,
          remarks: e.detail.value.remarks
        },
        success: function (res) {
          console.log(res.data)
          let code = res.data.code
          if (code == 0) {

            wx.showToast({
              title: '注册信息成功',
              icon: 'success',
              duration: 3000,
              mask: true
            })
            wx.navigateTo({
              url: '../newtask/newtask',
            })
            
          } else {
            wx.showToast({
              title: '注册信息失败',
              icon: 'error',
              duration: 1200,
              mask: true
            })
            wx.redirectTo({
              url: '../authorization/authorization'
            })
          }

        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        image: '../../images/error.png',
        duration: 1000,
        mask: true
      })
    }

  },

  initValidator() {
    this.validatorInstance = new WeValidator({
      rules: {
        nickName: {
          required: true
        },
        gender: {
          required: true,
        },
        language: {
          required: true
        },
        city: {
          required: true
        },
        province: {
          required: true
        },
        remarks: {
          required: true
        },
        
      },
      messages: {
        nickName: {
          required: '请输入姓名'
        },
        gender: {
          required: '请输入性别',
        },
        language: {
          required: '请输入语言'
        },
        city: {
          required: '请输入城市'
        },
        province: {
          required: '请输入省份'
        },
        remarks: {
          required: '请输入备注'
        }
      },
    })

  },
  onReady() {
    this.initValidator()
    //this.checkBinding()
  },
})

 


第三步:controller类的编写

           任何前端访问后端都需要有路径,这里的路径url实际上在mybatis plus框架中都是必然存在的,这个路径就是带有@RequestMapping的注解路径,现前端通过ajax方式请求后端,json数据传输都会打包发送到@RequestMapping的注解路径中,也就实现了所谓的前端数据流注入后端,后端进行数据接收后进行处理。现在我们后端需要编程的地方其实也相当的明确,就是在编写controller类时根据业务需求来即可。

 下面是controller类的简单代码。

package com.mbyte.easy.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mbyte.easy.admin.entity.TCproject;
import com.mbyte.easy.admin.entity.TProject;
import com.mbyte.easy.admin.entity.TUser;
import com.mbyte.easy.admin.service.ITCprojectService;
import com.mbyte.easy.admin.service.ITProjectService;
import com.mbyte.easy.admin.service.ITUnitpriceService;
import com.mbyte.easy.admin.service.ITUserService;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.rest.entity.WeChatAppLoginReq;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *     这是微信小程序的登录接口
 * </p>
 * @Author 
 * @Date 2019.4.24
 */
@Controller
@RequestMapping("/rest")
public class wxusercontroller extends BaseController {
    /**
     *用户自己修改用户信息
     * @param weixinUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/updateUserinfo"})
    public AjaxResult upUserinfo(@ModelAttribute TUser weixinUser) {
        //修改个人信息
        QueryWrapper<TUser> updateQueryWrapper = new QueryWrapper<TUser>();
        if (weixinUser.getOpenId() != null && !"".equals(weixinUser.getOpenId())) {
            updateQueryWrapper = updateQueryWrapper.eq("openId", weixinUser.getOpenId());
            boolean flag = itUserService.update(weixinUser, updateQueryWrapper);
            if (flag) {
        return success(weixinUser);
            //    return toAjax(itUserService.update(weixinUser, updateQueryWrapper));
            } else {
                error("更新失败");
            }
        }
        else{
            itUserService.save(weixinUser);
            return success(weixinUser);
        }
        return error("传参错误");
    }
}

这样我们就可以简单的实现微信小程序的前后端交互了。

Logo

更多推荐