畅购电商项目-02-用户注册-2021-06-11
作者:互联网
4.用户模块(8081)
4.1搭建环境
4.1.1后端web服务:changgou4-service-web
- 修改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">
<parent>
<artifactId>changgou4-parent-ali</artifactId>
<groupId>com.czxy.changgou</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>changgou4_service_web</artifactId>
<dependencies>
<!--自定义项目-->
<dependency>
<groupId>com.czxy.changgou</groupId>
<artifactId>changgou4_common_db</artifactId>
</dependency>
<dependency>
<groupId>com.czxy.changgou</groupId>
<artifactId>changgou4_pojo</artifactId>
</dependency>
<!--web起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- nacos 客户端 -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
<!-- nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies>
</project>
- 创建application.yml文档
#端口号
server:
port: 8081
spring:
application:
name: web-service #服务名
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/changgou_db?useUnicode=true&characterEncoding=utf8
username: root
password: 1234
druid: #druid 连接池配置
initial-size: 1 #初始化连接池大小
min-idle: 1 #最小连接数
max-active: 20 #最大连接数
test-on-borrow: true #获取连接时候验证,会影响性能
redis:
database: 0
host: 127.0.0.1
port: 6379
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #nacos服务地址
sentinel:
transport:
dashboard: 127.0.0.1:8080
- 创建启动类
package com.czxy.changgou4;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@SpringBootApplication
@EnableDiscoveryClient
public class Web-serviceApplication {
public static void main(String[] args) {
SpringApplication.run( Web-serviceApplication.class , args );
}
}
4.1.2后端创建JavaBean:User
- 在changgou4-pojo项目中添加User对象
package com.czxy.changgou4.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.beans.Transient;
import java.util.Date;
/** 与数据库对应JavaBean
* Created by liangtong.
*/
@TableName("tb_user")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
/*
CREATE TABLE `tb_user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Email',
`mobile` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT '手机号码',
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '昵称',
`password` char(60) COLLATE utf8_unicode_ci NOT NULL COMMENT '密码',
`face` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '头像',
`expriece` int(10) unsigned DEFAULT '0' COMMENT '经验值',
PRIMARY KEY (`id`),
UNIQUE KEY `users_mobile_unique` (`mobile`),
UNIQUE KEY `users_name_unique` (`name`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
*/
@TableId(value="id",type = IdType.AUTO)
private Long id;
@TableField(value="username")
private String username;
@TableField(value="password")
private String password;
@TableField(value="face")
private String face;
@TableField(value="expriece")
private Integer expriece;
@TableField(value="email")
private String email;
@TableField(value="mobile")
private String mobile;
@TableField(value="created_at")
private Date createdAt;
@TableField(value="updated_at")
private Date updatedAt;
@TableField(exist = false)
private String code;
@TableField(exist = false)
private String password_confirm;
}
4.1.3前端页面:创建公共组件
- 1)删除components目录下所有内容,并创建3个新组件
- 2)创建 TopNav.vue组件,用于配置“顶部导航”
<template>
<!-- 顶部导航 start -->
<div class="topnav">
<div class="topnav_bd w990 bc">
<div class="topnav_left">
</div>
<div class="topnav_right fr">
<ul>
<li>您好,欢迎来到畅购![<a href="login.html">登录</a>] [<a href="register.html">免费注册</a>] </li>
<li class="line">|</li>
<li>我的订单</li>
<li class="line">|</li>
<li>客户服务</li>
</ul>
</div>
</div>
</div>
<!-- 顶部导航 end -->
</template>
<script>
export default {
}
</script>
<style>
</style>
- 3)创建 HeaderLogo.vue组件,用于配置“页面头部,仅有LOGO”.
<template>
<!-- 页面头部 start -->
<div class="header w990 bc mt15">
<div class="logo w990">
<h2 class="fl"><a href="index.html"><img src="/images/logo.png" alt="畅购商城"></a></h2>
</div>
</div>
<!-- 页面头部 end -->
</template>
<script>
export default {
}
</script>
<style>
</style>
- 4)创建 Footer.vue组件,用于配置“底部版权”
<template>
<!-- 底部版权 start -->
<div class="footer w1210 bc mt15">
<p class="links">
<a href="">关于我们</a> |
<a href="">联系我们</a> |
<a href="">人才招聘</a> |
<a href="">商家入驻</a> |
<a href="">千寻网</a> |
<a href="">奢侈品网</a> |
<a href="">广告服务</a> |
<a href="">移动终端</a> |
<a href="">友情链接</a> |
<a href="">销售联盟</a> |
<a href="">畅购论坛</a>
</p>
<p class="copyright">
© 2006-2020 畅购网上商城 版权所有,并保留所有权利。 ICP备案证书号:京ICP证070359号
</p>
<p class="auth">
<a href=""><img src="/images/xin.png" alt="" /></a>
<a href=""><img src="/images/kexin.jpg" alt="" /></a>
<a href=""><img src="/images/police.jpg" alt="" /></a>
<a href=""><img src="/images/beian.gif" alt="" /></a>
</p>
</div>
<!-- 底部版权 end -->
</template>
<script>
export default {
}
</script>
<style>
</style>
4.2用户注册:用户名占用
4.2.1接口
http://localhost:10010/web-service/user/checkusername
4.2.2后端
- 创建三层需要的接口或类
- 步骤一:创建UserMapper,编写findByUsername()完成“通过用户名查询用户”
package com.czxy.changgou4.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.czxy.changgou4.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* Created by liangtong.
*/
@org.apache.ibatis.annotations.Mapper
public interface UserMapper extends BaseMapper<User> {
/**
* 通过用户名查询
* @param username
* @return
*/
@Select("select * from tb_user where username = #{username}")
User findByUsername(@Param("username") String username);
}
- 步骤二:创建UserService接口,查询功能
package com.czxy.changgou4.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.czxy.changgou4.pojo.User;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
public interface UserService extends IService<User> {
/**
* 通过用户名查询
* @param username
* @return
*/
public User findByUsername(String username);
}
- 步骤三:创建UserServiceImpl实现类,查询功能
package com.czxy.changgou4.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.changgou4.mapper.UserMapper;
import com.czxy.changgou4.pojo.User;
import com.czxy.changgou4.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public User findByUsername(String username) {
return baseMapper.findByUsername(username);
}
}
- 步骤四:创建UserController,完成用户名检查
package com.czxy.changgou4.controller;
import com.czxy.changgou4.pojo.User;
import com.czxy.changgou4.service.UserService;
import com.czxy.changgou4.vo.BaseResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* Created by liangtong.
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@PostMapping("/checkusername")
public BaseResult checkUsername(@RequestBody User user){
//查询用户
User findUser = userService.findByUsername( user.getUsername() );
//判断
if(findUser != null){
return BaseResult.error("用户名已经存在");
} else {
return BaseResult.ok("用户名可用");
}
}
}
4.2.3前端
- 步骤一:创建Register.vue
- 步骤二:添加公共组件
<template>
<div>
<TopNav></TopNav>
<div style="clear:both;"></div>
<HeaderLogo></HeaderLogo>
<div style="clear:both;"></div>
<!-- 正文 -->
<div style="clear:both;"></div>
<Footer></Footer>
</div>
</template>
<script>
import TopNav from '../components/TopNav'
import HeaderLogo from '../components/HeaderLogo'
import Footer from '../components/Footer'
export default {
head: {
title: '用户注册'
},
components : {
TopNav,
HeaderLogo,
Footer
}
}
</script>
<style>
</style>
- 步骤三:编写注册表单,并导入独有样式
<template>
<div>
<TopNav></TopNav>
<div style="clear:both;"></div>
<HeaderLogo></HeaderLogo>
<div style="clear:both;"></div>
<!-- 正文 -->
<!-- 登录主体部分start -->
<div class="login w990 bc mt10 regist">
<div class="login_hd">
<h2>用户注册</h2>
<b></b>
</div>
<div class="login_bd">
<div class="login_form fl">
<form action="" method="post">
<ul>
<li>
<label for="">用户名:</label>
<input type="text" class="txt" name="username" />
<p>3-20位字符,可由中文、字母、数字和下划线组成</p>
<p class="error">用户名已存在</p>
</li>
<li>
<label for="">密码:</label>
<input type="password" class="txt" name="password" />
<p>6-20位字符,可使用字母、数字和符号的组合,不建议使用纯数字、纯字母、纯符号</p>
</li>
<li>
<label for="">确认密码:</label>
<input type="password" class="txt" name="password" />
<p>请再次输入密码</p>
</li>
<li>
<label for="">手机号码:</label>
<input type="text" class="txt" name="mobile" />
<p>请输入手机号码</p>
</li>
<li class="checkcode">
<label for="">验证码:</label>
<input type="text" name="checkcode" />
<button >
发送验证码<span>5秒</span>
</button>
</li>
<li>
<label for=""> </label>
<input type="checkbox" class="chb" checked="checked" /> 我已阅读并同意《用户注册协议》
</li>
<li>
<label for=""> </label>
<input type="submit" value="" class="login_btn" />
</li>
</ul>
</form>
</div>
<div class="mobile fl">
<h3>手机快速注册</h3>
<p>中国大陆手机用户,编辑短信 “<strong>XX</strong>”发送到:</p>
<p><strong>1069099988</strong></p>
</div>
</div>
</div>
<!-- 登录主体部分end -->
<div style="clear:both;"></div>
<Footer></Footer>
</div>
</template>
<script>
import TopNav from '../components/TopNav'
import HeaderLogo from '../components/HeaderLogo'
import Footer from '../components/Footer'
export default {
head: {
title: '用户注册',
link: [
{rel:'stylesheet',href:'style/login.css'}
],
script: [
{ type: 'text/javascript', src: 'js/header.js' },
{ type: 'text/javascript', src: 'js/index.js' },
]
},
components : {
TopNav,
HeaderLogo,
Footer
}
}
</script>
<style>
</style>
- 步骤四:修改api.js,编写检查用户名的ajax函数
const request = {
test : ()=> {
return axios.get('/test')
},
//检查用户名
checkUsername : ( username )=> {
return axios.post('/web-service/user/checkusername', { username })
}
}
- 步骤五:修改Register.vue页面,完成检查功能
- 发送ajax进行用户名是否可用检查
- 如果可用,显示对应信息,并使用success样式显示
- 如果不可用,显示对应信息,并使用error样式提示
<template>
<div>
<TopNav></TopNav>
<div style="clear:both;"></div>
<HeaderLogo></HeaderLogo>
<div style="clear:both;"></div>
<!-- 正文 -->
<!-- 登录主体部分start -->
<div class="login w990 bc mt10 regist">
<div class="login_hd">
<h2>用户注册</h2>
<b></b>
</div>
<div class="login_bd">
<div class="login_form fl">
<form action="" method="post">
<ul>
<li>
<label for="">用户名:</label>
<input type="text" class="txt" name="username" v-model="user.username" @blur="checkUsernameFn" />
<p>3-20位字符,可由中文、字母、数字和下划线组成</p>
<p :class="userMsg.usernameData.code == 1 ? 'success' : 'error'">{{userMsg.usernameData.message}} </p>
</li>
<li>
<label for="">密码:</label>
<input type="password" class="txt" name="password" />
<p>6-20位字符,可使用字母、数字和符号的组合,不建议使用纯数字、纯字母、纯符号</p>
</li>
<li>
<label for="">确认密码:</label>
<input type="password" class="txt" name="password" />
<p>请再次输入密码</p>
</li>
<li>
<label for="">手机号码:</label>
<input type="text" class="txt" name="mobile" />
<p>请输入手机号码</p>
</li>
<li class="checkcode">
<label for="">验证码:</label>
<input type="text" name="checkcode" />
<button >
发送验证码<span>5秒</span>
</button>
</li>
<li>
<label for=""> </label>
<input type="checkbox" class="chb" checked="checked" /> 我已阅读并同意《用户注册协议》
</li>
<li>
<label for=""> </label>
<input type="submit" value="" class="login_btn" />
</li>
</ul>
</form>
</div>
<div class="mobile fl">
<h3>手机快速注册</h3>
<p>中国大陆手机用户,编辑短信 “<strong>XX</strong>”发送到:</p>
<p><strong>1069099988</strong></p>
</div>
</div>
</div>
<!-- 登录主体部分end -->
<div style="clear:both;"></div>
<Footer></Footer>
</div>
</template>
<script>
import TopNav from '../components/TopNav'
import HeaderLogo from '../components/HeaderLogo'
import Footer from '../components/Footer'
export default {
head: {
title: '用户注册',
link: [
{rel:'stylesheet',href:'style/login.css'}
],
script: [
{ type: 'text/javascript', src: 'js/header.js' },
{ type: 'text/javascript', src: 'js/index.js' },
]
},
components : {
TopNav,
HeaderLogo,
Footer
},
data() {
return {
user : { //表单绑定对象
username : ""
},
userMsg : { //错误信息
usernameData : ""
}
}
},
methods: {
async checkUsernameFn() {
let {data} = await this.$request.checkUsername( this.user.username )
this.userMsg.usernameData = data
}
},
}
</script>
<style>
</style>
4.3用户注册:手机号检查
4.3.1接口
http://localhost:10010/web-service/user/checkmobile
4.3.2后端
- 步骤一:修改UserService,添加 findByMobile() 方法,进行电话号码的查询
/**
* 通过手机号查询
* @param mobile
* @return
*/
User findByMobile(String mobile);
- 步骤二:编写UserServiceImpl,实现findByMobile() 方法
@Override
public User findByMobile(String mobile) {
// 拼凑条件
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("mobile", mobile);
// 查询一个
List<User> list = baseMapper.selectList(queryWrapper);
if(list.size() == 1) {
return list.get(0);
}
return null;
}
- 步骤三:修改UserController,添加checkMobile() 方法
/**
* 通过手机号查询
* @param user
* @return
*/
@PostMapping("/checkmobile")
public BaseResult checkMobile(@RequestBody User user){
//查询用户
User findUser = userService.findByMobile( user.getMobile() );
//判断
if(findUser != null){
return BaseResult.error("电话号码已经注册");
} else {
return BaseResult.ok("电话号码可用");
}
}
4.3.3前端
- 步骤一:修改api.js,添加 checkMobile() 函数
const request = {
test : ()=> {
return axios.get('/test')
},
//检查用户名
checkUsername : ( username )=> {
return axios.post('/web-service/user/checkusername', { username })
},
//检查电话号码
checkMobile : ( mobile )=> {
return axios.post('/web-service/user/checkmobile', { mobile })
}
}
- 步骤二:修改Register.vue,添加 checkMobileFn() 进行手机号检查
methods: {
async checkUsernameFn() {
//检查用户名
let {data} = await this.$request.checkUsername( this.user.username )
this.userMsg.usernameData = data
},
async checkMobileFn() {
//检查电话
let {data} = await this.$request.checkMobile( this.user.mobile )
this.userMsg.mobileData = data
}
},
- 步骤三:编写需要的2个变量
data() {
return {
user : { //表单封装数据
username : "",
mobile : ""
},
userMsg : { //错误提示数据
usernameData : "",
mobileData : ""
}
}
},
- 步骤四:处理页面
<li>
<label for="">手机号码:</label>
<input type="text" class="txt" name="mobile" v-model="user.mobile" @blur="checkMobileFn" />
<p>请输入手机号码</p>
<p :class="userMsg.mobileData.code == 1 ? 'success' : 'error'">{{userMsg.mobileData.message}} </p>
</li>
- 完整版
<template>
<div>
<TopNav></TopNav>
<div style="clear:both;"></div>
<HeaderLogo></HeaderLogo>
<div style="clear:both;"></div>
<!-- 正文 -->
<!-- 登录主体部分start -->
<div class="login w990 bc mt10 regist">
<div class="login_hd">
<h2>用户注册</h2>
<b></b>
</div>
<div class="login_bd">
<div class="login_form fl">
<form action="" method="post">
<ul>
<li>
<label for="">用户名:</label>
<input type="text" class="txt" name="username" v-model="user.username" @blur="checkUsernameFn" />
<p>3-20位字符,可由中文、字母、数字和下划线组成</p>
<p :class="userMsg.usernameData.code == 1 ? 'success' : 'error'">{{userMsg.usernameData.message}} </p>
</li>
<li>
<label for="">密码:</label>
<input type="password" class="txt" name="password" />
<p>6-20位字符,可使用字母、数字和符号的组合,不建议使用纯数字、纯字母、纯符号</p>
</li>
<li>
<label for="">确认密码:</label>
<input type="password" class="txt" name="password" />
<p>请再次输入密码</p>
</li>
<li>
<label for="">手机号码:</label>
<input type="text" class="txt" name="mobile" v-model="user.mobile" @blur="checkMobileFn" />
<p>请输入手机号码</p>
<p :class="userMsg.mobileData.code == 1 ? 'success' : 'error'">{{userMsg.mobileData.message}} </p>
</li>
<li class="checkcode">
<label for="">验证码:</label>
<input type="text" name="checkcode" />
<button >
发送验证码<span>5秒</span>
</button>
</li>
<li>
<label for=""> </label>
<input type="checkbox" class="chb" checked="checked" /> 我已阅读并同意《用户注册协议》
</li>
<li>
<label for=""> </label>
<input type="submit" value="" class="login_btn" />
</li>
</ul>
</form>
</div>
<div class="mobile fl">
<h3>手机快速注册</h3>
<p>中国大陆手机用户,编辑短信 “<strong>XX</strong>”发送到:</p>
<p><strong>1069099988</strong></p>
</div>
</div>
</div>
<!-- 登录主体部分end -->
<div style="clear:both;"></div>
<Footer></Footer>
</div>
</template>
<script>
import TopNav from '../components/TopNav'
import HeaderLogo from '../components/HeaderLogo'
import Footer from '../components/Footer'
export default {
head: {
title: '用户注册',
link: [
{rel:'stylesheet',href:'style/login.css'}
],
script: [
{ type: 'text/javascript', src: 'js/header.js' },
{ type: 'text/javascript', src: 'js/index.js' },
]
},
components : {
TopNav,
HeaderLogo,
Footer
},
data() {
return {
user : { //表单封装数据
username : "",
mobile : "",
password : "",
code : ""
},
userMsg : { //错误提示数据
usernameData : "",
mobileData : ""
}
}
},
methods: {
async checkUsernameFn() {
//检查用户名
let {data} = await this.$request.checkUsername( this.user.username )
this.userMsg.usernameData = data
},
async checkMobileFn() {
//检查电话
let {data} = await this.$request.checkMobile( this.user.mobile )
this.userMsg.mobileData = data
}
},
}
</script>
<style>
</style>
4.4用户注册:前置技术–Redis
4.5用户注册:前置技术–阿里大鱼
4.6用户注册:短信验证码
- 4.6.1分析
4.6.2接口
http://localhost:10010/web-service/sms
4.6.3后端
- 创建 SmsController类,调用阿里大鱼工具类,发送短信。
package com.czxy.changgou4.controller;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.czxy.changgou4.pojo.User;
import com.czxy.changgou4.utils.SmsUtil;
import com.czxy.changgou4.vo.BaseResult;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
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.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* Created by liangtong.
*/
@RestController
@RequestMapping("/sms")
public class SmsController {
@Resource
private StringRedisTemplate redisTemplate;
@PostMapping
public BaseResult sendSms(@RequestBody User user){
long start = System.currentTimeMillis();
try {
//发送短信
//1 生产验证码
String code = RandomStringUtils.randomNumeric(4);
System.out.println("验证码:" + code);
//2 并存放到reids中 , key: "sms_register" + 手机号 , value:验证码 , 1小时
redisTemplate.opsForValue().set( "sms_register" + user.getMobile() , code , 1 , TimeUnit.HOURS);
/**/
//3 发送短信
SendSmsResponse smsResponse = SmsUtil.sendSms(user.getMobile(), user.getUsername() , code, "", "");
//https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55322.6.557.KvvIJx
if("OK".equalsIgnoreCase(smsResponse.getCode())){
return BaseResult.ok("发送成功");
} else {
return BaseResult.error(smsResponse.getMessage());
}
/*
//模拟数据
System.out.println("验证码:" + code);
return BaseResult.ok("发送成功");
*/
} catch (Exception e) {
long end = System.currentTimeMillis();
System.out.println( end - start);
return BaseResult.error("发送失败" );
}
}
}
4.6.4前端
- 步骤一:修改apiclient.js,发送短信ajax操作
//发短信
sendSms : ( user )=> {
return axios.post('/web-service/sms', user )
}
- 步骤二:修改Register.vue页面,给“发送验证码”绑定点击事件 sendSmsFn
<button @click.prevent="sendSmsFn" >
发送验证码<span>5秒</span>
</button>
- 步骤三:修改Register.vue页面,编写sendSmsFn函数,建议采用 ajax…then()…catch 可以处理异常
sendSmsFn () {
this.$request.sendSms( this.user )
.then(( response )=>{
//发送短信的提示信息
this.userMsg.smsData = response.data
})
.catch(( error )=>{
//错误提示信息
alert( error.message )
})
}
- 步骤四:修改Register.vue页面,提供变量smsData
userMsg : { //错误提示数据
usernameData : "",
mobileData : "",
smsData : ""
}
- 步骤五:修改Register.vue页面,显示 smsData提示信息
<p :class="userMsg.smsData.code == 1 ? 'success' : 'error'">{{userMsg.smsData.message}} </p>
4.6.5倒计时
- 步骤一:提供3个变量,用于控制倒计时
btnDisabled : false, //倒计时控制变量
seconds : 5, //默认倒计时秒数
timer : null, //接收定时器,清除定时器
- 步骤二:在标签上面控制倒计时的显示
<button :disabled="btnDisabled" @click.prevent="sendSmsFn" >
发送验证码<span v-show="btnDisabled">{{seconds}}秒</span>
</button>
- 步骤三:发送短信后,开启倒计时控制
sendSmsFn () {
this.$request.sendSms( this.user )
.then(( response )=>{
//发送短信的提示信息
this.userMsg.smsData = response.data
//按钮不可用
this.btnDisabled = true;
//倒计时
this.timer = setInterval( ()=>{
if(this.seconds <= 1){
//结束
// 重置秒数
this.seconds = 5;
// 按钮可用
this.btnDisabled = false;
// 停止定时器
clearInterval(this.timer);
} else {
this.seconds --;
}
} , 1000);
})
.catch(( error )=>{
//错误提示信息
alert( error.message )
})
}
4.7用户注册
4.7.1接口
http://localhost:10010/web-service/user/register
4.7.2后端
*保存前需要再次进行服务端校验
-
用户名是否注册
-
手机号是否注册
-
验证码是否失效
-
验证码是否错误
-
密码需要使用 BCrypt进行加密
-
步骤一:修改UserService接口,添加register方法
/**
* 用户注册
* @param user
* @return
*/
public boolean register(User user) ;
- 步骤二:完善UserServiceImpl实现类
@Override
public boolean register(User user) {
//密码加密
String newPassword = BCrypt.hashpw(user.getPassword());
user.setPassword(newPassword);
//处理数据
user.setCreatedAt(new Date());
user.setUpdatedAt(user.getCreatedAt());
int insert = baseMapper.insert(user);
return insert == 1;
}
- 步骤三:修改UserController,添加register方法
/**
* 用户注册
* @param user
* @return
*/
@PostMapping("/register")
public BaseResult register(@RequestBody User user){
//服务端校验
User findUser = userService.findByUsername(user.getUsername());
if(findUser != null) {
return BaseResult.error("用户名已经存在");
}
findUser = userService.findByMobile(user.getMobile());
if(findUser != null) {
return BaseResult.error("电话号码已经存在");
}
//验证码
String code = stringRedisTemplate.opsForValue().get("sms_register" + user.getMobile());
//删除redis中的验证码
stringRedisTemplate.delete("sms_register" + user.getMobile());
if(code == null) {
return BaseResult.error("验证码失效");
}
if(!code.equals(user.getCode())) {
return BaseResult.error("验证码不正确");
}
//注册
boolean register = userService.register(user);
if(register) {
return BaseResult.ok("注册成功");
}
return BaseResult.error("注册失败");
}
4.7.3日期处理(可选)
- 编写 DateMetaObjectHandler 用于处理“创建时间”和“修改日期”
package com.czxy.changgou4.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@Component
public class DateMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createdAt", new Date(), metaObject);
this.setFieldValByName("updatedAt", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updatedAt", new Date(), metaObject);
}
}
- 完善User JavaBean,设置填充方式
@TableField(value="created_at",fill = FieldFill.INSERT)
private Date createdAt;
@TableField(value="updated_at",fill = FieldFill.INSERT_UPDATE)
private Date updatedAt;
4.7.4前端
- 步骤一:修改 api.js ,添加注册函数
//注册
register : ( user )=> {
return axios.post('/web-service/user/register', user )
}
- 步骤二:处理表单,验证码input绑定数据,提交按钮绑定事件
<li class="checkcode">
<label for="">验证码:</label>
<input type="text" name="checkcode" v-model="user.code" />
<button :disabled="btnDisabled" @click.prevent="sendSmsFn" >
发送验证码<span v-show="btnDisabled">{{seconds}}秒</span>
</button>
<p :class="userMsg.smsData.code == 1 ? 'success' : 'error'">{{userMsg.smsData.message}} </p>
</li>
<li>
<label for=""> </label>
<input type="checkbox" class="chb" checked="checked" /> 我已阅读并同意《用户注册协议》
</li>
<li>
<label for=""> </label>
<input type="submit" value="" @click.prevent="registerFn" class="login_btn" />
</li>
- 步骤三:完善data区域的user数据
user : { //表单封装数据
username : "", //用户名
mobile : "13699282444", //手机号
password : "", //密码
code : "" //验证码
},
- 步骤四:编写registerFn函数
async registerFn() {
let { data } = await this.$request.register( this.user )
if( data.code == 20000) {
//成功
this.$router.push('/login')
} else {
//失败--与发送验证码使用一个位置显示错误信息
this.userMsg.smsData = data
}
}
标签:畅购,username,return,用户注册,user,import,电商,com,changgou4 来源: https://blog.csdn.net/li13429743580/article/details/117820590