springboot與vue詳解實現短信發送流程

一、前期工作

1.開啟郵箱服務

開啟郵箱的POP3/SMTP服務(這裡以qq郵箱為例,網易等都是一樣的)

2.導入依賴

在springboot項目中導入以下依賴:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

3.配置application.yaml文件

# 郵箱設置
spring:
 mail:
   host: smtp.163.com //如果是qq的郵箱就是smtp.qq.com
   password: 開啟pop3生成的一個字符串密碼
   username: 自己的郵箱地址,是什麼郵箱後綴就是什麼。
   port:
   default-encoding: UTF-8
   protocol: smtp
   properties:
     mail.smtp.auth: true
     mail.smtp.starttls.enable: true
     mail.smtp.starttls.required: true
     mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
     mail.smtp.socketFactory.fallback: false
     mail:
       smtp:
         ssl:
           enable: true
 mvc:
   pathmatch:
     matching-strategy: ant_path_matcher
 datasource: # jdbc數據庫設置
   druid:
     password: sql密碼
     username: sql用戶
     url: jdbc:mysql://localhost:3306/sys?charsetEncoding=utf-8&useSSL=false
     driver-class-name: com.mysql.jdbc.Driver
     db-type: com.alibaba.druid.pool.DruidDataSource
mybatis: #mybatis的配置
 type-aliases-package: com.cheng.springcolud.pojo
 config-location: classpath:mybatis/mybatis-config.xml
 mapper-locations: classpath:mybatis/mapper/*.xml

二、實現流程

1.導入數據庫

/*
 Navicat Premium Data Transfer
 Source Server         : likai
 Source Server Type    : MySQL
 Source Server Version : 50719
 Source Host           : localhost:3306
 Source Schema         : sys
 Target Server Type    : MySQL
 Target Server Version : 50719
 File Encoding         : 65001
 Date: 04/06/2022 14:08:29
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for useremaillogintable
-- ----------------------------
DROP TABLE IF EXISTS `useremaillogintable`;
CREATE TABLE `useremaillogintable`  (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `VerificationCode` int(20) NULL DEFAULT NULL,
  `createTime` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

2.後端實現

編寫實體類

代碼如下(示例):

@Data
@NoArgsConstructor
@ToString
public class EmailVerification {
    private int id;
    private String email; //需要發送的郵箱
    private Integer verificationCode;//驗證碼
    private Date createTime;
    public EmailVerification(String email, Integer verificationCode) {
        this.email = email;
        this.verificationCode = verificationCode;
    }
}

編寫工具類ResultVo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultVO {
    private int code;//相應給前端的狀態碼
    private String msg;//相應給前端的提示信息
    private Object data;//響應給前端的數據
}

編寫dao層接口

Mapper
@Repository
public interface EmailVerificationDao {
    /*將短信驗證碼和個人郵箱保存到數據庫中*/
    public Boolean getEmailVerificationCode(String email,Integer verificationCode);
    /*校驗短信信息*/
    public List<EmailVerification> checkEmailVerificationCode(String email,Integer verificationCode);
    /*查詢所有的用戶*/
    public List<EmailVerification> queryEmailVerificationInfo();
}

