springboot使用qq邮箱进行注册登录的实现

设计依赖

springboot mybatis-plus json数据 MySQL8 lombok

先打开qq邮箱权限记住验证key

springboot使用qq邮箱进行注册登录的实现

先为登录方式,先进行qq邮箱验证码的发送 获取的code输入表单在输入信息进行注册 将qq邮箱号保存到数据库 登录进行验证qq邮箱号与密码

springboot使用qq邮箱进行注册登录的实现

pom

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xuda.msm</groupId>
<artifactId>emailmsm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>emailmsm</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<!--springboot的web启动依赖-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!--lombok-->
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<!--MySQL依赖-->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<!--mybatis-plus启动依赖-->
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<!--springboot启动依赖-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<!--meil发送启动依赖-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

配置文件


#appliction.properties配置
#邮箱配置
#平台地址
spring.mail.host=smtp.qq.com
#使用自己的邮箱
spring.mail.username=1375595011@qq.com
#授权码
spring.mail.password=个人权限key输入
spring.mail.properties.mail.smtp.ssl.enable=ture
#编码格式
spring.mail.default-encoding=UTF-8
#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/chat?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
#账号密码
spring.datasource.username=root
spring.datasource.password=123456
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.web.resources.static-locations=classpath:/static/

实体类

package com.xuda.msm.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:22
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private Integer id;
private String username;
private String email;
private String password;
}

mapper层

package com.xuda.msm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xuda.msm.entity.User;
import org.springframework.stereotype.Repository;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:25
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}

service层

package com.xuda.msm.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xuda.msm.entity.User;
import com.xuda.msm.vo.UserVo;
import javax.servlet.http.HttpSession;
public interface UserService extends IService<User> {
boolean sendMimeMail(String email, HttpSession session);
boolean registered(UserVo userVo, HttpSession session);
User loginIn(String email, String password,HttpSession session);
}

serviceImpl层

package com.xuda.msm.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuda.msm.entity.User;
import com.xuda.msm.mapper.UserMapper;
import com.xuda.msm.service.UserService;
import com.xuda.msm.service.ex.EmailInputErroeException;
import com.xuda.msm.service.ex.SendEmailFileException;
import com.xuda.msm.service.ex.UserNotFoundException;
import com.xuda.msm.service.ex.emailEmptyException;
import com.xuda.msm.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Random;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:29
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
//需要导入springboot的mail启动依赖
@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("邮箱验证码"); //主题
//生成随机数放入code中
String code = randomCode();
session.setAttribute("email",email);
session.setAttribute("code",code); //将随机数放入session中
mailmessage.setText("您收到的验证码是:"+code); //内容
mailmessage.setTo(email); //发给谁
mailmessage.setFrom(from); //自己的邮箱进行发送
mailSender.send(mailmessage); //进行发送
return true;
} catch (Exception e) {
throw new SendEmailFileException("验证码发送失败");
}
}
/**
* 进行验证码的校验
* @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();
if (email == null || email.isEmpty()) {
throw new emailEmptyException("验证码不能为空");
} else
if (!code.equals(userVo.getCode())){
throw new EmailInputErroeException("您输入的的验证码有误[" + userVo +"],请从新输入");
}
User user =new User();
//传值
user.setUsername(userVo.getUsername());
user.setPassword(userVo.getPassword());
user.setEmail(userVo.getEmail());
int insert = userMapper.insert(user);
System.out.println(insert);
//返回包装后的对象
return true;
}
/**
* 通过输入的email查询password,然后比较登录
* @param email
* @param password
* @return
*/
@Override
public User loginIn(String email, String password,HttpSession session) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("email",email)
.eq("password",password);
User user = userMapper.selectOne(queryWrapper);
if (user == null) {
throw new UserNotFoundException("用户数据不存在请进行注册");
}
session.setAttribute("user",user);
return user;
}
/**
* 生成随机数
* @return
*/
public String randomCode(){
StringBuffer str = new StringBuffer();
Random random = new Random();
for(int i=0;i<6;i++){
str.append(random.nextInt(10));
}
return str.toString();
}
}

service异常规划

