首頁 > 軟體

springboot與vue詳解實現簡訊傳送流程

2022-06-06 14:01:08

一、前期工作

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 = "li3122456997@163.com";
    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("***7@qq.com");
        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郵箱被騰訊被封了,我害怕試多了之後,網易郵箱也被封了!!!!


IT145.com E-mail:sddin#qq.com