1. 程式人生 > 其它 >微信小程式+SpringBoot實現使用者登入

微信小程式+SpringBoot實現使用者登入

技術標籤:學習邏輯互動mysqljava小程式spring boot

微信小程式+SpringBoot實現使用者登入

前言

微信小程式越來越吃香了(前話就這麼多,嘿嘿)

前端

那就開始吧,登入介面就如此了

在這裡插入圖片描述

wxml內容如下,這是格式化後貼上過來的,emmm,怪像那回事。

<view class="total">
  <form bindsubmit="create_login">
    <view class="t1">
      <text class="text"
>
賬號</text> <input type="text" name="moblie" class="box" placeholder="輸入您的賬號" value="{{moblie}}" bindinput="mobileInput"></input> </view> <view class="t2"> <text class="text"
>
密碼</text> <input type="password" name="password" class="box" placeholder="輸入您的密碼" value="{{password}}" bindinput="passwordInput"></input> </view> <button bindtap="login" class="btn"
>
<text class="font2">登陸</text> </button> </form> </view>

wxss是這樣的,本來是不想發wxss的,發出來感覺有點看不起在座的各位,可能捱打,不過我尋思著,隔著螢幕你們又弄不死我,嘎嘎嘎,搞錯了,桀桀桀

.total{
  width:100%;
  height:100%;
  background-color: rgb(245,245,245);
}
.t1{
  width:100%;
  height:125rpx;
  background-color: white;
  position: relative;
  top:50rpx;
}
.t2{
  width:100%;
  height:125rpx;
  background-color: white;
  position: relative;
  top:60rpx;
}
.text{
position: relative;
left:40rpx;
top:40rpx;
color: rgb(143, 143, 143);
}
.box{
  width:400rpx;
  height:80rpx;
  margin-left: 200rpx;
  position: relative;
  bottom: 25rpx;
}
#t3 text{
position: relative;
left:40rpx;
top:40rpx;
color: rgb(143, 143, 143);
}
#pass2{
  width:400rpx;
  height:80rpx;
  margin-left: 320rpx;
  position: relative;
  bottom: 25rpx;
}
.btn{
  position: relative;
  top:100rpx;
  background-color:rgb(51, 204, 170);
  width:600rpx;
  border-radius: 50rpx;
}
.font2{
  color:white;
  font-size: 39rpx;
}
//js
Page({
  data: {
    moblie: '',//賬號
    password: ''//密碼
  },
  // 獲取輸入的賬號 
  mobileInput: function (e) {
    this.setData({
      moblie: e.detail.value
    })
  },
  // 獲取輸入的密碼 
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  }, // 登入
  login: function () {
    var that = this;
    //判斷賬號密碼是否為空,為空彈窗提示
    if (this.data.moblie == nul || that.data.password == null) {
      wx.showToast({
        title: "使用者名稱或密碼錯誤",
        icon: '',
        duration: 2000 //彈出時間
      })
    } else {
      wx.request({
        url: "http://localhost:9000/user/login",
        method: "POST",
        dataType: "json",
        data: {
          mobile: that.data.moblie,
          password: that.data.password
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (result) {
          console.log("回撥函式:" + result)
          if (result.data.code == "20000") {
            console.log("成功")

            wx.navigateTo({
              url: '../logs/logs',
            })
          } else {
            console.log("使用者名稱或密碼錯誤")
            wx.showToast({
              title: "使用者名稱或密碼錯誤",
              icon: '',
              duration: 2000 //彈出時間
            })
          }
        },
        //若是請求路徑錯了,著下面語句就有用了
        fail: function () {
          console.log("登入失敗")
        }
      })
    }
  }
})

後端

那啥springboot啥的我就不建了, emmm,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>

    <groupId>com.zut</groupId>
    <artifactId>t_parents</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <!--子模組-->
             
        <!--經常用的類封裝到一個模組裡邊,返回型別,常量,分頁啥的-->
        <module>t_common</module>
        <module>t_base</module>
        <module>t_recruit</module>
        <module>t_article</module>
        <!--使用者登入的模組-->
        <module>t_user</module>
        <module>t_qa</module>
    </modules>

    <!--為了統一jar包版本,讓子工程依賴-->
    <!--springboot專案是通過main方法啟動 是web專案-->
    <!--其內建tomcat 不需要第三方tomcat-->
    <!--父工廠 包含spring所需要的一系列jar-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/>
    </parent>
    <!--編譯版本-->
    <properties>
        <project.build.sourceEncoding>UTF‐8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF‐8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--相當於springmvc的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--spring測試的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <!--指定遠端倉庫 方便jar包快速下載-->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <!--加速jar包下載的外掛-->
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

t_user的pom.xml 依賴就這麼多,頭頭尾尾的麻煩還佔空間

<dependencies>
        <!--依賴common工程-->
        <dependency>
            <groupId>com.zut</groupId>
            <artifactId>t_common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--依賴jpa 【前身是hibernate】-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--依賴MySQL連線包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

