基于SpringBoot的登录注册及找回密码有关的邮箱验证码操作
底下附git链接
介绍
基于SpringBoot的登录注册及找回密码有关的邮箱验证码操作
1整体思路
注册
通过输入的邮箱发送验证码,检验输入的验证码是否和后台生成的一致,若一致,将用户数据写入数据库,完成注册;
登录
通过输入用户名和密码与数据库中一条数据进行对比,若一致,则登陆成功
找回密码
首先校验数据库中是否存在用户名及其密码,存在时,再调用发送验证码进行比对的方式进行修改密码
2整体的结构图
3准备工程
开始QQ邮箱POP3/SMTP服务
登录QQ邮箱后,点击左上方的设置,选择账户
然后一直往下滑,看到POP3/SMTP服务,点击开启,应该会让帮定的手机号发个短信,然后会收到一个授权码,一定要好好保存,在appliction.properties配置中会用到。
创建一个SpringBoot项目工程
pom.xml中标签的全部依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.22</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
配置application.properties文件
server.port=8088#邮箱配置#平台地址,这里用的是qq邮箱,使用其他邮箱请更换spring.mail.host = #spring.mail.port=587#改成自己的邮箱spring.mail.username = XXXXXXXX@#发送短信后它给你的授权码 填写到这里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.Driverspring.datasource.url=jdbc:mysql://localhost:3306/email?useSSL=true&characterEncoding=utf-8&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456#配置mappermybatis.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;
4全部代码类
包含义
controller包是和前端对接的
mapper包中是接口
pojo是实体类
service层是逻辑代码
vo包是前端发送数据暂时保存
执行流程
使用postman发送请求,controller中会接受,然后调用service中的逻辑代码,service会调用的mapper中接口,mapper的对应的xml实现对数据库的各种操作。
User.java
@Data@AllArgsConstructor@NoArgsConstructorpublic class User {private String username;private String password;private String email;}
UserMapper.java
@Mapper@Repositorypublic 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);}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN""/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 userset password = #{password}where username = #{username} and email = #{email}</update><select id="queryByEmail" resultType="com.jiuqi.pojo.User">select *from userwhere email = #{email}</select><select id="selectUser" resultType="com.jiuqi.pojo.User">select *from userwhere username = #{username} and password = #{password}</select><select id="selectUserByUsername" resultType="com.jiuqi.pojo.User">select *from userwhere username= #{username} and email = #{email}</select></mapper>
MailService.java
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);}
MailServiceImpl.java
@Servicepublic class MailServiceImpl implements MailService {@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate UserMapper userMapper;//application.properties中已配置的值@Value("${spring.mail.username}")private String from;/*** 发送邮箱** @param email* @param session* @return*/@Overridepublic 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*/@Overridepublic 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*/@Overridepublic 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*/@Overridepublic boolean login(User user) {return userMapper.selectUser(user) != null ? true : false;}/*** 判断用户和邮箱是否存在** @param user* @return*/@Overridepublic String selectUserByUsername(User user) {User user1 = userMapper.selectUserByUsername(user);System.out.println(user1);return user1 != null ? "SUCCESS" : "ERROR";}@Overridepublic 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;}}@Overridepublic 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;}}
UserController.java
@Controllerpublic class UserController {@Autowiredprivate 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}")@ResponseBodypublic String sendEmail(@PathVariable String email, HttpSession httpSession) {boolean flag = mailService.sendMimeMail(email, httpSession);return flag ? "success" : "false";}/*** 注册* @param userVo* @param session* @return*/@PostMapping("/register")@ResponseBodypublic 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")@ResponseBodypublic String verify(User user) {return mailService.selectUserByUsername(user);}/*** 发送找回密码验证码* @param email* @param httpSession* @return*/@PostMapping("/sendEmail2/{email}")@ResponseBodypublic String sendEmail2(@PathVariable String email, HttpSession httpSession) {boolean flag = mailService.sendMimeMail2(email, httpSession);return flag ? "success" : "false";}/*** 注册* @param userVo* @param session* @return*/@PostMapping("/update")@ResponseBodypublic String update(UserVo userVo, HttpSession session) {boolean flag = mailService.updateUser(userVo, session);session.removeAttribute("code");return flag ? "success" : "false";}}
5使用postman测试
测试发送邮件
请求url:http://localhost:8088/sendEmail?email=1223334444@
请求方式:post
随机生成的验证码
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w8bnwFWb-1636107494747)(README.assets/image-1105173824158.png)]
发送的邮件验证码
测试注册
请求url:http://localhost:8088/register?username=王五&password=123456&email=1223334444@&code=496300
请求方式:post
code值是上面已发送的验证码
测试登录
请求url:http://localhost:8088/login?username=王五&password=123456
请求方式:post
测试找回密码
找回密码分为两步: 第一步校验用户名和邮箱是否都存在, 第二步若存在发送邮箱
校验用户名和邮箱
请求url:http://localhost:8088/verify?username=王五&email=1223334444@
请求方式: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 前端网页测试页面
6 Git
Git: lr_email