一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

2021-12-22 13:01AimerDaniil Java教程

現(xiàn)在很多的網(wǎng)站都提供有用戶注冊功能,當(dāng)我們注冊成功之后就會收到封注冊網(wǎng)站的郵件,郵件里包含了我們的注冊的用戶名和密碼及激活賬戶的超鏈接等信息,這篇文章主要給大家介紹了關(guān)于java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活

一、前期準(zhǔn)備

1、準(zhǔn)備兩個郵箱賬號(一個發(fā)郵件,一個收郵件)

1.1)登錄需要發(fā)送郵件的QQ郵箱,找到設(shè)置項

1.2)然后在賬戶欄下,找到(POP3/SMTP)服務(wù)協(xié)議

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

1.3)生成授權(quán)碼

下拉找到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù) 打開 POP3/SMTP服務(wù),并記住授權(quán)碼,后面發(fā)送郵件時會用到授權(quán)碼

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

 

二、項目

1、準(zhǔn)備用戶數(shù)據(jù)表

CREATE TABLE `user` (
 `userid` int(20) NOT NULL AUTO_INCREMENT COMMENT '用戶編號',
 `name` varchar(16) DEFAULT NULL COMMENT '姓名',
 `password` varchar(16) DEFAULT '' COMMENT '密碼',
 `sex` varchar(12) DEFAULT NULL COMMENT '性別',
 `idno` varchar(18) DEFAULT NULL COMMENT '身份證號碼',
 `tel` int(11) DEFAULT NULL COMMENT '手機(jī)號碼',
 `userVerificationCode` int(6) DEFAULT NULL COMMENT '驗證碼',
 `userActivationCode` varchar(255) DEFAULT NULL COMMENT '激活碼',
 `eml` varchar(255) DEFAULT '' COMMENT '郵箱',
 `vipid` int(1) DEFAULT 0 COMMENT '會員等級',
 `permissionid` int(1) DEFAULT 0 COMMENT '權(quán)限等級',
 `registerdata` datetime DEFAULT NULL COMMENT '注冊日期',
 `status` tinyint(1) DEFAULT NULL COMMENT '狀態(tài):0 未激活 1激活',
 PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=1007 DEFAULT CHARSET=utf8

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

2、idea 創(chuàng)建項目

2.1)在項目的pom表中導(dǎo)入郵件jar包

		<!--引入郵件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

為了使項目能夠跑通測試,以下是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>

	<!--
    定位: SpringBoot主要的作用整合SSM,使得框架的使用更加簡化
    原則: "開箱即用"
    parent主要的作用:
           1.SpringBoot在內(nèi)部兼容了當(dāng)下幾乎所有的第三方框架
           2.SpringBoot官網(wǎng)已經(jīng)將所有兼容的版本進(jìn)行了定義
            (幾乎解決了版本沖突問題)以后幾乎不寫版本號
    概括: parent標(biāo)簽中管理其他的項目版本信息.
-->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<!--坐標(biāo)-->
	<groupId>com.demo</groupId>
	<artifactId>yuyue</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>yuyue</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<!--跳過測試類打包-->
		<skipTests>true</skipTests>
	</properties>

	<!--原則: 按需導(dǎo)入  -->
	<dependencies>
		<dependency>
			<!--springboot啟動項(器)在包的內(nèi)部SpringBoot
		   已經(jīng)完成了項目的"整合"(配置) 用戶拿來就用
		   web導(dǎo)入SpringMVC
		   -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!--支持熱部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

		<!--添加lombok依賴-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<!--引入數(shù)據(jù)庫驅(qū)動 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--springBoot數(shù)據(jù)庫連接  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!--導(dǎo)入MP包之后,刪除原有的Mybatis的包 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>

		<!--引入郵件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
	</dependencies>

	<!--SpringBoot項目與Maven整合的一個插件
	   可以通過插件 執(zhí)行項目打包/測試/文檔生成等操作
	   注意事項: 該插件不能省略
	   項目發(fā)布時: java -jar xxxx.jar  報錯:沒有主清單信息!!!!
 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<fork>true</fork><!--熱部署必須添加這個配置-->
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

2.2)創(chuàng)建user類―用戶類

package com.demo.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.sql.Timestamp;

