底下附git链接
基于SpringBoot的登录注册及找回密码有关的邮箱验证码操作
通过输入的邮箱发送验证码,检验输入的验证码是否和后台生成的一致,若一致,将用户数据写入数据库,完成注册;
通过输入用户名和密码与数据库中一条数据进行对比,若一致,则登陆成功
首先校验数据库中是否存在用户名及其密码,存在时,再调用发送验证码进行比对的方式进行修改密码
登录QQ邮箱后,点击左上方的设置,选择账户
然后一直往下滑,看到POP3/SMTP服务,点击开启,应该会让帮定的手机号发个短信,然后会收到一个授权码,一定要好好保存,在appliction.properties配置中会用到。
pom.xml中标签的全部依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.22version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
配置application.properties文件
server.port=8088
#邮箱配置
#平台地址,这里用的是qq邮箱,使用其他邮箱请更换
spring.mail.host = smtp.qq.com
#spring.mail.port=587
#改成自己的邮箱
spring.mail.username = [email protected]
#发送短信后它给你的授权码 填写到这里
spring.mail.password = XXXXXXXXXXXXXXXXX
#这东西不用改
spring.mail.properties.mail.smtp.ssl.enable=true
##编码格式
spring.mail.default-encoding=UTF-8
#数据库相关配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/email?useSSL=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
#配置mapper
mybatis.mapper-locations=classpath:mapper/*.xml
CREATE DATABASE email;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
controller包是和前端对接的
mapper包中是接口
pojo是实体类
service层是逻辑代码
vo包是前端发送数据暂时保存
使用postman发送请求,controller中会接受,然后调用service中的逻辑代码,service会调用的mapper中接口,mapper的对应的xml实现对数据库的各种操作。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String username;
private String password;
private String email;
}
@Mapper
@Repository
public interface UserMapper {
/**
* 注册,插入数据
* @param user
*/
void insertUser(User user);
/**
* 根据邮箱查询
* @param email
* @return
*/
User queryByEmail(String email);
/**
* 登录
* @param user
* @return
*/
User selectUser(User user);
/**
* 检验username和email是否存在
* @param user
* @return
*/
User selectUserByUsername(User user);
void updateUser(User user);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jiuqi.mapper.UserMapper">
<insert id="insertUser" parameterType="com.jiuqi.pojo.User">
insert into user (username,password,email)
values (#{username},#{password},#{email})
insert>
<update id="updateUser">
update user
set password = #{password}
where username = #{username} and email = #{email}
update>
<select id="queryByEmail" resultType="com.jiuqi.pojo.User">
select *
from user
where email = #{email}
select>
<select id="selectUser" resultType="com.jiuqi.pojo.User">
select *
from user
where username = #{username} and password = #{password}
select>
<select id="selectUserByUsername" resultType="com.jiuqi.pojo.User">
select *
from user
where username= #{username} and email = #{email}
select>
mapper>
public interface MailService {
/**
* 给前端输入的邮箱,发送验证码
*
* @param email
* @param session
* @return
*/
boolean sendMimeMail(String email, HttpSession session);
/**
* 随机生成6位数的验证码
*
* @return String code
*/
String randomCode();
/**
* 检验验证码是否一致
*
* @param userVo
* @param session
* @return
*/
boolean registered(UserVo userVo, HttpSession session);
/**
* 通过输入email查询password,然后比较两个password,如果一样,登录成功
*
* @param email
* @param password
* @return
*/
boolean loginIn(String email, String password);
/**
* 登录
* 检验用户名和密码
*
* @param user
* @return
*/
boolean login(User user);
/**
* 校验用户名和邮箱
* @param user
* @return
*/
String selectUserByUsername(User user);
/**
* 通过邮箱找回密码
* @param email
* @param session
* @return
*/
boolean sendMimeMail2(String email, HttpSession session);
/**
* 校验验证码并重置更改密码
* @param userVo
* @param session
* @return
*/
boolean updateUser(UserVo userVo, HttpSession session);
}
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private UserMapper userMapper;
//application.properties中已配置的值
@Value("${spring.mail.username}")
private String from;
/**
* 发送邮箱
*
* @param email
* @param session
* @return
*/
@Override
public boolean sendMimeMail(String email, HttpSession session) {
try {
//邮箱信息
SimpleMailMessage mailMessage = new SimpleMailMessage();
//主题
mailMessage.setSubject("lr_email注册");
//生成随机数
String code = randomCode();
System.out.println("code = " + code);
//将随机数放置到session中
session.setAttribute("email", email);
session.setAttribute("code", code);
//内容
mailMessage.setText("lr_email注册的验证码是:" + code);
//发给谁
mailMessage.setTo(email);
//你自己的邮箱
mailMessage.setFrom(from);
//发送
mailSender.send(mailMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 6位数验证码
*
* @return
*/
@Override
public String randomCode() {
StringBuilder str = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
/**
* 检验验证码是否一致
*
* @param userVo
* @param session
* @return
*/
@Override
public boolean registered(UserVo userVo, HttpSession session) {
//获取session中的验证信息
String email = (String) session.getAttribute("email");
String code = (String) session.getAttribute("code");
//获取表单中的提交的验证信息
String voCode = userVo.getCode();
//如果email数据为空,或者不一致,注册失败
if (email == null || email.isEmpty()) {
return false;
} else if (!voCode.equals(code)) {
return false;
}
//保存数据
User user = UserVoToUser.toUser(userVo);
//将数据写入数据库
userMapper.insertUser(user);
//跳转成功页面
return true;
}
/**
* 登录
*
* @param user
* @return
*/
@Override
public boolean login(User user) {
return userMapper.selectUser(user) != null ? true : false;
}
/**
* 判断用户和邮箱是否存在
*
* @param user
* @return
*/
@Override
public String selectUserByUsername(User user) {
User user1 = userMapper.selectUserByUsername(user);
System.out.println(user1);
return user1 != null ? "SUCCESS" : "ERROR";
}
@Override
public boolean sendMimeMail2(String email, HttpSession session) {
try {
//邮箱信息
SimpleMailMessage mailMessage = new SimpleMailMessage();
//主题
mailMessage.setSubject("lr_email找回密码");
//生成随机数
String code = randomCode();
System.out.println("code = " + code);
//将随机数放置到session中
session.setAttribute("email", email);
session.setAttribute("code", code);
//内容
mailMessage.setText("lr_email找回密码的验证码是:" + code);
//发给谁
mailMessage.setTo(email);
//你自己的邮箱
mailMessage.setFrom(from);
//发送
mailSender.send(mailMessage);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean updateUser(UserVo userVo, HttpSession session) {
//获取session中的验证信息
String email = (String) session.getAttribute("email");
String code = (String) session.getAttribute("code");
//获取表单中的提交的验证信息
String voCode = userVo.getCode();
//如果email数据为空,或者不一致,注册失败
if (email == null || email.isEmpty()) {
return false;
} else if (!voCode.equals(code)) {
return false;
}
//保存数据
User user = UserVoToUser.toUser(userVo);
//将数据写入数据库
userMapper.updateUser(user);
//跳转成功页面
return true;
}
}
@Controller
public class UserController {
@Autowired
private MailService mailService;
@RequestMapping({"/", "/index"})
public String index() {
return "login";
}
@RequestMapping("/toReg")
public String toReg() {
return "register";
}
@RequestMapping("/toPass")
public String toPass() {
return "password";
}
/**
* 发送注册验证码
* @param email
* @param httpSession
* @return
*/
@PostMapping("/sendEmail/{email}")
@ResponseBody
public String sendEmail(@PathVariable String email, HttpSession httpSession) {
boolean flag = mailService.sendMimeMail(email, httpSession);
return flag ? "success" : "false";
}
/**
* 注册
* @param userVo
* @param session
* @return
*/
@PostMapping("/register")
@ResponseBody
public String register(UserVo userVo, HttpSession session) {
boolean flag = mailService.registered(userVo, session);
session.removeAttribute("code");
return flag ? "success" : "false";
}
@PostMapping("/login")
public String login(User user) {
boolean flag = mailService.login(user);
return flag ? "success" : "false";
}
@PostMapping("/verify")
@ResponseBody
public String verify(User user) {
return mailService.selectUserByUsername(user);
}
/**
* 发送找回密码验证码
* @param email
* @param httpSession
* @return
*/
@PostMapping("/sendEmail2/{email}")
@ResponseBody
public String sendEmail2(@PathVariable String email, HttpSession httpSession) {
boolean flag = mailService.sendMimeMail2(email, httpSession);
return flag ? "success" : "false";
}
/**
* 注册
* @param userVo
* @param session
* @return
*/
@PostMapping("/update")
@ResponseBody
public String update(UserVo userVo, HttpSession session) {
boolean flag = mailService.updateUser(userVo, session);
session.removeAttribute("code");
return flag ? "success" : "false";
}
}
请求url:http://localhost:8088/[email protected]
请求方式: post
随机生成的验证码
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w8bnwFWb-1636107494747)(README.assets/image-20211105173824158.png)]
发送的邮件验证码
请求url:http://localhost:8088/register?username=王五[email protected]&code=496300
请求方式: post
code值是上面已发送的验证码
请求url:http://localhost:8088/login?username=王五&password=123456
请求方式: post
找回密码分为两步: 第一步校验用户名和邮箱是否都存在, 第二步若存在发送邮箱
请求url:http://localhost:8088/verify?username=王五[email protected]
请求方式: post
校验到用户名和密码同时存在, 发送邮箱
邮箱中的验证码和idea中的验证码
注意: 在找回密码这一步骤中, 如果没有校验到数据中用户名和邮箱, 是不可以发送邮箱的,这一步骤主要在ajax中体现
<script>
/**
* 校验用户名和邮箱
* 发送验证码
*/
function sendMessage() {
$.ajax({
type: "post",
url: "/verify?username=" + $("#username").val() + "&email=" + $("#email").val(),
success(data) {
if (data == "SUCCESS") {
console.log("校验成功 date = " + data)
$.ajax({
type: "post",
url: "/sendEmail2/" + $("#email").val(),
});
$("#message").text("邮件发送成功, 请注意查收").css("color", "green");
} else if (data = "ERROR"){
$("#message").text("邮箱或密码填写错误").css("color", "red");
console.log("校验失败 date = " + data)
}
},error() {
console.log("错误!")
}
});
}
6 前端网页测试页面
Git: lr_email