实现向邮箱发送随机生成验证码,修改用户密码的功能。没什么好说的,进入正文。
前置条件:耐性100%;IDEA2019;SSM框架
Maven工程导入jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
获取邮箱授权码(QQ邮箱为例)
设置>账户>开启POP3/SMTP服务>拿到邮箱授权码
创建资源文件
mail.properties
#服务器主机名 smtp.xx.com
mail.smtp.host=smtp.qq.com
mail.smtp.username=XXX@qq.com
#客户端授权码
mail.smtp.password=你的邮箱授权码
#编码字符
mail.smtp.defaultEncoding=utf-8
#是否进行用户名密码校验
mail.smtp.auth=true
#设置超时时间
mail.smtp.timeout=20000
调用资源文件
springMVC.xml OR applicationContext.xml
<!--读取属性文件-->
<context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/>
<!--配置邮件接口-->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.smtp.host}"/>
<property name="username" value="${mail.smtp.username}"/>
<property name="password" value="${mail.smtp.password}"/>
<property name="defaultEncoding" value="${mail.smtp.defaultEncoding}"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
</props>
</property>
</bean>
创建修改密码界面
这里css样式用到了bootstrap框架,可以先忽视,也可以戳这了解一下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>找回密码</title>
<link rel="icon" href="images/timg.jpg" type="image/x-icon">
<link rel="stylesheet" href="css/modify.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/modify.js"></script>
</head>
<body id="background">
<div class="container">
<div class="row ">
<div class="col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 div-background">
<form action="user/updatepassword" title="找回密码" class="form-group" method="post">
<p>
<label for="account">登录账号:</label>
<input class="form-control" id="account" placeholder="请输入账号" name="account" oninput="checkinput('account')">
<div id="account-tips"></div><div style="display: none"><input value="false" id="account-check"></div>
</p>
<p>
<label for="email">邮箱:</label>
<input class="form-control" id="email" placeholder="请输入邮箱" name="email" oninput="checkinput('email')">
<div id="email-tips"></div><div style="display: none"><input value="false" id="email-check"></div>
</p>
<p>
<label for="captcha">验证码:</label>
<input class="form-control" id="captcha" placeholder="请输入验证码" name="captcha" oninput="checkinput('captcha')">
<div id="captcha-tips"></div><div style="display: none"><input value="false" id="captcha-check"></div>
<input class="btn btn-info" type="button" value="获取验证码" id="get-captcha">
</p>
<p>
<label for="pwd">输入密码:</label>
<input class="form-control" id="pwd" placeholder="请输入密码" name="pwd" type="password" oninput="checkinput('pwd')" onfocus="$('#confirm-pwd').val('')">
<div id="pwd-tips"></div><div style="display: none"><input value="false" id="pwd-check"></div>
</p>
<p>
<label for="confirm-pwd">确认密码:</label>
<input class="form-control" id="confirm-pwd" placeholder="再次确认密码" name="confirm-pwd" type="password" oninput="checkinput('confirm-pwd')">
<div id="confirm-pwd-tips"></div><div style="display: none"><input value="false" id="confirm-pwd-check"></div>
</p>
<p>
<input class="btn btn-success" id="submit-btn" type="button" value="确认提交" disabled>
</p>
</form>
</div>
</div>
</div>
</body>
</html>
梳理找回密码流程
- 输入账号,输入邮箱;
- 点击按钮获取验证码;
- 判断邮箱是否为空,判断邮箱格式是否正确(这里按“xxx.@xx.com”格式);
- ajax异步请求控制器查找数据库中是否有该邮箱(注意:这里是没这么多邮箱,实际开发中应该要判断邮箱与账号一一对应);
- 控制器调用services方法调用对应dao访问数据库查找数据;
- 控制器根据查找的数据返回请求结果;
- false拒绝发送验证码,弹窗提示“该邮箱不能获取验证码”,true则异步请求控制器发送验证码;
- 控制器随机生成一组6位数验证码并存入session中,根据收到的邮箱地址发送验证码;
- 设置计时器,超过一分钟后异步请求删除session中的验证码(因为对session的生命周期不熟悉,所以这里调用方法来删除),并弹窗提示“请重新获取验证码”;
- 输入新密码和再次确认密码,两次密码一致且所有输入框不为空后释放提交按钮;
- 点击按钮提交表单;
- 判断输入的验证码和session中的一致,则更新数据库中的密码
创建控制器
SenEmailController 控制器
package com.qiang.controller;
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.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.Random;
/**
* @author Mr.锵
* date 2020-04-14
*/
@Controller
@RequestMapping("/email")
public class SenEmailController {
@Autowired
private JavaMailSender javaMailSender;
@Value("${mail.smtp.username}")
private String emailFrom;
@RequestMapping("/send")
public @ResponseBody Boolean senMsg(HttpSession httpSession, @RequestParam String email){
//生成六位数验证码
String Captcha = String.valueOf(new Random().nextInt(899999) + 100000);
httpSession.setAttribute("Captcha",Captcha);
SimpleMailMessage message = new SimpleMailMessage();
//发件人的邮箱地址
message.setFrom(emailFrom);
//收件人的邮箱地址
message.setTo(email);
//邮件主题
message.setSubject("邮件的主题");
//邮件内容
message.setText("内容:"+Captcha);
//发送邮件
javaMailSender.send(message);
return true;
}
}
UserController控制器
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/updatepassword",method = RequestMethod.POST)
public String updatepassword(String account,String pwd){
User1 user1=new User1();
user1.setPhone(account);
user1.setPassword(pwd);
userService.updatepassword(user1);
return "redirect:/";
}
@RequestMapping("/checkemail")
public @ResponseBody boolean checkemail(String email){
List<User1> checkemail = userService.checkemail(email);
if(checkemail.size()!=0){
return true;
}else{
return false;
}
}
@RequestMapping("/checkcaptcha")
public @ResponseBody boolean checkcaptcha(HttpSession httpSession,@RequestParam String captcha){
String captcha1 = (String)httpSession.getAttribute("Captcha");
if(captcha.equals(captcha1)){
return true;
}else {
return false;
}
}
@RequestMapping("/deletecaptcha")
public @ResponseBody void deletecaptcha(HttpSession httpSession){
httpSession.removeAttribute("Captcha");
}
}
JavaScript实现异步请求
<Script>
$(function () {
$("#get-captcha").click(function () {
if($("#email").val()==""){
alert("邮箱不能为空");
$("#email").focus();
return false;
} else if($("#email").val().indexOf('@')=='-1'||$("#email").val().indexOf('.com')=='-1'){
alert("请检查邮箱格式是否正确")
} else{
$.ajax({
url:'user/checkemail',
datatype : "json",
type : "post",
data:{
email:$("#email").val()
},
success:function (res) {
if(res==true){
$("#get-captcha").attr("disabled", true);
$("#get-captcha").val("发送中...");
$.ajax({
url:'email/send',
datatype : "json",
type : "post",
data:{
email:$("#email").val()
},
success:function (res) {
if(res){
alert("验证码发送成功")
var count = 60;
var countdown = setInterval(CountDown, 1000);
function CountDown() {
$("#get-captcha").attr("disabled", true);
$("#get-captcha").val(count + "s");
if (count == 0) {
$("#get-captcha").val("重新获取验证码").removeAttr("disabled");
clearInterval(countdown);
$.ajax({
url : "user/deletecaptcha",
datatype : "json",
type : "post",
success:function () {
alert("获取验证码失效,请重新获取")
}
})
}
count--;
}
}
},error:function () {
alert("获取验证码失败")
$("#get-captcha").val("重新获取验证码").removeAttr("disabled");
}
})
}else{
alert("该邮箱不能获取验证码")
}
}})
}
});
$("#submit-btn").click(function () {
$.ajax({
url:"user/findPhone",
data:{
phone:$("#account").val()
},
dataType:"json",
type:"post",
success:function(result){
if(result==true){
alert("没有该账号");
return false;
}else{
$.ajax({
url:"user/checkcaptcha",
data:{
captcha:$("#captcha").val()
},
dataType:"json",
type:"post",
success:function (res) {
if(res==false){
alert("验证码不正确");
return false;
}else{
alert("修改成功")
$("form").submit();
}
}
})
}
}
})
});
function checkinput(id) {
if($("#"+id+"").val()==""){
$("#"+id+"-tips").html("");
$("#"+id+"-tips").append("<h5 style='color:red'>不能为空!</h5>");
$("#"+id+"-check").val("false");
}else{
if(id=='confirm-pwd'){
if($("#"+id+"").val()!=$("#pwd").val()){
$("#"+id+"-tips").html("");
$("#"+id+"-tips").append("<h5 style='color:red'>两次密码不正确</h5>");
$("#"+id+"-check").val("false");
}else{
$("#"+id+"-tips").html("");
$("#"+id+"-check").val("true");}
}else{
$("#"+id+"-tips").html("");
$("#"+id+"-check").val("true");
}
}
if($("#account-check").val()=="true"&&$("#pwd-check").val()=="true"&&$("#email-check").val()=="true"&&$("#confirm-pwd-check").val()=="true"&&$("#captcha-check").val()=="true"){
$("#submit-btn").removeAttr("disabled");
}else{
$("#submit-btn").attr("disabled", true);
}
}
</Script>
结尾
发送邮箱的功能实现比较简单,建议JavaScript看多几遍,逻辑比较重要。
感觉有帮助就点个赞呗~
下一篇先用bootstrap框架画个主界面