配置dao層接口的數據庫操作

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cheng.dao.EmailVerificationDao">
    <insert id="getEmailVerificationCode">
        insert into sys.useremaillogintable(email, VerificationCode,createTime) VALUES (#{email},#{verificationCode},NOW())
    </insert>
    <select id="checkEmailVerificationCode" resultType="com.cheng.bean.EmailVerification">
        select * from sys.useremaillogintable where email=#{email} and VerificationCode=#{verificationCode}
    </select>
    <select id="queryEmailVerificationInfo" resultType="com.cheng.bean.EmailVerification" >
        select * from sys.useremaillogintable;
    </select>
</mapper>

編寫service層接口

public interface EmailVerificationCodeService {
    public boolean getEmailVerificationCode(String email,Integer verificationCode);
    public ResultVO checkEmailVerificationCode(String email, Integer verificationCode);
    public ResultVO queryEmailVerificationInfo();
    public ResultVO sendEmailVerificationCode(String email);
}

代碼講解: getEmailVerificationCod方法是將數據(驗證碼和郵箱地址)放入數據庫當中,checkEmailVerificationCode是用來校驗其驗證碼和郵箱是否是正確,·queryEmailVerificationInfo·是用來查詢所有的數據,在這裡我新加瞭個接口叫做senEmailVerificationCode就是單純用來發送短信信息的,隻有一個參數,他是沒有相對應的數據庫操作的。

編寫service層的實現方法

@Service
public class EmailVerificationCodeServiceImpl implements EmailVerificationCodeService{
    @Autowired
    EmailVerificationDao emailVerificationDao;
    private final static String EmailFrom = "[email protected]";
    private final JavaMailSenderImpl javaMailSender;
    public int code = (int)(Math.random() * 9000 + 1000);
    public EmailVerificationCodeServiceImpl(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }
    @Override
    public boolean getEmailVerificationCode(String email,Integer verificationCode) {
            verificationCode =code;
            return emailVerificationDao.getEmailVerificationCode(email,verificationCode);
    }
    @Override
    public ResultVO checkEmailVerificationCode(String email, Integer verificationCode) {
        List<EmailVerification> emailVerifications = emailVerificationDao.checkEmailVerificationCode(email, verificationCode);
        if (emailVerifications.size()>0){
            return new ResultVO(1001,"校驗成功",emailVerifications);
        }else {
            return new ResultVO(1002,"校驗失敗",null);
        }
    }
    @Override
    public ResultVO queryEmailVerificationInfo() {
        List<EmailVerification> emailVerifications = emailVerificationDao.queryEmailVerificationInfo();
        return new ResultVO(1001,"success",emailVerifications);
    }
    @Override
    public ResultVO sendEmailVerificationCode(String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("驗證碼");
        simpleMailMessage.setTo(email);//收件人
        simpleMailMessage.setText("驗證碼為:"+code);
        simpleMailMessage.setFrom("******@163.com"); //發送的人(寫自己的)
        javaMailSender.send(simpleMailMessage);
        boolean emailVerificationCode = getEmailVerificationCode(email, code);
        if (emailVerificationCode){
            return new ResultVO(1001,"發送成功!","驗證碼為:"+code);
        }else {
            return new ResultVO(1002,"發送失敗",null);
        }
    }
}

代碼講解: 這裡就一個註重點,就是sendEmailVerificationCode的實現,我將隨機數給提出出來,因為getEmailVerificationCode也是需要將隨機數給保存到數據庫當中的,為瞭避免兩者的驗證碼不同,我就給其提取出來,以確保其一致性,在sendEmailVerificationCode的實現,我在裡面調用瞭getEmailVerificationCode方法,這樣可以保證其郵箱地址的一致性。在通過判斷,驗證短信是否發送成功。

實現controller層

@RestController
@CrossOrigin//允許回復前端數據,跨域請求允許
public class EmailController {
    @Autowired
    EmailVerificationCodeService emailVerificationCodeService;
    @Autowired
    InfoTimingSendServiceImpl infoTimingSendService;
    @GetMapping("send")
    public ResultVO sendMail(@RequestParam(value = "email") String email){
        return emailVerificationCodeService.sendEmailVerificationCode(email);
    }
    @GetMapping("checkEmailVerification")
    public ResultVO checkEmail(@RequestParam(value = "email") String email, @RequestParam(value = "verificationCode") Integer verificationCode){
        ResultVO resultVO = emailVerificationCodeService.checkEmailVerificationCode(email, verificationCode);
        return resultVO;
    }
    @GetMapping("queryAll")
    public ResultVO queryAll(){
        ResultVO resultVO = emailVerificationCodeService.queryEmailVerificationInfo();
        return resultVO;
    }
}

註意: 需要加入@CrossOrigin註解,這個註解是可以解決跨域問題,這個項目我寫的是前後端分離的,所以這裡需要加入這個在註解,為後面通過axios來獲取數據做準備

Test代碼

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    EmailVerificationCodeService emailVerificationCodeService;
    @Autowired
    InfoTimingSendServiceImpl infoTimingSendService;
    @Test
    void contextLoads() {
        ResultVO aBoolean = emailVerificationCodeService.checkEmailVerificationCode("***@qq.com", 8001);
        System.out.println(aBoolean);
    }
    @Test
    void infoSendTest(){
        infoTimingSendService.infoSend();
    }
    @Test
    void send(){
        final ResultVO resultVO = emailVerificationCodeService.sendEmailVerificationCode("***[email protected]");
        System.out.println(resultVO);
    }
}

前端頁面的實現

註意: 在前端頁面我使用瞭bootstrap框架,vue,axios,所以需要當如相對應的包

