Springboot+微信小程序

項目描述:在微信小程序中通過與Springboot操作數據庫實現登錄驗證,其中我是用springboot整合mybatis操作數據庫
微信小程序代碼:`
account.wxml

<form bindsubmit="formSumbit" bindreset="formRest"> 
<view>       
    <view class="text">員工簽到</view>
    <view class="input">
        <view class="text1">姓名:</view>
        <input class="input1" type='text' name="username" value="admin"/>
    </view>
     <view class="input">
          <view class="text1">密碼:</view>
          <input  class="input1" password="true" name="password" value="123456" />
    </view>
</view>

<view class="btn">
        <button class="btn1" size="mini" form-type="reset">清除</button>
        <button class="btn2" size="mini" form-type="submit" bindtap="onLoad">登錄</button>


</view>
</form>

account.js

Page({
  data: {
    username:'',
    password:'',

   
  },

 formSumbit:function (e) {
    console.log("點擊提交按鈕");
    this.setData({
      username: e.detail.value.username,
      password: e.detail.value.password

    })

  },
  onLoad: function (options) {
    console.log("******");
    var that = this;
    wx.request({
          url:'http://localhost:8080/login', //服務器地址

      menthod: "GET",   
      header: {
        'content-type': 'application/json'
      },
      data: {
        'username':that.data.username,
        'password': that.data.password
      },

    
      success:function (res) {
        console.log(".....回調函數....." +res.data );
        var resData=res.data;
        if(resData==true){
            wx:wx.showToast({
              title: '登錄成功',
              duration: 2000,
            })
        }else{
          wx:wx.showToast({
            title: '登錄失敗',
            duration: 2000,
          })
        }
      
      }  
    })
   
  },
  formRest: function () {
    console.log("點擊了重置")
  },
  onReady: function () {
    console.log("onReady")
  },
  onShow: function () {
    console.log("onShow")
  },
  onHide: function () {
    console.log("onHide")
  },
  onUnload: function () {
    console.log("onUnload")
  },
  onPullDownRefresh: function () {
    console.log("onPullDownRefresh")
  },
  onReachBottom: function () {
    console.log("onReachBottom")
  },
  onShareAppMessage: function () {
    console.log("onShareAppMessage")
  }

 
 
})

account.wxss



.text{
    width: 100%;
      height: 60rpx;    
    text-align: center;
    font-size: 40rpx;
    margin-top: 40rpx;
    font-weight: 600;
}
.input{
    width: 100%;
    height: 60rpx;
    font-size: 40rpx;
    margin-top: 40rpx;
    font-weight: 600;
}
.text1{
    width: 20%;
    float: left;
    margin-left: 30rpx;
}
.input1{
      width: 50%;
     height: 60rpx;
    border:1rpx solid #000;
}
.btn{
     width: 100%;
      height: 60rpx;    
    font-size: 50rpx;
    margin-top: 40rpx;
}


.btn1{  
    margin-left: 20%;
    float: left;
    color: white;
    background: cornflowerblue;

}


.btn2{  
    margin-left: 20%;
    color: white;
    background: cornflowerblue;

}

我使用eclipse安裝一個springboot的插件,也可以使用idea,都一樣,下面我以eclipse爲例
安裝插件這裏我就不寫了百度有很多教程,下面這個鏈接裏面也有
https://www.cnblogs.com/zjdxr-up/p/8617242.html

springboot代碼:
新建一個springboot項目file>new >Spring Starter Project
如果沒找到Spring Starter Project可以去Other中搜索
在這裏插入圖片描述
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo-1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo-1</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
		<druid.version>1.0.28</druid.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>

		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			 <version>1.3.0</version>  
		</dependency>
		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>

Demo1Application.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication
public class Demo1Application {

	public static void main(String[] args) {
		SpringApplication.run(Demo1Application.class, args);
	}

}

配置文件
application.properties

spring.datasource.url = jdbc:mysql://localhost:3306/ssm
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver

通過逆向工程生成mapper與mapper.xml和實體類

點擊提取逆向工程項目+sql文件 提取碼:9eze(自己新建一個數據庫然後在運行sql文件,我的數據名爲ssm,如果不知道怎麼去改逆向工程代碼,數據庫名就命名跟我一樣,就不用改了)
下面就是改數據庫名,msyql用戶名跟密碼的地方
在這裏插入圖片描述
下面我寫UserMapper.xml與UserMapper.java的原因是因爲我要通過用戶名查找用戶,這個方法逆向工程沒有自動生成,所以要自己加,下面我備註有註釋
UserMapper.java

package com.example.demo.dao;

import com.example.demo.pojo.User;
import com.example.demo.pojo.UserExample;
import com.example.demo.pojo.UserKey;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
/*import org.apache.ibatis.annotations.Param;*/

@Mapper
public interface UserMapper {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(UserKey key);

    int insert(User record);
    int insertSelective(User record);
    // 通過用戶名查找用戶。自己加的
    User selectUser(String username);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(int key);

    /*int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    int updateByExample(@Param("record") User record, @Param("example") UserExample example);
*/
    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <id column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, username, password
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.example.demo.pojo.UserExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="com.example.demo.pojo.UserKey" >
    select 
    <include refid="Base_Column_List" />
    from user
   	 where id = #{id,jdbcType=INTEGER}
     
  </select>
  
  
    <!-- 通過用戶名查找用戶。自己加的 -->
   <select id="selectUser" parameterType="com.example.demo.pojo.User" resultMap="BaseResultMap">
    select * from user where username=#{username}
  </select>
  
  
  <delete id="deleteByPrimaryKey" parameterType="com.example.demo.pojo.UserKey" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
      and username = #{username,jdbcType=VARCHAR}
  </delete>
  <delete id="deleteByExample" parameterType="com.example.demo.pojo.UserExample" >
    delete from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.example.demo.pojo.User" >
    insert into user (id, username, password
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.pojo.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.example.demo.pojo.UserExample" resultType="java.lang.Integer" >
    select count(*) from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update user
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.username != null" >
        username = #{record.username,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null" >
        password = #{record.password,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update user
    set id = #{record.id,jdbcType=INTEGER},
      username = #{record.username,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.pojo.User" >
    update user
    <set >
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
      and username = #{username,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.pojo.User" >
    update user
    set password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
      and username = #{username,jdbcType=VARCHAR}
  </update>
</mapper>

實體層就不用改了,直接用逆向工程生成的,我就省略不寫了

服務層:
UserService.java

package com.example.demo.service;

import com.example.demo.pojo.User;

public interface UserService {
	User selectUser(String username);
	User selectByPrimaryKey(int id);
}

UserServiceImpl.java

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.dao.UserMapper;
import com.example.demo.pojo.User;

@Service
public class UserServiceImpl implements UserService {

	@Autowired(required=false)
	private  UserMapper userMapper;
	
	@Override
	public User selectUser(String username) {
		System.out.println("-------");
		// TODO Auto-generated method stub
		
		//根據用戶名查找用戶信息
		return userMapper.selectUser(username);
	}

	@Override
	public User selectByPrimaryKey(int id) {
		// TODO Auto-generated method stub
		
		User user=userMapper.selectByPrimaryKey(1);
		return user;
	}

}

控制層:
UserController.java

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.pojo.User;
import com.example.demo.service.UserService;

@RestController
public class UserController {
	@Autowired
	private UserService userService;
	
	

	
	@RequestMapping("/login")
	   public  boolean login(String username, String password){
		System.out.println ( "微信小程序調用接口!!!用戶名:" + username + "密碼:" + password );
		User user=userService.selectUser(username);
		if(user!=null) {
			String password1=user.getPassword();
			if(password1.equals(password)) {
				System.out.println("登錄成功");
				return true;
			}else {
				System.out.println("密碼錯誤"); 
				return false;
			}
			
		}else {
			System.out.println("用戶名不存在");
			return false;
		}
	
		}	
	
	
	@RequestMapping("/selectById")
	public User selectById(int id) {
	
		System.out.println("*******");
		User user=userService.selectByPrimaryKey(id);
		
		return user;
	}
	

	
}

項目結構:
在這裏插入圖片描述
點擊運行Demo1Application.java文件
如下圖:
在這裏插入圖片描述
然後到微信開發者工具account.wxml中點擊登錄
微信開發者工具控制檯:
在這裏插入圖片描述
eclipse控制檯:
在這裏插入圖片描述
到此項目能運行成功
如果有問題歡迎評論,我看到會第一時間回覆
如果幫助到了你,請幫忙點一下贊,謝謝支持

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章