当前位置:网站首页>7. development of mobile login function
7. development of mobile login function
2022-06-30 09:57:00 【xjhqre】
Mobile login function development
It is difficult to apply for SMS service , The function of sending text messages is not done . Verification code directly with log Print it out in the form of a log .
1、 Sort out the interaction process
- On the login page (front/ page/login.html) Enter phone number , Click on 【 Get verification code 】 Button , Page sending ajax request , Call the SMS service at the server API Send verification code SMS to the specified mobile phone number
- Enter the verification code on the login page , Click on 【 land 】 Button , send out ajax request , Handle the login request on the server
2、 preparation
Create basic classes and interfaces :
- Entity class User( Import directly from the course materials )
- Mapper Interface UserMapper
- Business layer interface UserService
- Business layer implementation classes UserServicelmpl
- Control layer UserController
- Tool class SMSutils、ValidateCodeutils ( Import directly from the course materials )
2.1、 modify LoginCheckFilter
When we log in with the mobile verification code , Requests sent need to be released directly when processed by this filter
modify LoginCheckFilter Of doFilter There are two ways .

Add "judge mobile user login" under "judge user login"

// 4.2 Determine whether to log in for mobile phone users
if (request.getSession().getAttribute("user") != null) {
log.info(" Mobile user has logged in , user id by :{}", request.getSession().getAttribute("user"));
Long userId = (Long) request.getSession().getAttribute("user");
BaseContext.setCurrentId(userId);
filterChain.doFilter(request, response);
return;
}
3、 Simulate sending SMS
stay UserController Created in sendMsg Method to simulate SMS sending
package com.itheima.reggie.controller;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
/** * @Author: xjhqre * @DateTime: 2022/6/15 16:50 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/** * Send SMS verification code * @param user * @return */
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session) {
// Get cell phone number
String phone = user.getPhone();
if(StringUtils.isNotEmpty(phone)) {
// Generate random 4 Bit verification code
String code = ValidateCodeUtils.generateValidateCode(4).toString();
log.info("4 The bit verification code is :{}", code);
// Call the SMS service provided by Alibaba cloud API Finish sending SMS
//...
// Save the generated verification code to Session
session.setAttribute(phone, code);
return R.success(" Mobile phone verification code SMS sent successfully ");
}
return R.error(" SMS sending failed ");
}
@PostMapping("/login")
public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
log.info(map.toString());
return R.error(" Login failed ");
}
}
3.1、 Modify the front page ( Optional )
The mobile landing page given in the course materials , Click send verification code and it will be directly displayed in the form , There is no back-end interface . The following is the method to request the back-end interface instead
1、 stay front/api/login.js Add in sendMsgApi Method
function sendMsgApi(data) {
return $axios({
'url': '/user/sendMsg',
'method': 'post',
data
})
}
2、 And then modify front/page/login.html page

3.2、 Test Click to get the verification code
4、 Landing function
Input the verification code on the front-end login page and click login to send the request

stay UserController Write the login method login
@PostMapping("/login")
public R<User> login(@RequestBody Map map, HttpSession session) {
log.info(map.toString());
// Get cell phone number
String phone = map.get("phone").toString();
// Get the verification code entered by the user
String code = map.get("code").toString();
// from Session Get the saved verification code from
String sessionCode = (String) session.getAttribute(phone);
// Verification code verification
if(sessionCode != null && sessionCode.equals(code)) {
// After successful verification, determine whether the user is logging in for the first time , It needs to be saved to the database
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getPhone, phone);
User user = userService.getOne(queryWrapper);
if (user == null) {
user = new User();
user.setPhone(phone);
user.setStatus(1); // You can leave it blank , The default value of the database is 1
userService.save(user);
}
session.setAttribute("user", user.getId());
return R.success(user);
}
return R.error(" Login failed ");
}
4.1、 Test the login function
Follow the above steps to write the interface , Click the login button to find that there is only one parameter in the page request phone, Without code Parameters . The front-end request code needs to be modified
modify front/page/login.html On the page btnLogin The method can

Test again and you will be successful
边栏推荐
- Utlis memory pool object pool
- Stack Title: String decoding
- utils 协程
- The present situation and challenge of the infrastructure of Yiwen parsing database
- Eight sorts (II)
- Flutter 中的 ValueNotifier 和 ValueListenableBuilder
- JWT expiration processing - single token scheme
- [Ubuntu redis installation]
- MySQL index optimization miscellaneous
- Self service terminal handwritten Chinese character recognition input method library tjfink introduction
猜你喜欢

MySQL优化

NER – Named Entity Recognition Summary

云技能提升好伙伴,亚马逊云师兄今天正式营业

Cobbler Automated Deployment

MySQL internal component structure

Shell script multi loop experiment

机械臂速成小指南(五):末端执行器

安装和使用

Forrester senior analyst: five important trends in the development of the hyper convergence market

JVM notes (III): analysis of JVM object creation and memory allocation mechanism
随机推荐
Redis docker master-slave mode and sentinel
布隆过滤器
Enterprise data center "cloud" transformation solution
Appium自动化测试基础 — 12.APPium自动化测试框架介绍
Application exploration and practice of super convergence in the production environment of insurance industry
Self service terminal development process
MySQL optimization
Abstract classes and interfaces
【Ubuntu-MySQL8安装与主从复制】
MySQL internal component structure
NER – Named Entity Recognition Summary
Brève description du collecteur d'ordures G1
Configuring MySQL for error reporting
qmlplugindump executable not found. It is required to generate the qmltypes file for VTK Qml
Difference between bow and cbow
Xlnet (generalized autorefressive trainingfor language understanding) paper notes
[new book recommendation] DeNO web development
Cloud native database
3. integrate eslint and prettier
Oracle cross database replication data table dblink