午夜91福利视频,午夜成人在线观看,午夜在线视频免费观看,午夜福利短视频,精品午夜成人免费视频APP

小程序模板網

Spring Boot 整合微信小程序實現登錄與增刪改查

發布時(shi)間(jian):2020-05-13 10:04 所屬欄目:小程序開發教程

項目描述(shu):在(zai)微(wei)信小程序中(zhong)通過與Springboot操作數(shu)據庫實現簡(jian)單的增刪改查,其中(zhong)我是用(yong)springboot整合mybatis-plus 和mysql使(shi)用(yong)的

1. 開發前準備

1.1 前置知識

  • java基礎

  • SpringBoot簡單基礎知識

1.2 環境參數

  • 開發工(gong)具(ju):IDEA

  • 基礎環境:Maven+JDK8

  • 主(zhu)要(yao)技(ji)術:SpringBoot、lombok、mybatis-plus、mysql 、微信小程序

  • SpringBoot版本:2.2.6

2.開發者服務器

項目結構:

2.1 初始配置

(1)pom.xml配(pei)置

 <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>2.1.1</version>
        </dependency>

        <!--模板引(yin)擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- 引入(ru)阿里數據庫(ku)連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>

        <!-- mysql依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
            <scope>runtime</scope>
        </dependency>

        <!-- mybatisPlus 核心庫 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!--生成(cheng)實體成(cheng)get set-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- pagehelper 分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!--junit 測(ce)試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

(2)application.yml

# Spring Boot 的數(shu)據源配(pei)置
spring:
  datasource:
    name: wx
    url: jdbc:mysql://localhost:3306/wx_mini_program?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
 username: root
    password: root
    # 使(shi)用(yong)druid數據源(yuan)
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 maxOpenPreparedStatements: 20 # mybatis-plus相關配置
mybatis-plus:
  # xml掃描,多個目錄用逗號或(huo)者分號分隔(告(gao)訴 Mapper 所對應(ying)的 XML 文件位置)
  mapper-locations: classpath:mapper/*.xml
  # 以(yi)下(xia)配置(zhi)(zhi)均有默認(ren)值,可以(yi)不設置(zhi)(zhi)
  global-config:
    db-config:
      #主鍵類(lei)型(xing) AUTO:"數據(ju)庫ID自增(zeng)" INPUT:"用戶輸(shu)入(ru)ID",ID_WORKER:"全局唯(wei)一(yi)ID (數字類(lei)型(xing)唯(wei)一(yi)ID)", UUID:"全局唯(wei)一(yi)ID UUID";
      id-type: auto
      #字段策略(lve) IGNORED:"忽略(lve)判斷"  NOT_NULL:"非(fei) NULL 判斷")  NOT_EMPTY:"非(fei)空判斷"
      field-strategy: NOT_EMPTY
      #數據庫(ku)類(lei)型
      db-type: MYSQL

  # 指定實體類(lei)的包
  type-aliases-package: com.ckf.login_wx.entity
  configuration:
    # 是否(fou)開(kai)啟自動駝峰命名(ming)(ming)規(gui)則映射:從(cong)數(shu)據庫列(lie)名(ming)(ming)到Java屬性駝峰命名(ming)(ming)的類似映射
    map-underscore-to-camel-case: true
    # 如果(guo)查詢(xun)結(jie)果(guo)中(zhong)包含(han)空值的(de)列,則 MyBatis 在映射的(de)時(shi)候(hou),不(bu)會映射這(zhe)個(ge)字段(duan)
    call-setters-on-nulls: true
    # 這個配置(zhi)會將(jiang)執(zhi)行(xing)的sql打印出來,在開發或(huo)測試的時候可以用(yong)
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

# PageHelper分頁插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

2.2 小程序用戶表

CREATE table users(
 id int not null PRIMARY key auto_increment,
 name varchar(255) not null,
 age int not null );

insert into users value(null,'陳克(ke)鋒',18);
insert into users value(null,'陳克帥(shuai)',11);
insert into users value(null,'陳克兵',14); select * from users;

2.3 pojo

2.4 mapper

2.5 service

2.5 serviceImpl

配置SpringBoot掃(sao)描mapper

2.6 controller

LoginController

package com.ckf.login_wx.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map; /**
 * @author 安詳的苦丁茶
 * @date 2020/4/30 11:46 */ @RestController public class LoginController { /**
     * 登錄
     * @param phone
     * @param password
     * @return */ @PostMapping("/doLogin") public Map doLogin(String phone, String password){
        Map map = new HashMap(); if ((phone.equals("10086")&& password.equals("123456"))){
            map.put("code",200);
            map.put("result","登錄成功");
            System.out.println("登錄(lu)成(cheng)功(gong)");
        }else {
            map.put("result","no");
        } return map;
    }

}