@Data							//lombok---自動創(chuàng)建get、set等方法
@NoArgsConstructor				//lombok---無參構(gòu)造
@AllArgsConstructor				//lombok---全參構(gòu)造
@Accessors(chain = true)		//開啟鏈?zhǔn)骄幊?
@TableName("user")    			//關(guān)聯(lián)數(shù)據(jù)表--user表的名字
public class User {
	//主鍵自增
	@TableId(type= IdType.AUTO)
	private Integer userid;         		//登錄賬號
	private String name;            		//姓名
	private String password;        		//密碼
	private String repassword;      		//確認(rèn)密碼
	private String sex;             		//性別
	private String idno;            		//身份證號碼
	private Integer userVerificationCode; 	//驗證碼
	private Integer userActivationCode; 	//激活碼
	private String eml;             		//郵箱
	private String tel;             		//聯(lián)系電話
	private Integer vipid;          		//vip標(biāo)志id
	private Integer permissionid;   		//權(quán)限標(biāo)志id
	private boolean status;					//狀態(tài):0 未激活 1激活
	//日期出參格式化
	@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
	private Timestamp registerdata;      	//注冊時間
	
	
	@TableField(exist = false)         		//不是數(shù)據(jù)表格中固有的屬性
	private String vipname;          		//vip標(biāo)志名稱
	
	@TableField(exist = false)         		//不是數(shù)據(jù)表格中固有的屬性
	private String permissionname; 			//權(quán)限標(biāo)志名稱
}

2.3)創(chuàng)建配置文件

server:
port: 8090

spring:
#連接數(shù)據(jù)數(shù)據(jù)庫
datasource:
  driver-class-name: com.mysql.cj.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/yuyue?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
  username: root
  password: root
  #如果數(shù)據(jù)庫密碼以數(shù)字0開頭 則必須使用""號包裹
  #password: "01234"

#連接發(fā)送者郵箱
mail:
  host: smtp.qq.com #這個是QQ郵箱的,發(fā)件人郵箱的 SMTP 服務(wù)器地址, 必須準(zhǔn)確, 不同郵件服務(wù)器地址不同, 一般(只是一般, 絕非絕對)格式為: smtp.xxx.com,可以百度
  username: [email protected] #qq郵箱	
  password: 			 #qq郵箱授權(quán)碼
  protocol: smtp #發(fā)送郵件協(xié)議
  properties.mail.smtp.auth: true   #設(shè)置是否需要認(rèn)證,如果為true,那么用戶名和密碼就必須的,
  properties.mail.smtp.starttls.enable: true
  properties.mail.smtp.starttls.required: true
  properties.mail.smtp.ssl.enable: true #開啟SSL
  default-encoding: utf-8


