前置技能:1.创建spring boot项目(博客链接:点击跳转)
2.整合mybatis框架(博客链接:点击跳转)
3.热加载(并不必要,但是部署了测试项目会方便很多,博客链接:点击跳转)
4.基于mybatis和spring boot实现对mysql的增删改查(博客链接:点击跳转)
5.基于Spring Boot框架实现发送邮件(博客链接:点击跳转)
首先是一个前端页面,可以自己写,下面是一篇前端模板:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>注册页面</p>
<form id="message">
<input name="userName" type="text" placeholder="请输入邮箱(未注册请先注册)"></br>
<input name="password" type="password" placeholder="请输入密码"></br>
<input name="code" type="text" placeholder="请输入验证码"></br>
</form>
<input id="register" type="button" value="注册">
<input id="getCode" type="button" value="获取验证码">
</body>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
// 获取验证码
$('#getCode').click(function () {
$.ajax({
url:"/GetCodeController/getCodeController",
data:$('#message').serialize(),
success:function (data) {
if(data==="success"){
alert("获取验证码成功");
}else{
alert("获取失败");
}
}
})
})
// 注册功能
$('#register').click(function () {//$里的#后面跟的是触发按钮的id
$.ajax({
url:"/Register/register",//url里填控制器的映射
data:$('#message').serialize(),//$里面的#后面跟着输入数据的from的id
success:function (data) {
if(data==="success")alert("注册成功");
else if(data==="nameError")alert("请输入正确的邮箱");
else if(data==="passwordError")alert("请输入正常的密码");
else if(data==="error")alert("验证码错误");
else if(data==="repeat")alert("用户名已存在");
else alert("注册失败,请检查输入");
}
})
})
</script>
</html>
首先是发送验证码的类,
在pojo文件夹下创建一个SendMail类,
代码如下:
setFrom里的内容记得改成自己发送邮件的邮箱
package com.example.demo.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class SendMail {
@Autowired
private JavaMailSender mailSender;
public void sendMail(String To,String Text)throws Exception{
try {
SimpleMailMessage messege=new SimpleMailMessage();
messege.setFrom("@qq.com");//这里填自己的邮箱
messege.setTo(To);
messege.setSubject("主题:验证码");
messege.setText(Text);
mailSender.send(messege);
}catch (Exception e){
e.printStackTrace();
System.out.println("邮件发送失败");
}
}
}
然后写一个获取验证码的控制器,
在controller文件夹下创建一个GetCodeController类,通过获取前端填的邮箱来发送验证码,代码如下:
package com.example.demo.controller;
import com.example.demo.pojo.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/GetCodeController")
public class GetCodeController {
@Autowired
private SendMail sendMail;
//获取验证码
@RequestMapping("/getCodeController")
@ResponseBody
public String getCodeController(String userName,HttpServletRequest request){
//生成验证码
int code=(int)((Math.random()*9+1)*100000);
try{
//对象创建session
//通过键值对存储
if(!Regular.isEmail(userName)||!Regular.isEmoji(userName))return "fail";
request.getSession().setAttribute(userName,code);//把验证码与该用户邮箱绑定
sendMail.sendMail(userName,String.valueOf(code));//给该用户发送验证码
}catch (Exception e){
e.printStackTrace();
return "fail";
}
return "success";
}
}
最后就是注册流程了,通过前端获取的邮箱判断验证码是否为发送给该用户的验证码,是就把该组数据添加进数据库,
代码如下:
package com.example.demo.controller;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserExample;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller //表示该类为控制器
@RequestMapping("/Register")//映射,访问test将会被该类处理
public class Register {
@Resource
private UserMapper userMapper;
@RequestMapping("/register")
@ResponseBody
public String register(String userName, String password, String code, HttpServletRequest request){//参数变量名要与前端代码中input标签的name相同
if(userName==null||userName.length()==0||password==null||password.length()==0)return "fail";//判空数据返回失败
if(!Regular.isEmail(userName)||!Regular.isEmoji(userName))return "nameError";
if(!Regular.isEmoji(password))return "passwordError";
UserExample userExample=new UserExample();//查询数据库里用户名是否重复,用户名不是主键这一块可以不要
userExample.createCriteria().andUserNameEqualTo(userName);
List<User> userList=userMapper.selectByExample(userExample);
for(int i=0;i<userList.size();i++){
if(userList.get(i).getUserName().compareTo(userName)==0){//数据库查询到已有该用户名返回失败
return "repeat";
}
}
try {
try{
if(request.getSession().getAttribute(userName)==null){
return "error";
}
}catch (Exception e){
e.printStackTrace();
return "error";
}
if(request.getSession().getAttribute(userName).toString().compareTo(code)!=0){
return "error";
}
User user=new User();
user.setUserName(userName);
user.setUserPassword(password);
userMapper.insert(user);
return "success";
}catch (Exception e){
e.printStackTrace();
return "fail";
}
}
}
上面用到判断邮箱的正则
package com.example.demo.pojo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regular {
public static boolean isEmoji(String email){
if (email == null)
return false;
String rule="\\uD83C[\\uDF00-\\uDFFF]|\\uD83D[\\uDC00-\\uDE4F]|\\uD83D[\\uDE80-\\uDEFF]|[\\u2700-\\u27BF]\\uFE0F";
Pattern pattern;
Matcher matcher;
pattern = Pattern.compile(rule);
matcher = pattern.matcher(email);
if (matcher.matches()){
System.out.println("Yes");
return false;
}
else
return true;
}
public static boolean isEmail(String email) {
if (email == null)
return false;
String rule = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
Pattern pattern;
Matcher matcher;
pattern = Pattern.compile(rule);
matcher = pattern.matcher(email);
if (matcher.matches()){
System.out.println("Yes");return true;
}
else
return false;
}
}