UserController

package com.ckf.login_wx.controller;

import com.ckf.login_wx.entity.User;
import com.ckf.login_wx.servic.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
 * @author 安詳的苦丁茶
 * @date 2020/4/30 13:39 */ @RestController
@RequestMapping("/test") public class UserController {

    @Autowired private UserService userService; /**
     * 查詢全部
     * @return */ @GetMapping("/list") public Object list(){
        System.out.println("查詢成功"); return userService.list();
    } /**
     * 根據id刪除
     * @param id
     * @return */ @GetMapping("/delete") public boolean delete(Integer id){
        System.out.println("刪(shan)除成功"); return userService.removeById(id);
    } /**
     *  根據id查詢
      * @param id
     * @return */ @GetMapping("/byid") public Object byid(Integer id){
        System.out.println("查詢成(cheng)功"); return userService.getById(id);
    } /**
     *  修改
     * @param user
     * @return */ @PostMapping("/update") public boolean update(@RequestBody User user){
        System.out.println("修改(gai)成功(gong)"); return userService.updateById(user);
    } /**
     * 添加
     * @param user
     * @return */ @PostMapping("/add") public boolean add(@RequestBody User user){
        System.out.println("添加成功"); return userService.save(user);
    }

}

3. 微信小程序

項目結構(gou):

3.1 初始配置

3.2 bing.wxml

<!--pages/bind/bind.wxml-->
<view>

  <form bindsubmit='doLogin'>
            <!--賬號-->
            <view class="inputView">

                <label class="loginLabel">賬號</label>
                <input name="phone" value='10086' class="inputText" placeholder="請輸入賬號" />
            </view>
            <view class="line"></view>

            <!--密碼-->
            <view class="inputView">

                <label class="loginLabel">密碼</label>
                <input name="password" value='123456' class="inputText" password="true" placeholder="請(qing)輸入密碼" />
            </view>
            <view class="line"></view>
            <!--按鈕-->
            <view class='backColor'>
                <button class="loginBtn" formType="submit"  open-type='getUserInfo' >登錄</button>
            </view>

            <!-- <view>
                <button class="goRegistBtn" type="warn" open-type='getUserInfo' bindgetuserinfo='doLogin'>微信登錄</button>
            </view> -->
        </form>

</view>

3.3 bing.js

3.3 list.wxml

<!--pages/list/list.wxml-->
  <button class="add" type='primary' bindtap='addArea'>添加</button>
<view class="container">
  <view class='widget'>
    <text class='column'>編號</text>
    <text class='column'>姓名</text>
    <text class='column'>年齡</text>
    <text class='link-column'>操作</text>
  </view>
  <scroll-view scroll-y="true">
    <view>
      <block wx:for='{{list}}'>
      <view class='widget'> 
        <text class='column'>{{item.id}}</text>
        <text class='column'>{{item.name}}</text>
         <text class='column'>{{item.age}}</text>
        <view class='link-column'>
          <navigator class='link' url='../operation/operation?id={{item.id}}'>編輯</navigator> |
          <text class='link' bindtap='deleteArea' data-areaid='{{item.id}}' data-areaname='{{item.name}}' data-index='{{index}}'>刪除</text>  
        </view>
        </view>      
      </block>
    </view>
  </scroll-view>

