当前位置:网站首页>数据与信息资源共享平台(八)
数据与信息资源共享平台(八)
2022-06-10 21:58:00 【yyDrifter】
邮箱注册/密码找回/认证
原理
数据库中设置两个字段,status:(0:未激活,1:激活成功),activition_code:(放激活码):
用户填写资料,点击注册,插入数据成功,state字段默认是0,同时生成一个activition_code(用传过来的邮箱、密码、和当前时间加密形成)也存入数据库。
发送邮件,提示用户登录邮箱激活,邮件中带一个激活成功页的URL,URL里有两个参数(用户ID和激活码)。
用户登录邮箱点击链接,来到处理激活的业务逻辑页面或Servlet,得到URL中两个参数,以这两个参数为条件查询数据库里的数据,如果有,查看链接传过来的激活码与数据库字段激活码是否一致,不一致,删除数据库中该条记录,并跳转到激活失败界面,一致,则将字段state为1,激活成功,转到激活成功页。
后端
UserController.java
邮箱注册
@RequestMapping("/register.do")
public OutResponse<Object> registerdo( User user) {
OutResponse<Object> outResponse = new OutResponse<>();
try {
userService.register(user);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error("用户注册失败,用户名:{}邮箱:{}", user.getUserName(), user.getEmail());
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error("用户注册失败,用户名:{}邮箱:{}", user.getUserName(), user.getEmail());
}
return outResponse;
}
邮箱账户激活
@RequestMapping("/activate")
public ModelAndView activate(String userName, String activationCode) {
OutResponse<Object> outResponse = new OutResponse<>();
ModelAndView view = new ModelAndView("/page/active");
try {
userService.updateUserActivate(userName, activationCode);
outResponse.setCode(CodeEnum.SUCCESS);
outResponse.setMsg("尊敬的【"+userName+"】用户,恭喜您账户激活成功");
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error("用户激活失败,用户名:{}", userName);
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error("用户激活失败,用户名:{}", userName);
}
view.addObject("outResponse", outResponse);
return view;
}
找回密码
@RequestMapping("/sendCheckCode")
public OutResponse<Object> sendCheckCode(String email) {
OutResponse<Object> outResponse = new OutResponse<>();
try {
System.out.println("--------------------kajsfdlkjaslkfd");
userService.sendCheckCode(email);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error("验证码发送失败,邮箱:{}");
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error("验证码发送失败,邮箱:{}", email);
}
return outResponse;
}
密码修改
@RequestMapping("/findPassword.do")
public OutResponse<Object> findPassworddo(String email, String password, String checkcode) {
OutResponse<Object> outResponse = new OutResponse<Object>();
try {
userService.modifyPassword(email, password, checkcode);
outResponse.setCode(CodeEnum.SUCCESS);
} catch (BussinessException e) {
outResponse.setMsg(e.getLocalizedMessage());
outResponse.setCode(CodeEnum.BUSSINESSERROR);
logger.error("密码修改失败,邮箱{}", email);
} catch (Exception e) {
outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
outResponse.setCode(CodeEnum.SERVERERROR);
logger.error("密码修改失败,邮箱:{}", email);
}
return outResponse;
}
User.java
public class User {
private String userid;
private String email;
private String userName;
private String password;
private String userIcon;
private String userBg;
private String age;
private String sex;
private String characters;
private Integer mark=0;
private String address;
private String work;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
private String birthdayString;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
private Date registerTime;
private String registerTimeString;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
private Date lastLoginTime;
private String lastLoginTimeString ;
private String activationCode;
private Integer status;
private Integer userPage;
}
UserMapper.xml
插入邮箱地址信息
<insert id="insert" parameterType="com.known.common.model.User" >
insert into known_user (userid, email, user_name,
password, user_icon, user_bg, birthday,
register_time, last_login_time, activation_code)
values (#{
userid,jdbcType=VARCHAR}, #{
email,jdbcType=VARCHAR}, #{
userName,jdbcType=VARCHAR},
#{
password,jdbcType=VARCHAR}, #{
userIcon,jdbcType=VARCHAR}, #{
userBg,jdbcType=VARCHAR},
#{
birthday,jdbcType=TIMESTAMP}, #{
registerTime,jdbcType=TIMESTAMP},
#{
lastLoginTime,jdbcType=TIMESTAMP},#{
activationCode,jdbcType=VARCHAR})
</insert>
邮箱账户激活后更新账户信息
<update id="updateStatus">
update known_user set status = 1
where user_name = #{
userName,jdbcType=VARCHAR}
and activation_code=#{
activationCode,jdbcType=VARCHAR}
</update>
StringUtil.java
邮箱格式初步校验
//判断是否为邮箱
public static boolean isEmail(String str) {
String checkEmail = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
if (!isEmpty(str)) {
return str.matches(checkEmail);
} else {
return false;
}
}
UserService.java-接口
User findUserByEmail(String email);//邮箱找回
void sendCheckCode(String email) throws BussinessException;//发送验证码
void modifyPassword(String email, String password, String checkcode) throws BussinessException;//修改密码
UserServiceImpl.java-接口实现逻辑
发送激活邮件
// 发送激活邮件
String subject = "学生信息资源共享系统系统通知邮件";
StringBuffer content = new StringBuffer("亲爱的 【" + user.getUserName() + "】用户<br><br>");
content.append("欢迎您使用学生信息资源共享系统!<br><br>");
content.append("点击<a href='" + mailConfig.getGlob_Real_Path() + "/user/activate?userName=" + user.getUserName() +
"&activationCode=" + activationCode + "'>学生信息资源共享系统账号激活</a>激活您的账号!");
try {
MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
subject, new String(content));
} catch (Exception e) {
throw new BussinessException("发送邮件失败,请稍后再试");
}
效果图
通过用户名查找用户,校验是否激活并注册成功
public void updateUserActivate(String userName, String activationCode) throws BussinessException {
//通过用户名查找用户
User user = findUserByUserName(userName);
if (user == null) {
throw new BussinessException("用户【"+userName+"】不存在,请注册用户");
}
if (user.getUserPage() != 0) {
throw new BussinessException("用户【"+userName+"】已激活, 请登录");
}
if (!activationCode.equals(user.getActivationCode())) {
throw new BussinessException("用户【"+userName+"】激活码失效, 请使用最新激活链接");
}
userMapper.updateStatus(userName, activationCode);
}
status为0代表账户未激活
if (user.getStatus() == 0) {
throw new BussinessException("请查收邮件, 激活账户后登录");
}
邮箱验证码发送
public void sendCheckCode(String email) throws BussinessException {
if (StringUtil.isEmpty(email) || !StringUtil.isEmail(email)) {
throw new BussinessException("输入参数不合法");
}
User user = findUserByEmail(email);
if (user == null) {
throw new BussinessException("邮箱不存在");
}
String checkCode = StringUtil.getActivationCode(6);
String subject = "学生信息资源共享系统系统通知邮件";
StringBuffer content = new StringBuffer("亲爱的 【" + user.getUserName() + "】用户<br><br>");
content.append("欢迎您使用<a href='"+mailConfig.getGlob_Real_Path()+"'>学生信息资源共享系统</a>的找回密码功能<br><br>");
content.append("您的验证码是<h3 style='color:red;'>" + checkCode + "</h3>");
try {
System.out.println("======================"+checkCode);
MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
subject, new String(content));
} catch (Exception e) {
throw new BussinessException("发送邮件失败,请稍后再试");
}
user.setActivationCode(checkCode);
userMapper.update(user);
}
用户有效性验证
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Integer changeMark(String userid, int mark) {
return userMapper.changeUserMark(mark, userid);
}
public User findUserInfo4UserHome(String userId) throws BussinessException {
User user = findUserByUserid(userId);
if (user == null) {
throw new BussinessException("用户不存在");
}
//设置密码为空
user.setPassword(null);
//设置激活码为空
user.setActivationCode(null);
return user;
}
application-config设置发件人邮箱
mail.sendUserName=你的邮箱地址(推荐163)
mail.sendPassword=邮箱pop服务器地址
前端
注册
<div class="form-group">
<label class="col-lg-2 control-label">邮箱:</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="email" id="email" placeholder="用于取回密码,请填写正确的常用邮箱">
</div>
</div>

