转自:https://idig8.com/2018/09/01/xiaochengxujavashizhanxiaochengxudengluyuhouduanliandiao36/

重新温习下用户的注册的方式,开发一个用户登录的spring boot接口。源码:https://github.com/limingios/wxProgram.git 中的wx-springboot 和 No.15

service 类的开发

  • UserService.java

 

package com.idig8.service;

import com.idig8.pojo.Users;

public interface UserService {

    /**
     * 判断用户名是否存在
     * @param username
     * @return
     */
    public boolean queryUsernameIsExist(String username);

    /**
     * 保存用户
     * @param user
     * @return
     */
    public void saveUser(Users user);

    /**
     * 查询用户对象
     * @param username
     * @return
     */
    public Users queryUserIsExist(Users user);


}

···

* UserServiceImpl.java
> Sid 是注入的id的生成工具,Example queryExample = new Example(Users.class);
和 Criteria criteria = queryExample.createCriteria(); 都是一种套路,就是查询套路,大家可以看看
https://baike.baidu.com/item/criteria/5354117

··· java
package com.idig8.service;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.idig8.mapper.UsersMapper;
import com.idig8.pojo.Users;
import com.idig8.utils.MD5Utils;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private Sid sid;

    @Transactional(propagation =Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Users user = new Users();
        user.setUsername(username);
        Users result = usersMapper.selectOne(user);
        return result==null? false:true;
    }

    @Transactional(propagation =Propagation.REQUIRED)
    @Override
    public void saveUser(Users user) {
        String userId =sid.nextShort();
        user.setId(userId);
        usersMapper.insert(user);
    }

    @Transactional(propagation =Propagation.SUPPORTS)
    @Override
    public Users queryUserIsExist(Users user) {
        Example queryExample = new Example(Users.class);
        Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("username",user.getUsername());
        try {
            criteria.andEqualTo("password",MD5Utils.getMD5Str(user.getPassword()));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Users userOne =  usersMapper.selectOneByExample(queryExample);
        return userOne;
    }

}

controller 类的开发

RegistLoginController.java

增加了登录方法。


package com.idig8.controller; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.idig8.pojo.Users; import com.idig8.service.UserService; import com.idig8.utils.JSONResult; import com.idig8.utils.MD5Utils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @Api(value="用户注册登录的接口",tags={"注册和登录的controller"}) public class RegistLoginController { @Autowired private UserService userService; @ApiOperation(value="用户注册",notes="用户注册的接口") @PostMapping("/regist") public JSONResult regist(@RequestBody Users user) { //1.判断用户名和密码不能为空 if(StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())) { return JSONResult.errorMsg("用户名或密码不能为空"); } //2.判断用户名是否存在 boolean usernameIsExist = userService.queryUsernameIsExist(user.getUsername()); if(!usernameIsExist) { user.setNickname(user.getUsername()); try { user.setPassword(MD5Utils.getMD5Str(user.getPassword())); } catch (Exception e) { return JSONResult.errorMsg(e.getMessage()); } user.setFollowCounts(0); user.setReceiveLikeCounts(0); user.setFansCounts(0); userService.saveUser(user); }else { return JSONResult.errorMsg("用户名或已经存在,请更换在试试!"); } //防止密码返回被获取到 user.setPassword(""); return JSONResult.ok(user); } @ApiOperation(value="用户登录",notes="用户登录的接口") @PostMapping("/login") public JSONResult login(@RequestBody Users user) { //1.判断用户名和密码不能为空 if(StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())) { return JSONResult.errorMsg("用户名或密码不能为空"); } //2.判断用户名是否存在 Users userObject = userService.queryUserIsExist(user); if(userObject==null){ return JSONResult.errorMsg("用户名或密码不存在!"); } //防止密码返回被获取到 user.setPassword(""); return JSONResult.ok(userObject); } }

wx前端部分的开发

<view>
    <view class="login-icon">
        <image class="login-img" src="../../resource/images/dsp.jpg"></image>
    </view>
    <view class="login-from">
        <form bindsubmit='doLogin'>
            <!--账号-->
            <view class="inputView">
                <image class="nameImage" src="../../resource/images/username.png"></image>
                <label class="loginLabel">账号</label>
                <input name="username" type="text"  maxlength="10" class="inputText" placeholder="请输入账号"/>
            </view>

            <view class="line"></view>

            <!--密码-->
            <view class="inputView">
                <image class="keyImage" src="../../resource/images/password.png"></image>
                <label class="loginLabel">密码</label>
                <input name="password" maxlength="10" type="text" class="inputText" password="{{true}}" placeholder="请输入密码"/>
            </view>

            <!--按钮-->
            <view>
                <button class="loginBtn" type="primary" form-type='submit'>登陆</button>
            </view>

            <view>
                <button class="goLoginBtn" type="warn" bindtap="goRegisterPage">返回注册</button>
            </view>
        </form>
    </view>
</view>
const app = getApp()

Page({
  data: {

  },

  doLogin: function (e) {
    var formObject = e.detail.value;
    var username = formObject.username;
    var password = formObject.password;

    // 简单验证
    if (username.length == 0 || password.length == 0) {
      wx.showToast({
        title: '用户名或密码不能为空',
        icon: 'none',
        duration: 3000
      })
    } else {
      wx.request({
        url: app.serverUrl + "/login",
        method: "POST",
        data: {
          username: username,
          password: password
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {
          console.log(res.data);
          var status = res.data.status;
          if (status == 200) {
            wx.showToast({
              title: "用户登陆成功~!",
              icon: 'none',
              duration: 3000
            })
            app.userinfo = res.data.data;
          } else if (status == 500) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 3000
            })
          }
        }
      })
    }
  },
  goLoginPage: function (e) {
    console.log("跳转到注册");
  }
})

PS:测试成功了,其实登录和注册页面基本一样的,就是改了个标题,请求的request地址发生了改变,唯一区别比较大的是,https://baike.baidu.com/item/criteria/5354117 这是spring boot常用的。

posted on 2019-01-21 02:11  Sharpest  阅读(828)  评论(0编辑  收藏  举报