Spring boot integrates wechat applet to realize login, addition, deletion, modification and query

Keywords: Java Spring MySQL Mybatis Database

Project Description: in the wechat applet, log in and verify with the spring boot operation database. I use spring boot to integrate the mybatis plus and mysql operation database

1. Preparation before development

1.1 prior knowledge

  • java Foundation
  • SpringBoot simple Basics

1.2 environmental parameters

  • Development tools: IDEA
  • Basic environment: Maven+JDK8
  • Technologies used: SpringBoot, lombok, mybatis plus, mysql, wechat applet
  • Spring boot version: 2.2.6

2. Developer server

Project structure:

 

2.1 initial configuration

(1) pom.xml configuration

 <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>

        <!--template engine-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- Import Alibaba database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>

        <!-- mysql rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
            <scope>runtime</scope>
        </dependency>

        <!-- mybatisPlus Core library -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>


        <!--Generate entity into get set-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- pagehelper Paging plug in -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!--junit test-->
        <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

# Data source configuration of Spring Boot
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
    # Using druid data sources
    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 Related configuration
mybatis-plus:
  # XML scanning, multiple directories separated by commas or semicolons (tell Mapper the corresponding XML file location)
  mapper-locations: classpath:mapper/*.xml
  # The following configurations have default values, which can not be set
  global-config:
    db-config:
      #Primary key type AUTO: "database ID AUTO increment" INPUT: "user INPUT ID", Id "worker:" globally unique ID (number type unique ID)", UUID:" globally unique ID UUID ";
      id-type: auto
      #Field policy IGNORED: "ignore judgment" not NULL: "non NULL judgment") not empty: "non NULL judgment"
      field-strategy: NOT_EMPTY
      #Database type
      db-type: MYSQL

  # Package specifying entity class
  type-aliases-package: com.ckf.login_wx.entity
  configuration:
    # Enable automatic hump naming rule mapping: similar mapping from database column name to Java attribute hump naming
    map-underscore-to-camel-case: true
    # If the query result contains a null value column, MyBatis will not map this field when mapping
    call-setters-on-nulls: true
    # This configuration will print out the executed sql, which can be used during development or test
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


# PageHelper paging plug-in
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

 

 

2.2 applet user table

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,'Chen Kefeng',18);
insert into users value(null,'Chen Keshuai',11);
insert into users value(null,'Chen kebing',14);

select * from users;

 

2.3 pojo

 

2.4 mapper

 

2.5 service

 

2.5 serviceImpl

 

Configure SpringBoot scan 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 Quiet Kuding tea
 * @date 2020/4/30 11:46
 */

@RestController
public class LoginController {

    /**
     * Sign in
     * @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","Login successful");
            System.out.println("Login successful");
        }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 Quiet Kuding tea
 * @date 2020/4/30 13:39
 */
@RestController
@RequestMapping("/test")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * Query all
     * @return
     */
    @GetMapping("/list")
    public Object list(){
        System.out.println("query was successful");
        return userService.list();
    }

    /**
     * Delete by id
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public boolean delete(Integer id){
        System.out.println("Delete succeeded");
        return userService.removeById(id);
    }

    /**
     *  Query by id
      * @param id
     * @return
     */
    @GetMapping("/byid")
    public Object byid(Integer id){
        System.out.println("query was successful");
        return userService.getById(id);
    }

    /**
     *  modify
     * @param user
     * @return
     */
    @PostMapping("/update")
    public boolean update(@RequestBody User user){
        System.out.println("Modification succeeded");
        return userService.updateById(user);
    }

    /**
     * Add to
     * @param user
     * @return
     */
    @PostMapping("/add")
    public boolean add(@RequestBody User user){
        System.out.println("Successfully added");
        return userService.save(user);
    }

}

 

 

3. Wechat applet

Project structure:

 

 

3.1 initial configuration

 

 

3.2 bing.wxml

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

  <form bindsubmit='doLogin'>
            <!--Account number-->
            <view class="inputView">
              
                <label class="loginLabel">Account number</label>
                <input name="phone" value='10086' class="inputText" placeholder="Please enter your account number" />
            </view>
            <view class="line"></view>

            <!--Password-->
            <view class="inputView">
                
                <label class="loginLabel">Password</label>
                <input name="password" value='123456' class="inputText" password="true" placeholder="Please input a password" />
            </view>
            <view class="line"></view>
            <!--Button-->
            <view class='backColor'>
                <button class="loginBtn" formType="submit"  open-type='getUserInfo' >Sign in</button>
            </view>

            <!-- <view>
                <button class="goRegistBtn" type="warn" open-type='getUserInfo' bindgetuserinfo='doLogin'>Wechat login</button>
            </view> -->
        </form>

</view>

 

3.3 bing.js

 

 

3.3 list.wxml

<!--pages/list/list.wxml-->
  <button class="add" type='primary' bindtap='addArea'>Add to</button>
<view class="container">
  <view class='widget'>
    <text class='column'>number</text>
    <text class='column'>Full name</text>
    <text class='column'>Age</text>
    <text class='link-column'>operation</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}}'>edit</navigator> |
          <text class='link' bindtap='deleteArea' data-areaid='{{item.id}}' data-areaname='{{item.name}}' data-index='{{index}}'>delete</text>  
        </view>
        </view>      
      </block>
    </view>
  </scroll-view>

</view>

 

3.4 list.js

// pages/list/list.js
Page({

  /**
   * Initial data of the page
   */
  data: {
    list:[]
  },

  /**
   * Life cycle function -- listening to page loading
   */
  onLoad: function (options) {
  
  },

  /**
   * Life cycle function -- listen to the completion of the first rendering of the page
   */
  onReady: function () {
  
  },

  /**
   * Life cycle function -- monitor page display
   */
  onShow: function () {
    var that=this;
    wx.request({
      url: 'http://localhost:8080/test/list',
      method:'GET',
      data:{},
      success:function(res){
        var list=res.data;
        if(list==null){
          var toastText='Failed to get data';
          wx.showToast({
            title: toastText,
            icon:'',
            duration:2000 //Pop up time
          })
        }else{
          that.setData({
            list:list
          })
        }
      }
    })
  },

  /**
   * Life cycle function -- monitor page hidden
   */
  onHide: function () {
  
  },

  /**
   * Life cycle function -- monitor page unloading
   */
  onUnload: function () {
  
  },

  /**
   * Page related event processing function -- listening to user pull-down action
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * Handling function of page pull bottom event
   */
  onReachBottom: function () {
  
  },

  /**
   * Users click the upper right corner to share
   */
  onShareAppMessage: function () {
  
  },
  addArea:function(){
    wx.navigateTo({
      url:'../operation/operation'
    })
  },
  deleteArea: function (e) {
    var that=this;
    wx.showModal({
      title: 'Tips',
      content: 'Are you sure you want to delete[' + e.target.dataset.areaname +']Do you?',
      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){

              var result=res.statusCode;
              var toastText="Delete succeeded";
              if(result!=200){
                toastText = "Delete failed";
              }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. Test

Start the developer server and start the main method of SpringBoot.

Open wechat applet developer tool

Login page

 

 

home page

 

 

 

 

Add page

 

 

Modify page

 

 

 

delete

 

The basic operations of adding, deleting, modifying and checking have been completed

Go to Gitee (code cloud) to download if necessary

Front desk: https://gitee.com/ckfeng/ckf_login.git

Background: https://gitee.com/ckfeng/login_wx.git

 

Posted by Ixplodestuff8 on Sat, 02 May 2020 02:21:48 -0700