#SpringBoot整合MP配置
mybatis-plus:
#定義別名包: 實現(xiàn)對象映射
type-aliases-package: com.demo.pojo
#加載映射文件一個接口對應(yīng)一個映射文件
mapper-locations: classpath:/mybatis/*.xml
#開啟駝峰映射
configuration:
  map-underscore-to-camel-case: true


#不打印日志
debug: false

#Mapper接口執(zhí)行 打印Sql日志
logging:
level:
  com.jt.mapper: debug

2.3.1)郵件的配置文件,application.yml寫法

spring:
mail:
  host: smtp.qq.com #發(fā)送郵件服務(wù)器
  username: [email protected] #發(fā)送者郵箱
  password: xxxxxxxx #發(fā)送者郵箱授權(quán)碼
  protocol: smtp #發(fā)送郵件協(xié)議
  properties.mail.smtp.auth: true #開啟認(rèn)證
  properties.mail.smtp.port: 994 #設(shè)置端口465或者994
  properties.mail.display.sendmail: aaa #可以任意
  properties.mail.display.sendname: bbb #可以任意
  properties.mail.smtp.starttls.enable: true
  properties.mail.smtp.starttls.required: true
  properties.mail.smtp.ssl.enable: true #開啟SSL
  default-encoding: utf-8
  #from: [email protected]  #發(fā)送者郵箱

2.3.2)郵件的配置文件,application.properties寫法

spring.mail.host=smtp.qq.com  //這個是QQ郵箱的  其他郵箱請另行百度
spring.mail.username=用戶名  //發(fā)送方的郵箱
spring.mail.password=密碼  //對于qq郵箱而言 密碼指的就是發(fā)送方的授權(quán)碼
spring.mail.properties.mail.smtp.auth=true  
spring.mail.properties.mail.smtp.starttls.enable=true  
spring.mail.properties.mail.smtp.starttls.required=true  

2.4)創(chuàng)建EmailController類

package com.demo.controller;

import com.demo.pojo.User;
import com.demo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//接受請求
@CrossOrigin //解決跨域
@RequestMapping("/email") //訪問路徑
public class EmailController{

  //注入對象
  @Autowired
  private EmailService emailService;

  @PostMapping ("/sendEmail")
  public String sendEmail(User user){
      System.out.println("發(fā)送郵件。。。。");
      return emailService.sendEmail(user);
  }

  @PostMapping ("/verificationEmail")
  public String verificationEmail(User user){
      System.out.println("驗證-郵箱發(fā)送的驗證碼。。。。");
      return emailService.verificationEmail(user);
  }
}

2.5)創(chuàng)建EmailService 類

package com.demo.service;

import com.demo.pojo.User;

public interface EmailService {
  //發(fā)送驗證碼
  String sendEmail(User user);
}

2.6)創(chuàng)建EmailServiceImpl 類

package com.demo.service;

import com.demo.pojo.User;
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 java.util.Random;
@Service
public class EmailServiceImpl implements EmailService {

  //定義驗證碼
  private  Integer userVerificationCode = null;

  @Autowired
  JavaMailSender jms;

  //讀取配置文件郵箱賬號參數(shù)
  @Value("${spring.mail.username}")
  private String sender;

  //發(fā)送驗證碼
  @Override
  public String sendEmail(User user) {
      //隨機(jī)數(shù)用作驗證
      Integer userVerificationCode = new Random().nextInt(999999);
      try {
          //建立郵件消息
          SimpleMailMessage mainMessage = new SimpleMailMessage();

          //發(fā)送者
          mainMessage.setFrom(sender);

          //接收者
          mainMessage.setTo(user.getEml());

          //發(fā)送的標(biāo)題
          mainMessage.setSubject("郵箱驗證");

          //發(fā)送的內(nèi)容
          String msg = "您好!" + user.getEml() + ",您正在使用郵箱驗證,驗證碼:" + userVerificationCode + "。";
          mainMessage.setText(msg);

          //發(fā)送郵件
          jms.send(mainMessage);

          //下面是加入緩存,以便于進(jìn)行郵箱驗證
          this.userVerificationCode = userVerificationCode;

      } catch (Exception e) {
          return ("發(fā)送郵件失敗,請核對郵箱賬號");
      }
      return "驗證碼已經(jīng)發(fā)送您的郵箱,請前去郵箱查看,驗證碼是:" + userVerificationCode ;
  }

  @Override
  public String verificationEmail(User user) {
      if (this.userVerificationCode.equals(user.getUserVerificationCode())){
          return "驗證成功";
      }
      return "驗證失敗";
  }
}

3、準(zhǔn)備網(wǎng)頁

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>郵箱驗證測試</title>
		<script src="../js/jquery-3.6.0.min.js"></script>
		<script src="../js/axios.js"></script>
		<script>
			function register(){
				axios.post("http://localhost:8090/fkxinli/register", $("#f1").serialize())
							.then(function(result){
							console.log(result.data)
				})
			}
			function register1(){
				$.ajax({ //發(fā)起Ajax請求數(shù)據(jù)
					type: "POST", //POST隱藏請求自帶的數(shù)據(jù),get顯示請求自帶的數(shù)據(jù)
					url: "http://localhost:8080/fkxinli/register", //要使用的請求路徑
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功時的方案
						document.write(data);
					},
					error: function(data) {
						//alert("返回失敗");
						//console.log("注冊失敗");
						
					}
				})
			}
			function sendEmail(){
				$.ajax({ //發(fā)起Ajax請求數(shù)據(jù)
					type: "POST", //POST隱藏請求自帶的數(shù)據(jù),get顯示請求自帶的數(shù)據(jù)
					url: "http://localhost:8090/email/sendEmail", //要使用的請求路徑
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功時的方案
						alert(data);
					},
					error: function(data) {
						//alert("返回失敗");
						//console.log("注冊失敗");
					}
				})
			}
			function verificationEmail(){
				$.ajax({ //發(fā)起Ajax請求數(shù)據(jù)
					type: "POST", //POST隱藏請求自帶的數(shù)據(jù),get顯示請求自帶的數(shù)據(jù)
					url: "http://localhost:8090/email/verificationEmail", //要使用的請求路徑
					//contentType: "application/json;charset=utf-8",
					data:$("#f1").serialize(),
					success: function(data) { //成功時的方案
						alert(data);
					},
					error: function(data) {
						//alert("返回失敗");
						//console.log("注冊失敗");
					}
				})
			}
			<!--返回首頁-->
			function returnfrontpage(){
				window.open("../1-homepage/frontpage.html")
			}
		</script>
	</head>
	<body>
		<h1 align="center">郵箱驗證測試</h1>
		<form  id="f1">
			<table align="center">
				<tr>
					<td>電子郵箱:</td>
					<td>
						<input type="email" name="eml" placeholder="請輸入電子郵箱"/>
						<input type="button" value="發(fā)送驗證碼" onclick="sendEmail()" />
					</td>
				</tr>
				
				<tr>
					<td>郵箱驗證碼:</td>
					<td>
						<input type="text" name="userVerificationCode" placeholder="請輸入郵箱驗證碼"/>
						<input type="button" value="驗證--郵箱發(fā)送的驗證碼" onclick="verificationEmail()" />
					</td>
				</tr>
				
			</table>
			
		</form>
	</body>
</html>

4、測試

后端代碼,寫的比較簡單,僅僅測試郵箱是否能夠發(fā)送驗證碼

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

java實戰(zhàn)案例之用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼

 

總結(jié)

到此這篇關(guān)于java用戶注冊并發(fā)送郵件激活/發(fā)送郵件驗證碼的文章就介紹到這了,更多相關(guān)java用戶注冊發(fā)送郵件激活內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://blog.csdn.net/AimerDaniel/article/details/120106116

延伸 · 閱讀

精彩推薦
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程20個非常實用的Java程序代碼片段

    20個非常實用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實用的Java程序片段,對java開發(fā)項目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程Java8中Stream使用的一個注意事項

    Java8中Stream使用的一個注意事項

    最近在工作中發(fā)現(xiàn)了對于集合操作轉(zhuǎn)換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點,所以這篇文章主要給大家介紹了關(guān)于Java8中S...

    阿杜7482021-02-04
  • Java教程Java實現(xiàn)搶紅包功能

    Java實現(xiàn)搶紅包功能

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關(guān)于小米推送Java代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩(wěn)中求8032021-07-12
  • Java教程Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經(jīng)有好久沒有升過級了。升級完畢重啟之后,突然發(fā)現(xiàn)好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程xml與Java對象的轉(zhuǎn)換詳解

    xml與Java對象的轉(zhuǎn)換詳解

    這篇文章主要介紹了xml與Java對象的轉(zhuǎn)換詳解的相關(guān)資料,需要的朋友可以參考下...

    Java教程網(wǎng)2942020-09-17
主站蜘蛛池模板: 久久视频在线视频观看天天看视频 | 华人在线京东热 | 久久精品国产色蜜蜜麻豆国语版 | 欧美专区在线视频 | 国产精品亚洲w码日韩中文 国产精品香蕉在线观看不卡 | 人妖欧美一区二区三区四区 | 范冰冰特黄xx大片 | 99热国产在线观看 | 奇米7777第四色 | 国产亚洲精品一区在线播 | 7777色鬼xxxx欧美色夫 | 女仆掀起蕾丝裙被打屁股作文 | 久久草福利自拍视频在线观看 | 国产精品久久毛片蜜月 | 亚洲成人影院在线 | 二次元美女互摸隐私互扒 | 91高清免费国产自产 | 久久国产精品永久免费网站 | 国产精品思瑞在线观看 | 国产日韩免费视频 | 福利姬 magnet | 毛片小视频 | 日本在线不卡免 | 满溢游泳池免费 | 亚洲国产成人久久精品影视 | 91在线精品国产丝袜超清 | 国产最强大片免费视频 | 国产精品污双胞胎在线观看 | 国产色司机在线视频免费观看 | 亚洲春色综合另类网蜜桃 | 公交车强校花系列小说 | 日本中文字幕在线观看视频 | 日本大尺度动漫在线观看缘之空 | 高清在线观看mv的网址免费 | 国产图片综合区 | 男人看片网址 | 日韩视频一 | 日本欧美大码a在线视频播放 | 日本高免费观看在线播放 | 欧美白人猛性xxxxx69交 | 国内精品露脸在线视频播放 |