1.Java实现用户注册,邮箱验证码激活的核心代码:
1.1 在RegisterServlet 用户注册类中
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName=request.getParameter("username");
String password=request.getParameter("password");
String email=request.getParameter("email");
System.out.println(userName+" "+password+" "+email);
UserService userService=new UserServiceImpl();
if(userService.doRegister(userName,password,email)){
request.setAttribute("msg", "注册成功,请登录邮箱激活账号");
}else{
request.setAttribute("msg", "注册失败,请检查相关信息");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
1.2 在ActiveServlet 邮箱验证中:
public class ActiveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code=request.getParameter("code");
UserService userService=new UserServiceImpl();
if(userService.activeUser(code)){
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/fail.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
1.3 在UserService中
public interface UserService {
boolean doRegister(String userName, String password, String email);
boolean activeUser(String code);
}
1.4 在UserServiceImpl中
public class UserServiceImpl implements UserService {
public boolean doRegister(String userName, String password, String email) {
// 这里可以验证各字段是否为空
//利用正则表达式(可改进)验证邮箱是否符合邮箱的格式
if(!email.matches("^\\w+@(\\w+\\.)+\\w+$")){
return false;
}
//生成激活码
String code=CodeUtil.generateUniqueCode();
User user=new User(userName,email,password,0,code);
//将用户保存到数据库
UserDao userDao=new UserDaoImpl();
//保存成功则通过线程的方式给用户发送一封邮件
if(userDao.save(user)>0){
new Thread(new MailUtil(email, code)).start();;
return true;
}
return false;
}
public boolean activeUser(String code) {
UserDao userDao=new UserDaoImpl();
if(userDao.activeUser(code)>0){
return true;
}else{
return false;
}
}
}
1.5 在UserDao中
public interface UserDao {
int save(User user);
int activeUser(String code);
}
1.6 在UserDaoImpl中
public class UserDaoImpl implements UserDao{
public int save(User user) {
int num=0;
try {
Connection conn=DBUtil.getConnection();
String sql ="insert into user(username,email,password,state,code) values(?,?,?,?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getEmail());
pstmt.setString(3, user.getPassword());
pstmt.setInt(4, user.getState());
pstmt.setString(5, user.getCode());
num=pstmt.executeUpdate();
DBUtil.close(conn,pstmt, null);
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
public int activeUser(String code) {
int num=0;
try {
Connection conn=DBUtil.getConnection();
String sql="update user set state=1 where code=?";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1, code);
num=pstmt.executeUpdate();
DBUtil.close(conn,pstmt,null);
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
}
1.7 在CodeUtil中
public class CodeUtil {
//生成唯一的激活码
public static String generateUniqueCode(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
1.8 在 MailUtils中
public class MailUtil implements Runnable {
private String email;// 收件人邮箱
private String code;// 激活码
public MailUtil(String email, String code) {
this.email = email;
this.code = code;
}
public void run() {
// 1.创建连接对象javax.mail.Session
// 2.创建邮件对象 javax.mail.Message
// 3.发送一封激活邮件
String from = "xxx@qq.com";// 发件人电子邮箱
String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
Properties properties = System.getProperties();// 获取系统属性
properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证
try {
//QQ邮箱需要下面这段代码,163邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
// 1.获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx@qq.com", "xxx"); // 发件人邮箱账号、授权码
}
});
// 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1设置发件人
message.setFrom(new InternetAddress(from));
// 2.2设置接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 2.3设置邮件主题
message.setSubject("账号激活");
// 2.4设置邮件内容
String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/RegisterDemo/ActiveServlet?code="
+ code + "'>http://localhost:8080/RegisterDemo/ActiveServlet?code=" + code
+ "</href></h3></body></html>";
message.setContent(content, "text/html;charset=UTF-8");
// 3.发送邮件
Transport.send(message);
System.out.println("邮件成功发送!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.9 在DBUtil中
public class DBUtil {
private static ComboPooledDataSource cpds=null;
static{
cpds=new ComboPooledDataSource("mysql");
}
public static Connection getConnection(){
Connection connection=null;
try {
connection = cpds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
1.10 所用到数据库表
create table `user`(
id int(11) primary key auto_increment comment '用户id',
username varchar(255) not null comment '用户名',
email varchar(255) not null comment '用户邮箱',
password varchar(255) not null comment '用户密码',
state int(1) not null default 0 comment '用户激活状态:0表示未激活,1表示激活',
code varchar(255) not null comment '激活码'
)engine=InnoDB default charset=utf8;
PS:若想通过代码更好的理解Java发送邮件,请:https://github.com/luomingkui/RegisterDemo
2.Java实现用户登录邮箱验证项目的核心代码:
2.1 点击获取验证码,调用如下:
在AdminUserController中
//获取验证码
@RequestMapping(value = "getVcode")
@ResponseBody
public Map<String, Object> getVcode(HttpServletRequest request) {
String userName = request.getParameter("userName");
Map<String , Object> map =new HashMap<String , Object>(4);
String msg;
try {
String send=adminUserService.genSendVecode(userName);
map.put("status", Constant.SUCCESS);
map.put("msg", send);
return map;
} catch (Exception e) {
if (e instanceof WlbException) {
msg = e.getMessage();
} else {
msg = "管理系统异常,请稍候重试";
}
WlbManageLogger.e(">>>>>> loginIn action时异常,具体原因:%s", e.getLocalizedMessage());
e.printStackTrace();
}
map.put("status", Constant.ERROR);
map.put("msg", msg);
return map;
}
2.2 在AdminUserService中:
@Service
public class AdminUserService {
@Autowired
private AdminUserDao adminUserDao;
@Autowired
private AdminAuthDao adminAuthDao;
private static String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
private static long expireTime = 24 * 60 * 60 * 1000;
public static String generateVcode(String cellphone) {
StringBuilder tmp = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < 6; i++) {
tmp.append(getRandomString(rand.nextInt(36)));
}
return tmp.toString();
}
public static String getRandomString(int num){
return String.valueOf(randString.charAt(num));
}
/**
* 邮箱发送验证码
* @param userEmail
* @return
*/
public String genSendVecode(String userEmail) {
// 1. 校验邮箱是否正确
// 2. 校验邮箱是否合法
// 3. 生成验证码
// 4. 将验证码发送至指定邮箱
if (!RegexUtil.emailVerify(userEmail) || !userEmail.endsWith("@wolaibao.com") || !userEmail.endsWith("@zhongbao.email") ) {
throw new WlbException("用户账户错误,请重新输入");
}
AdminUser adminUser = findAdminByAccount(userEmail);
if (null == adminUser || StringUtils.isBlank(adminUser.getUsername())
|| adminUser.getStatus()!=0) {
throw new WlbException("用户账户错误,请重新输入");
}
AdminAuth lastAuth = adminAuthDao.selectLastVcode(userEmail);
if (lastAuth != null && System.currentTimeMillis() - lastAuth.getUpdateTime().getTime() < (1 * 60 * 1000)) {
throw new WlbException("验证码已经发送至邮箱请勿重复获取");
}
String vcode;
if (lastAuth == null || System.currentTimeMillis() - lastAuth.getExpireTime() > 0) {
vcode = generateVcode(userEmail);
AdminAuth adminAuth = new AdminAuth();
adminAuth.setEmail(userEmail);
adminAuth.setVcode(vcode);
adminAuth.setExpireTime(System.currentTimeMillis() + expireTime);
adminAuthDao.insert(adminAuth);
} else {
vcode = lastAuth.getVcode();
adminAuthDao.update(lastAuth);
}
MsgService.sendMail(userEmail, "管理后台登录验证", "管理后台登录验证码为:" + vcode + "\n有效期为24小时!");
return "我有效期为24来保管理后台登录验证已经发送至邮箱,小时,请注意保管验证码";
}
private AdminUser findAdminByAccount(String userEmail) {
return adminUserDao.selectByAccount(userEmail);
}
}
2.3 在 MsgService 发送邮件接口中:
@Service
public class MsgService {
/**
* 调用邮件发送接口
* @param to
* @param subject
* @param content
*/
public static void sendMail(String to, String subject, String content) {
try {
NetRequest mailRequest = new NetRequest(ClientApiMethod.MSG_EMAIL).setMethod(RequestMethod.GET);
Map<String, Object> params = new HashMap<>();
params.put("to", to);
params.put("content", content);
params.put("subject", subject);
mailRequest.setParams(params);
String msgRsp = new HttpExecutor().execute(mailRequest, String.class);
Loggers.MANAGE.debug("REQUEST email : ", to, "\nRESPONSE", msgRsp.trim());
} catch (Exception e) {
Loggers.MANAGE.error("SendMsg error: \n", e);
}
}
}
2.4 在NetRequest中
public class NetRequest {
/**
* 请求方法
*/
private RequestMethod method = RequestMethod.GET;
/**
* 请求url
*/
private String path;
/**
* 标示
*/
private String tag;
public NetRequest(String url) {
this.path = url;
this.tag = "request-" + hashCode();
}
public RequestMethod getMethod() {
return method;
}
public NetRequest setMethod(RequestMethod method) {
this.method = method;
return this;
}
public String getUrl() {
return path;
}
public NetRequest setUrl(String path) {
this.path = path;
return this;
}
public String getTag() {
return tag;
}
public NetRequest setTag(String tag) {
this.tag = tag;
return this;
}
}
2.5 在ClientApiMethod中
public class ClientApiMethod {
private static final String MSG_HOST = Config.getInstance().getHttpMsgHost();
public static final String MSG_EMAIL = MSG_HOST + "/msg/email.json";
public static final String MSG_EMAIL_HTML = MSG_HOST + "/msg/emailHtml.json";
public static final String APL_NOTIFY = "/taskDistribution/taskDistributionManager.json";
}
2.6 在HttpExecutor中
public class HttpExecutor {
public List<HttpTask> taskList = new ArrayList<HttpTask>();
/**
* 同步执行请求
* @param netRequest 请求
* @param cls 接口响应结果Class
* @param <T>
* @return
*/
public <T> T execute(NetRequest netRequest,Class<T> cls) {
HttpTask httpTask = new HttpTask().setHttpParam(netRequest);
taskList.add(httpTask);
String responseData= httpTask.start();
if(StrUtil.isBlank(responseData))return null;
T response =null;
try {
response = netRequest.getDataParser().parseResponse(responseData, cls);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}