package com.xuda.msm.service.ex;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:41
*/
public class ServiceException extends RuntimeException{
public ServiceException() {
super();
}
public ServiceException(String message) {
super(message);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(Throwable cause) {
super(cause);
}
protected ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.xuda.msm.service.ex;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 19:40
*/
public class UserNotFoundException extends ServiceException{
public UserNotFoundException() {
super();
}
public UserNotFoundException(String message) {
super(message);
}
public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public UserNotFoundException(Throwable cause) {
super(cause);
}
protected UserNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.xuda.msm.service.ex;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:42
*/
public class SendEmailFileException extends ServiceException{
public SendEmailFileException() {
super();
}
public SendEmailFileException(String message) {
super(message);
}
public SendEmailFileException(String message, Throwable cause) {
super(message, cause);
}
public SendEmailFileException(Throwable cause) {
super(cause);
}
protected SendEmailFileException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.xuda.msm.service.ex;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 19:30
*/
public class EmailInputErroeException extends ServiceException{
public EmailInputErroeException() {
super();
}
public EmailInputErroeException(String message) {
super(message);
}
public EmailInputErroeException(String message, Throwable cause) {
super(message, cause);
}
public EmailInputErroeException(Throwable cause) {
super(cause);
}
protected EmailInputErroeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.xuda.msm.service.ex;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 19:24
*/
public class emailEmptyException extends ServiceException{
public emailEmptyException() {
super();
}
public emailEmptyException(String message) {
super(message);
}
public emailEmptyException(String message, Throwable cause) {
super(message, cause);
}
public emailEmptyException(Throwable cause) {
super(cause);
}
protected emailEmptyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

controller控制层

package com.xuda.msm.controller;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:40
*/
import com.xuda.msm.service.ex.*;
import com.xuda.msm.utils.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**控制器基类*/
public class BaseController {
/** 操作成功的状态码 */
public static final int OK = 200;
@ExceptionHandler(ServiceException.class)
public JsonResult<Void> handleException(Throwable e) {
JsonResult<Void> result = new JsonResult<Void>(e);
if (e instanceof SendEmailFileException) {
result.setState(4000);
} else if (e instanceof UserNotFoundException) {
result.setState(4001);
} else if (e instanceof EmailInputErroeException) {
result.setState(4002);
} else if (e instanceof emailEmptyException) {
result.setState(4003);
}
return result;
}
}
package com.xuda.msm.controller;
import com.xuda.msm.entity.User;
import com.xuda.msm.service.UserService;
import com.xuda.msm.utils.JsonResult;
import com.xuda.msm.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:31
*/
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
@Autowired
private UserService userService;
@RequestMapping("sendEmail")
public JsonResult<Void> sendEmail(String email, HttpSession session) {
userService.sendMimeMail(email,session);
return new JsonResult<Void>(OK);
}
@RequestMapping("regist")
public JsonResult<Void> regist(UserVo userVo, HttpSession session) {
System.out.println(session.getAttribute("code"));
//这里进行简单的校验 ,建议可以进行升级放入redis
boolean isSuccess = userService.registered(userVo,session);
return new JsonResult<Void>(OK);
}
@RequestMapping("login")
public JsonResult<User> login(String email,String password,HttpSession session) {
//User data = userService.loginIn(email,password);
User user = userService.loginIn(email, password,session);
return new JsonResult<User>(OK,user);
}
}

json工具类

package com.xuda.msm.utils;
import java.io.Serializable;
/**
* @author :程序员徐大大
* @description:返回前端数据
* @date :2022-04-24 18:35
*/
public class JsonResult<E> implements Serializable {
/**状态码*/
private Integer state;
/**状态描述信息*/
private String message;
/**数据*/
private E data;
public JsonResult(Integer state) {
super();
this.state = state;
}
/** 出现异常时调用 */
public JsonResult(Throwable e) {
super();
// 获取异常对象中的异常信息
this.message = e.getMessage();
}
public JsonResult(Integer state, E data) {
super();
this.state = state;
this.data = data;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}

vo类

package com.xuda.msm.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 18:27
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {
private String username;
private String password;
private String email;
//验证码
private String code;
}

配置类(可以不加,我这里是为了记录)

package com.xuda.msm.config;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 20:38
*/
@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoginHandlerInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// log.info("session+=》{}",request.getSession().getAttribute("user"));
//登录成功后,应该有用户得session
Object loginuser = request.getSession().getAttribute("user");
if (loginuser != null) {
request.setAttribute("loginmsg", "没有权限请先登录");
request.getRequestDispatcher("/login.html").forward(request, response);
return false;
} else {
return true;
}
}
}
package com.xuda.msm.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author :程序员徐大大
* @description:TODO
* @date :2022-04-24 20:37
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/login");
registry.addViewController("login").setViewName("login");
registry.addViewController("login.html").setViewName("login");
registry.addViewController("regist").setViewName("regest");
registry.addViewController("sendEmail");
registry.addViewController("addEmp").setViewName("addEmp");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/regist","/user/login","/css/**","/static/**","/js/**","/img/**","/user/regist","/login","regest.html","/login.html");
}
}

发送验证码

springboot使用qq邮箱进行注册登录的实现

收到验证码

springboot使用qq邮箱进行注册登录的实现

注册成功

springboot使用qq邮箱进行注册登录的实现

登录成功

springboot使用qq邮箱进行注册登录的实现

数据库信息添加成功

springboot使用qq邮箱进行注册登录的实现