找回密码
<div class="container-findpassword">
<div class="findpassword">
<div>
<legend class="form_legend">
找回密码
</legend>
<form id="findPassword">
<div class="form-group">
<input class="form-control" placeholder="请输入邮箱" name="email" id="email"></input>
</div>
<div class="form-group" >
<div id="embed-captcha"></div>
<p id="wait" class="show">正在加载验证码......</p>
<p id="notice" class="hide">请先拖动验证码到相应位置</p>
</div>
</form>
<div class="form-group">
<button type="button" class="btn btn-info block full-width" id="findpassword">发送验证码</button>
</div>
<p class="foot">
<a href="${realpath}/user/login">返回进行登录</a>
|
<a href="${realpath}/user/register">注册一个新账号</a>
</p>
</div>
</div>
var handlerEmbed = function (captchaObj) {
$("#findpassword").click(function (e) {
var validate = captchaObj.getValidate();
if (!validate) {
$("#notice")[0].className = "show";
setTimeout(function () {
$("#notice")[0].className = "hide";
}, 2000);
e.preventDefault();
} else{
var email = $('#email').val();
var emailreg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (email == null || $.trim(email) == '') {
checkForm('邮箱不能为空', 'email');
$("#email").parent().addClass('has-error');
} else if (!emailreg.test(email)) {
checkForm('请输入正确的邮箱', "email");
$("#email").parent().addClass('has-error');
} else {
$("#email").parent().removeClass('has-error');
var loadingindex = layer.load(0, {
shade: [0.1,'#fff'] //0.1透明度的白色背景
});
$.ajax({
url: known.realpath + '/user/sendCheckCode',
type: 'POST',
dataType: 'json',
data: $('#findPassword').serialize(),
success: function(data) {
layer.close(loadingindex);
if (data.msg == null) {
var content = '<form id="modifyPassword"><div class="form-group"><input class="form-control" type="password" placeholder="请输入新密码" name="password" id="password"></input></div><div class="form-group"><input class="form-control" type="password" placeholder="请确认新密码" name="confirmPassword" id="confirmPassword"></input></div><div class="form-group"><input class="form-control" placeholder="验证码" name="checkcode" id="checkcode"></input></div></form>';
var d = dialog({
title: '修改密码',
width: 300,
content: content,
okValue: '确定',
ok: function() {
。。。
} else if (checkcode == null || $.trim(checkcode) == '') {
$("#confirmPassword").parent().removeClass('has-error');
checkForm("验证码不能为空串", "checkcode");
$("#checkcode").parent().addClass('has-error');
return false;
} else {
$.ajax({
url: known.realpath+ '/user/findPassword.do',
type: 'POST',
dataType: 'json',
data: {
"email": email,
"password": password,
"checkcode": checkcode
},
success: function(data) {
if (data.msg == null) {
var d = dialog({
content: "<div><img src='" + known.realpath +"/resources/images/loading.gif' /> 修改成功,跳转中...</div>",
});
d.showModal();
setTimeout(function() {
d.close().remove();
document.location.href = known.realpath + "/user/login";
}, 1000);
} else {
checkForm(data.msg, "checkcode");
}
}
});
return false;

边栏推荐
- [Axi] explain the principle of two-way handshake mechanism of Axi protocol
- [tcapulusdb knowledge base] tcapulusdb shard relocation introduction
- Digital twin: third person mouse operation
- IP反查域名
- DependencyManagement 和 Dependencies
- IPO can't cure Weima's complications?
- How to run Plink software -- three methods
- 图像拼接摄像头拼接笔记
- Question bank and simulation test of 2022 tea artist (intermediate) operation certificate examination
- CCF CSP 202109-3 impulse neural network
猜你喜欢

ICML2022 | 从零开始重新审视端到端的语音到文本翻译

Vulnhub practice DC-1 target

【QPSK中频】基于FPGA的QPSK中频信号产生模块verilog设计

联想首次详解混合云Lenovo xCloud五大优势,如何打造智能化数字底座

Storage engine analysis

原生支持 ARM64 的首个版本!微软 Win11/10 免费工具集 PowerToys 0.59 发布

Opencv_ 100 questions_ Chapter III (11-15)

Opencv_100问_第四章 (16-20)

Multus CNI deployment and basic use of kubernetes multi network card scheme

DC4 of vulnhub
随机推荐
Niuke: expression evaluation
Vscode common shortcuts
Vulnhub's DC3
Watlow signs agreement to acquire EUROTHERM from Schneider Electric
【原创】医鹿APP九价HPV数据抓包分析
Basic use of mathtype7.x
smb匿名
Flowable BPMN相关知识
[Axi] explain the principle of two-way handshake mechanism of Axi protocol
LuoYongHao: if I were the person in charge, I could make apple products go up more than three steps
ICML2022 | 從零開始重新審視端到端的語音到文本翻譯
Is there any risk in opening an account with BOC securities? Is it safe?
Openjudge noi 1.13 15: finding modes in sequences
Locking mechanism
Keras deep learning practice (8) -- using data enhancement to improve neural network performance
Icml2022 | reexamine end-to-end voice to text translation from scratch
但身示你五县非那最土zaiFKMW
Pki/tls Swiss Army knife cfssl
原生支持 ARM64 的首个版本!微软 Win11/10 免费工具集 PowerToys 0.59 发布
数字孪生:第三人称鼠标操作