springboot微信小程序项目(手把手教你SpringBoot整合微信小程序实现登录与增删改查)
springboot微信小程序项目(手把手教你SpringBoot整合微信小程序实现登录与增删改查)<!--pages/bind/bind.wxml--> <view> <formbindsubmit='doLogin'> <!--账号--> <viewclass="inputView"> <labelclass="loginLabel">账号</label> <inputname="phone"value='10086'class="inputText"placeholder="请输入账号"/> </view> <viewclass="line"></view> <!--密码--> <viewclass=&
> 本文一把大部分源码罗列出来了,收录至我的GitHub精选文章,欢迎Star: https://github.com/Java-Ling/Java-Interview-guide
项目描述:在微信小程序中通过与Springboot操作数据库实现简单的增删改查,其中我是用springboot整合mybatis-plus 和mysql使用的
1. 开发前准备1.1 前置知识
- Java基础
- SpringBoot简单基础知识
1.2 环境参数
- 开发工具:IDEA
- 基础环境:Maven JDK8
- 主要技术:SpringBoot、lombok、mybatis-plus、mysql 、微信小程序
- SpringBoot版本:2.2.6
项目结构:
2.1 初始配置
(1)pom.xml配置
<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>
<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--引入阿里数据库连接池-->
<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>
<!--生成实体成getset-->
<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测试-->
<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
#SpringBoot的数据源配置
spring:
datasource:
name:wx
url:jdbc:mysql://localhost:3306/wx_mini_program?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT+8
username:root
password:root
#使用druid数据源
type:com.alibaba.druid.pool.DruidDataSource
driver-class-name:com.mysql.jdbc.Driver
filters:stat
maxActive:20initialSize:1maxWait:60000minIdle:1timeBetweenEvictionRunsMillis:60000minEvictableIdleTimeMillis:300000validationQuery:select'x'testWhileIdle:truetestOnBorrow:falsetestOnReturn:falsepoolPreparedStatements:truemaxPoolPreparedStatementPerConnectionSize:20maxOpenPreparedStatements:20#mybatis-plus相关配置
mybatis-plus:
#xml扫描,多个目录用逗号或者分号分隔(告诉Mapper所对应的XML文件位置)
mapper-locations:classpath:mapper/*.xml
#以下配置均有默认值 可以不设置
global-config:
db-config:
#主键类型AUTO:"数据库ID自增"INPUT:"用户输入ID" ID_WORKER:"全局唯一ID(数字类型唯一ID)" UUID:"全局唯一IDUUID";
id-type:auto
#字段策略IGNORED:"忽略判断"NOT_NULL:"非NULL判断")NOT_EMPTY:"非空判断"
field-strategy:NOT_EMPTY
#数据库类型
db-type:MYSQL
#指定实体类的包
type-aliases-package:com.ckf.login_wx.entity
configuration:
#是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case:true
#如果查询结果中包含空值的列,则MyBatis在映射的时候,不会映射这个字段
call-setters-on-nulls:true
#这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl:org.apache.ibatis.logging.stdout.StdOutImpl
#PageHelper分页插件
pagehelper:
helperDialect:mysql
reasonable:true
supportMethodsArguments:true
params:count=countSql
2.2 小程序用户表
CREATEtableusers(
idintnotnullPRIMARYkeyauto_increment
namevarchar(255)notnull
ageintnotnull);
insertintousersvalue(null '陈克锋' 18);
insertintousersvalue(null '陈克帅' 11);
insertintousersvalue(null '陈克兵' 14);select*fromusers;
2.3 pojo
2.4 mapper
2.5 service
2.5 serviceImpl
配置SpringBoot扫描mapper
2.6 controller
LoginController
packagecom.ckf.login_wx.controller;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RestController;
importjava.util.HashMap;
importjava.util.Map;/**
*@author安详的苦丁茶
*@date2020/4/3011:46*/@RestControllerpublicclassLoginController{/**
*登录
*@paramphone
*@parampassword
*@return*/@PostMapping("/doLogin")publicMapdoLogin(Stringphone Stringpassword){
Mapmap=newHashMap();if((phone.equals("10086")&&password.equals("123456"))){
map.put("code" 200);
map.put("result" "登录成功");
System.out.println("登录成功");
}else{
map.put("result" "no");
}returnmap;
}
}
UserController
packagecom.ckf.login_wx.controller;
importcom.ckf.login_wx.entity.User;
importcom.ckf.login_wx.servic.UserService;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.*;/**
*@author安详的苦丁茶
*@date2020/4/3013:39*/@RestController
@RequestMapping("/test")publicclassUserController{
@AutowiredprivateUserServiceuserService;/**
*查询全部
*@return*/@GetMapping("/list")publicObjectlist(){
System.out.println("查询成功");returnuserService.list();
}/**
*根据id删除
*@paramid
*@return*/@GetMapping("/delete")publicbooleandelete(Integerid){
System.out.println("删除成功");returnuserService.removeById(id);
}/**
*根据id查询
*@paramid
*@return*/@GetMapping("/byid")publicObjectbyid(Integerid){
System.out.println("查询成功");returnuserService.getById(id);
}/**
*修改
*@paramuser
*@return*/@PostMapping("/update")publicbooleanupdate(@RequestBodyUseruser){
System.out.println("修改成功");returnuserService.updateById(user);
}/**
*添加
*@paramuser
*@return*/@PostMapping("/add")publicbooleanadd(@RequestBodyUseruser){
System.out.println("添加成功");returnuserService.save(user);
}
}
3. 微信小程序
项目结构:
3.1 初始配置
3.2 bing.wxml
<!--pages/bind/bind.wxml-->
<view>
<formbindsubmit='doLogin'>
<!--账号-->
<viewclass="inputView">
<labelclass="loginLabel">账号</label>
<inputname="phone"value='10086'class="inputText"placeholder="请输入账号"/>
</view>
<viewclass="line"></view>
<!--密码-->
<viewclass="inputView">
<labelclass="loginLabel">密码</label>
<inputname="password"value='123456'class="inputText"password="true"placeholder="请输入密码"/>
</view>
<viewclass="line"></view>
<!--按钮-->
<viewclass='backColor'>
<buttonclass="loginBtn"formType="submit"open-type='getUserInfo'>登录</button>
</view>
<!--<view>
<buttonclass="goRegistBtn"type="warn"open-type='getUserInfo'bindgetuserinfo='doLogin'>微信登录</button>
</view>-->
</form>
</view>
3.3 bing.js
3.3 list.wxml
<!--pages/list/list.wxml-->
<buttonclass="add"type='primary'bindtap='addArea'>添加</button>
<viewclass="container">
<viewclass='widget'>
<textclass='column'>编号</text>
<textclass='column'>姓名</text>
<textclass='column'>年龄</text>
<textclass='link-column'>操作</text>
</view>
<scroll-viewscroll-y="true">
<view>
<blockwx:for='{{list}}'>
<viewclass='widget'>
<textclass='column'>{{item.id}}</text>
<textclass='column'>{{item.name}}</text>
<textclass='column'>{{item.age}}</text>
<viewclass='link-column'>
<navigatorclass='link'url='../operation/operation?id={{item.id}}'>编辑</navigator>|
<textclass='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({/**
*页面的初始数据*/data:{
list:[]
} /**
*生命周期函数--监听页面加载*/onLoad:function(options){
} /**
*生命周期函数--监听页面初次渲染完成*/onReady:function(){
} /**
*生命周期函数--监听页面显示*/onShow:function(){varthat=this;
wx.request({
url:'http://localhost:8080/test/list'
method:'GET'
data:{}
success:function(res){varlist=res.data;if(list==null){vartoastText='获取数据失败';
wx.showToast({
title:toastText
icon:''
duration:2000//弹出时间
})
}else{
that.setData({
list:list
})
}
}
})
} /**
*生命周期函数--监听页面隐藏*/onHide:function(){
} /**
*生命周期函数--监听页面卸载*/onUnload:function(){
} /**
*页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh:function(){
} /**
*页面上拉触底事件的处理函数*/onReachBottom:function(){
} /**
*用户点击右上角分享*/onShareAppMessage:function(){
}
addArea:function(){
wx.navigateTo({
url:'../operation/operation'})
}
deleteArea:function(e){varthat=this;
wx.showModal({
title:'提示'
content:'确定要删除[' e.target.dataset.areaname ']吗?'
success:function(sm){if(sm.confirm){
wx.request({
url:'http://localhost:8080/test/delete'
data:{id:e.target.dataset.areaid}
method:'GET'
success:function(res){varresult=res.statusCode;vartoastText="删除成功";if(result!=200){
toastText="删除失败";
}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方法。
打开微信小程序开发者工具
登录页面
首页
添加页面
修改页面
删除
到处基本的增删改查操作已经完成了。