註冊頁面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" href="css/bootstrap.min.css" rel="external nofollow"  />	
		<script src="js/jquery.min.js"></script>
		<script src="js/bootstrap.min.js"></script>
		<script src="js/vue.js"></script>
		<style>
		</style>
		</head>
	<body style="background: linear-gradient(to right,#7b4397,#dc2430);">
		<div id="container">
		<div class="container-fluid" style="color: white;">
		  <form class="form-horizontal" role="form" style="padding-left: 500px;  margin-top: 200px;">
				<fieldset>
		    <div class="form-group">
						<p style="font-size: 30px;margin-left: 250px; margin-right: 240px;color:white">登錄</p>
						<hr style="width: 400px;margin-left: 90px; background-color: red;" />
						<p style="font-size: 15px;margin-left: 190px; margin-right: 240px;color:red" id="tips">{{tips}} &nbsp;</p>
		      <label for="inputEmail3" class="col-sm-2 control-label">郵箱</label>
		      <div class="col-sm-3">
		        <input type="email" v-model="email" class="form-control" id="inputEmail3" placeholder="Email">
		      </div>
		    </div>
		    <div class="form-group">
		      <label for="inputPassword3" class="col-sm-2 control-label">驗證碼</label>
		      <div class="col-sm-3">
		        <input v-if="verification_send" type="text" v-model="verification" class="form-control" id="inputPassword3" placeholder="VerificationCode">
						<input v-else type="text"  class="form-control" v-model="verification" id="inputPassword3" placeholder="5分鐘內有效,60s後可重新發送" />
		      </div>
		    </div>
		    <div class="form-group">
		      <div class="col-sm-offset-2 col-sm-3">
		        <a type="submit" class="btn btn-default" @click="sign">Sign in</a>
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<a v-if="time==60" class="btn btn-default" @click="send" class="btn btn-default">{{info}}</a>
						<a v-if="time<60&&time>=0"  class="btn btn-default" @click="send" class="btn btn-default" style="pointer-events: none;">{{"wait"+time+"s"}}</a>
						<a v-if="time<0" class="btn btn-default" @click="send" class="btn btn-default">{{info}}</a>
		      </div>
		    </div>
		  </form>
		</div>
		</div>
		<script src="js/axios.min.js"></script>
		<script type="text/javascript">
			var baseUrl="http://localhost:8080/";
			var vm = new Vue({
				el:'#container',
				data:{
					info: 'send out',
					time: 60,
					verification_send: true,
					verification:"",
					email:"",
					tips:""
				},
				methods:{
					send:function (){
						var url1 = baseUrl+"/send";
						axios.get(url1,{params:{email:vm.email}}).then((res)=>{
							console.log(res);
							if(res.data.code==1001){
								vm.tips="發送成功!";
							}else{
								vm.tips="發送失敗!請稍後再試"
							}
						});
						setInterval(function(){
							if(vm.time==60){
								vm.time--;
								this.time=vm.time;
								vm.verification_send = false;
								console.log(vm.time);
							}else if(vm.time==0){
								clearInterval(vm.time)
								vm.verification_send = true;
							}else{
								vm.time--;
								console.log(vm.time);
							}
						},1000);
					},
					sign:function(){
						var url = baseUrl+"/checkEmailVerification";
						if(vm.email==""&&vm.verification==""){
							vm.tips="請輸入驗證碼或郵箱!";
						}else{
							axios.get(url,{params:{email:vm.email,verificationCode:vm.verification}})
							.then((res)=>{
								var vo = res.data;
								if(vo.code==1001){
									vm.tips="登錄成功";
									setInterval(function(){
										window.location.href="index.html" rel="external nofollow" ;
									},3000);
								}else{
									vm.tips="請輸入正確的驗證碼!";
								}
							})
						}
					}
					}
			})
		</script>
	</body>
</html>

講解:在這裡,在發送按鈕上面加入瞭時間倒計時,當我點擊的時候,會倒計時1minute,在這期間,發送按鈕是無法被點擊的!這就避免瞭多次放松

index.htm

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<center style="margin-top: 50px;">
			<p>歡迎你:</p>
			<p>登錄成功!</p>
		</center>
	</body>
</html>

頁面效果:

效果圖:

運行截圖+sql圖

總結

以上就是springboot+vue實現後端和前端短信發送的所有代碼,其實像短信發送瞭兩次,以第二次為準的話,我們可以實現一個數據庫內容的修改,當其發送瞭兩次,我們就以第二次為準!希望對大傢有所幫助,這裡前端的驗證其實是不夠完善的,我沒有去加入郵箱的驗證。是因為我的QQ郵箱被騰訊被封瞭,我害怕試多瞭之後,網易郵箱也被封瞭!!!!😭😭

配張QQ郵箱被封的截圖鎮樓

到此這篇關於springboot與vue詳解實現短信發送流程的文章就介紹到這瞭,更多相關springboot短信發送內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: