您的当前位置:首页正文

基于 SpringBoot 实现QQ邮箱验证码注册功能

2024-11-27 来源:个人技术集锦

开启邮箱服务

(1)首先打开QQ邮箱,点击设置并来到账号页面

(2)找到并开通以下的邮件协议服务,而且服务开启也较为简单,需要我们发送一个短信到指定的号码,开启后平台会提供一个授权码,一定要记住这个授权码,发邮件的时候需要这个。

导入项目依赖

发送邮件的核心依赖是 mail ,由于该项目还涉及其他依赖就全都导进来了。

    <dependencies>
        <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>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</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>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>3.0.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</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-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.16</version>
        </dependency>
    </dependencies>

配置 yml 文件

spring:
  application:
    name: demo
    # 配置数据库
  datasource:
    url: jdbc:mysql://localhost:3306/user?useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password:
    driver-class-name: com.mysql.cj.jdbc.Driver
  mail:
    # smtp服务主机  qq邮箱则为smtp.qq.com; 163邮箱是smtp.163.com
    host: smtp.qq.com
    # 服务协议
    protocol: smtp
    # 编码集
    default-encoding: UTF-8
    # 发送邮件的账户
    username: xxx@qq.com
    # 授权码
    password: xxx
    # 发送人昵称
    nickname: xxx

    test-connection: true
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

        其中的 username 是你第一步中操作的邮箱账号,nickname 是接收者收到邮件中显示的发件人。

        host 是根据服务主机区分,网易邮箱是 smtp.163.com, qq邮箱是 smtp.qq.com。其它的默认即可。

创建数据库文件

CREATE TABLE `user` (
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `mailbox` varchar(20) NOT NULL,
  `id` int(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String username;
    private String password;
    private int id;
    private String mailbox;
}

Dao 层

@Mapper
public interface UserDaoImpl {
    @Select("select * from user.user where username = #{username} and password = #{password}")
    User queryUser(@Param("username") String username, @Param("password")  String password);

    @Select("select * from user.user where username = #{username}")
    User selectByUsername(String username);

    @Insert("insert into user.user(username,password,mailbox) values (#{username},#{password},#{mailbox})")
    void AddUser(@Param("username") String username, @Param("password") String password, @Param("mailbox") String mailbox);
}
@Repository
public class UserDao implements UserDaoImpl{
    @Autowired
    private UserDaoImpl userDaoImpl;

    @Override
    public User queryUser(String username, String password) {
        return userDaoImpl.queryUser(username,password);
    }

    @Override
    public User selectByUsername(String username){
        return userDaoImpl.selectByUsername(username);
    }

    @Override
    public void AddUser(String username, String password, String mailbox) {
        userDaoImpl.AddUser(username,password,mailbox);
    }
}

Service 层

public interface UserServiceImpl {
    User queryUser(String username, String password);
    User selectByUsername(String username);
    void AddUser(String username, String password, String mailbox);
}
@Service
public class UserService implements UserServiceImpl{
    @Autowired
    private UserDao userDao;

    @Override
    public User queryUser(String username, String password) {
        return userDao.queryUser(username, password);
    }

    @Override
    public User selectByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    @Override
    public void AddUser(String username, String password, String mailbox) {
        userDao.AddUser(username, password, mailbox);
    }
}

Controller 层

登入
@RequestMapping("/User")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    // 判断登入
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Boolean login(String name, String password, HttpSession session){
        if (!StringUtils.hasLength(name) || !StringUtils.hasLength(password)){
            System.out.println(false);
            return false;
        }
        if (userService.selectByUsername(name) != null&&
                userService.queryUser(name,password)!= null){
            session.setAttribute("userName", name);
            System.out.println(true);
            return true;
        }
        System.out.println(false);
        return false;
    }
    // 获取用户名
    @RequestMapping("/getLoginUser")
    public String getLoginUser(HttpSession session){
        if(session.getAttribute("userName")!=null){
            return (String)session.getAttribute("userName");
        }
        return "";
    }

}
注册
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private UserService userService;
    // 这个是 mail 依赖提供给的发送邮件的接口
    @Autowired
    private JavaMailSender mailSender;
    // 获取发件人邮箱
    @Value("${spring.mail.username}")
    private String sender;
    // 获取发件人昵称
    @Value("${spring.mail.nickname}")
    private String nickname;
    // 获取验证码
    @GetMapping("/code")
    public boolean getCode(@RequestParam("email")String email,HttpSession session){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(nickname + '<' + sender + '>');
        message.setTo(email);
        message.setSubject("欢迎访问东方");

        // 使用 hutool-all 生成 6 位随机数验证码
        String code = RandomUtil.randomNumbers(6);
        session.setAttribute("email", code);
        String content = "【验证码】您的验证码为:" + code + " 。 3分钟内有效,请勿泄露和转发。如非本人操作,请忽略此短信。\n\n\n";
        message.setText(content);
        mailSender.send(message);
        return true;
    }
    // 注册账号
    @PostMapping("/SignIn")
    public boolean UserSignIn(@RequestParam("userName")String userName,
                              @RequestParam("password")String password,
                              @RequestParam("mailbox")String mailbox,
                              @RequestParam("Verification")String Verification,
                              HttpSession session){
        // 通过 session 获取验证码
        String SignInEmail = (String)session.getAttribute("email");
        // 如果用户名存在返回 false
        if(userService.selectByUsername(userName)!= null)return false;
        // 验证码为空返回 false
        if(SignInEmail == null) return false;
        // 验证码对得上才进行插入操作,并返回 true
        if(SignInEmail.equals(Verification)){
            userService.AddUser(userName,password,mailbox);
            return true;
        }
        return false;
    }

前端

login.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登入</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/login.css">
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body>
<div class="container-login">
    <div class="container-pic">
        <img src="pic/computer.png" width="350px">
    </div>
    <div class="login-dialog">
        <h3>登陆</h3>
        <div class="row">
            <span>用户名</span>
            <input type="text" name="userName" id="userName" class="form-control">
        </div>
        <div class="row">
            <span>密码</span>
            <input type="password" name="password" id="password" class="form-control">
        </div>
        <div class="row">
            <button type="button" class="btn btn-info btn-lg" onclick="login()">登录</button>
        </div>
        <div class="row">
            <button type="button" class="btn btn-info btn-lg" onclick="Signin()">注册</button>
        </div>
    </div>
</div>
<script src="js/jquery.min.js"></script>
<script>
    function login() {
        $.ajax({
            type: "post",
            url: "/User/login",
            data: {
                name: $("#userName").val(),
                password: $("#password").val()
            },
            success: function(result){
                if(result){
                    //登录成功
                    location.href = "index.html";
                }else{
                    alert("账号或密码错误");
                }
            }
        });
    }
</script>

<script>
    function Signin(){
        window.location.href="Signin.html";
    }
</script>

</body>

</html>

Signin.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/login.css">
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body>
<div class="container-login">
    <div class="container-pic">
        <img src="pic/computer.png" width="350px">
    </div>
    <div class="login-dialog">
        <h3>注册</h3>
        <div class="row">
            <span>用户名</span>
            <input type="text" name="userName" id="userName" class="form-control">
        </div>

        <div class="row">
            <span>密码</span>
            <input type="password" name="password" id="password" class="form-control">
        </div>

        <div class="row">
            <span>邮箱</span>
            <input type="mailbox" name="mailbox" id="mailbox" class="form-control">
        </div>

        <input type="button" value="发送验证码" id="email" onclick="jump()">

        <div class="row">
            <span>验证码</span>
            <input type="Verification" name="Verification" id="Verification" class="form-control">
        </div>
        <div class="row">
            <button type="button" class="btn btn-info btn-lg" onclick="SignIn()">注册</button>
        </div>
    </div>
</div>

<script src="js/jquery.min.js"></script>

<script>
        function SignIn() {
            $.ajax({
                type: "post",
                url: "/email/SignIn",
                data: {
                    userName: $("#userName").val(),
                    password: $("#password").val(),
                    mailbox: $("#mailbox").val(),
                    Verification: $("#Verification").val(),
                },
                success: function(result){
                    if(result){
                        alert("注册成功");
                        location.href = "login.html";
                    }else{
                        alert("注册失败");
                    }
                }
            });
            }
</script>


<script>
    function jump() {
        $.ajax({
            type: "get",
            url: "/email/code",
            data: {
                email: $("#mailbox").val()
            },
            success: function (result) {
                if (result) alert("验证码发送成功");
            }
        });
    }
</script>

</body>

</html>

显示全文