用到的工具類

/**
 * 返回結果類
 * @author hjh 這不是我名字,就是單純的好傢伙首字母拼寫 笑
 */
public class Result {
    //滿足介面文件對返回值資料格式要求
    private Boolean flag;
    private Integer code;
    private String message;
    private Object data;
    //三個構造方法 無參,無data,全參 以及get set

常量類還是寫出來吧

/**
 * 定義常量類
 * @author hjh
 */
public class StatusCode {
    //滿足介面文件資料格式要求,把狀態碼提埃納定義為常量,方便使用
    //不需要構造方法 以及get set
    public static final int OK=20000;//成功
    public static final int ERROR =20001;//失敗
    public static final int LOGINERROR =20002;//使用者名稱或密碼錯誤
    public static final int ACCESSERROR =20003;//許可權不足
    public static final int REMOTEERROR =20004;//遠端呼叫失敗
    public static final int REPERROR =20005;//重複操作
}

對了,配置檔案,差點給忘了,要是看不懂,我直接阿巴阿巴

server:
  port: 9000
spring:
  application:
    name: t_user

  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/tensquare_user?useSSL=false
    username: root
    password: root
  jpa:
    database: mysql
    show-sql: true

專案啟動類,有個自動生成id的類,用不到就不展示了

/**
 * 啟動類
 * @author hjh
 */
@SpringBootApplication
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class);
    }
}

使用者實體類,加註解了,不懂的瞭解瞭解去,我能把我自己講糊塗,嘿嘿

/**
 * 使用者類
 * @author hjh
 */
@Entity
@Table(name = "tb_user")//表名
public class User implements Serializable {
    @Id
    private String id;//編號
    private String mobile;//手機號
    private String password;//密碼
    private String nickname;//暱稱
    private String sex;//性別
    private Date birthday;//生日
    private String avatar;//頭像
    private String email;//郵件
    private Date regdate;//註冊時間
    private Date updatedate;//更新時間
    private Date lastdate;//最後訊息時間
    private long online;//線上
    private String interest;//興趣
    private String personality;//性格
    private Integer fanscount;//粉絲數
    private Integer followcount;//關注數

持久層,註解全的很,我是不會浪費口舌的,哼

/**
 * 使用者持久層
 * 作用:訪問資料庫,向資料庫傳送sql語句,完成資料的增刪改查任務。
 * @author hjh
 */
public interface UserDao extends JpaRepository<User,String>, JpaSpecificationExecutor<User> {
    //JpaRepository 包含了簡單的crud的API crud:增刪改查  ---基本的增刪改查
    //JpaSpecificationExecutor 包含了帶(規範)條件查詢的API  ---複雜的條件查詢
    //效果:JPA繼承了這兩個介面,標誌著我們以後在後期操作資料庫過程中
    //     有大部分操作都不需要自己寫sql語句,而是可以呼叫介面中現成的API
}

介面和實現類放一塊得了,對了前端已經判斷過使用者名稱密碼是否為空了,這地方再寫有點多於,可以刪了(有這解釋的時間,早刪了,但我偏不)

public interface UserService {
    //登入
    public Result userLogin(User user);
}


/**
 * 操作使用者介面實現類
 * @author hjh
 */
@Transactional//emmm,自己瞭解,這玩意我也不明白
@Service
public class UserServiceImpl implements UserService {
    //注入dao層
    @Autowired
    UserDao userDao;
    @Autowired
    IdWorker idWorker;//啊,剛才說的就是這玩意

    @Override
    public Result userLogin(User user) {
        if (user.getMobile().equals("") || user.getMobile() == null || user.getPassword().equals("") || user.getPassword() == null) {
            return new Result(false, StatusCode.LOGINERROR, "使用者名稱或密碼為空");
        }
        List<User> all = userDao.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.equal(root.get("mobile").as(String.class), user.getMobile());
                Predicate predicate1 = criteriaBuilder.equal(root.get("password").as(String.class), user.getPassword());
                return criteriaBuilder.and(predicate, predicate1);
            }
        });
        if (all.size() > 0) {
            return new Result(true, StatusCode.OK, "登入成功");
        }
        return new Result(false, StatusCode.LOGINERROR, "使用者名稱或密碼錯誤");
    }
 }

那啥,控制層

/**
 * @author hjh
 */
@RestController//這也去了解吧,要是我說錯了,你信了,你笨了還怪我,嘿嘿
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/user/login")
    public Result userLogin(@RequestBody User user){
        return userService.userLogin(user);
    }
}

沒漏,沒漏,沒漏,嗯,沒漏,這是真的

在這裡插入圖片描述

運行了,postman瞅一眼,沒毛病,那啥就前端測了

在這裡插入圖片描述

在這裡插入圖片描述

完了。這就完了?嗯,完了。就這?,就這啊?
最後很複雜的審視了一遍,這時我寫的?倒數第二個圖提示可以改一下,不然容易和使用者名稱密碼錯誤提示弄混