</view>

3.4 list.js

// pages/list/list.js
Page({ /**
   * 頁(ye)面的初始數據 */ data: {
    list:[]
  }, /**
   * 生(sheng)命周(zhou)期函(han)數--監(jian)聽頁面加載 */ onLoad: function (options) {

  }, /**
   * 生命周期函(han)數--監聽頁面初(chu)次渲(xuan)染完成 */ onReady: function () {

  }, /**
   * 生(sheng)命周期函數--監(jian)聽頁面顯(xian)示 */ onShow: function () { var that=this;
    wx.request({
      url: '//localhost:8080/test/list',
      method:'GET',
      data:{},
      success:function(res){ var list=res.data; if(list==null){ var toastText='獲取數(shu)據失敗';
          wx.showToast({
            title: toastText,
            icon:'',
            duration:2000 //彈出時間(jian)
 })
        }else{
          that.setData({
            list:list
          })
        }
      }
    })
  }, /**
   * 生命(ming)周期函(han)數--監聽頁面隱藏(zang) */ onHide: function () {

  }, /**
   * 生命周(zhou)期函數--監(jian)聽(ting)頁面卸載(zai) */ onUnload: function () {

  }, /**
   * 頁面(mian)相關事件(jian)處(chu)理函數--監聽用戶下拉動(dong)作 */ onPullDownRefresh: function () {

  }, /**
   * 頁(ye)面上拉觸(chu)底事件的處理函數 */ onReachBottom: function () {

  }, /**
   * 用戶點擊右上角分享 */ onShareAppMessage: function () {

  },
  addArea:function(){
    wx.navigateTo({
      url:'../operation/operation' })
  },
  deleteArea: function (e) { var that=this;
    wx.showModal({
      title: '提示',
      content: '確定要刪除[' + e.target.dataset.areaname +']嗎?',
      success:function(sm){ if(sm.confirm){
          wx.request({
            url: '//localhost:8080/test/delete',
            data: { id: e.target.dataset.areaid},
            method:'GET',
            success:function(res){ var result=res.statusCode; var toastText="刪(shan)除成(cheng)功(gong)"; if(result!=200){
                toastText = "刪除失敗(bai)";
              }else{
                that.data.list.splice(e.target.dataset.index,1);
                that.setData({
                  list:that.data.list
                });
              }
              wx.showToast({
                title: toastText,
                icon:'',
                duration:2000 });
            }
          })
        }
      }
    })

  }
})

3.5 app.json

{ "pages": [ "pages/bind/bind", "pages/list/list", "pages/logs/logs", "pages/operation/operation", "pages/index/index" ], "window": { "backgroundColor": "#F6F6F6", "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#29d", "navigationBarTitleText": "login", "navigationBarTextStyle": "black" }, "sitemapLocation": "sitemap.json", "style": "v2" }

4. 測試

啟動開發者服務器,啟動SpringBoot的main方法(fa)。

打開微信小程序開發者工具

登錄(lu)頁(ye)面

首頁

添加頁面

修改頁面

刪除

到處基本的增刪(shan)改查操(cao)作已經完成了

如有需要前往(wang) Gitee(碼云)下(xia)載

 前臺://gitee.com/ckfeng/applet_of_wechat.git

后臺(tai)://gitee.com/ckfeng/wx_login.git



易優小程序(xu)(企(qi)業版)+靈活(huo)api+前后代(dai)碼開源(yuan) 碼(ma)云倉庫(ku):
本文地址://www.jinyoudianli.com/wxmini/doc/course/25132.html 復制鏈接 如需(xu)定制請聯系易(yi)優(you)客服(fu)咨詢:

工作日 8:30-12:00 14:30-18:00
周(zhou)六及部分節(jie)假日提供值(zhi)班服務

易(yi)小(xiao)優
轉人工 ×