java web通过163邮箱重置登录密码

来源:互联网 发布:淘宝客网站模板 编辑:程序博客网 时间:2024/05/14 20:11

许多开发项目中都需要用到邮箱实现找回密码或者重置密码的功能,就是改变数据库中存储的密码。根据在网上找的一些Javaweb通过邮箱找回密码的例子并和带我的研究生学长一起改了改,也成功开发了一个重置密码的小程序。
开发工具:myeclipse10。MySQL数据库。
项目结构:
这里写图片描述

这里写图片描述
password.dat里面存放的是163邮箱的授权码,不是登录密码,关于授权码可以自行百度了解下,并且在运行程序是,163邮箱要处于登录状态
下面将各个包中的代码包中的代码粘贴出来
com.ningmeng.util

package com.ningmeng.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;   public class DbUtil {    private String url="jdbc:mysql://localhost:3306/db-jsp";    private String user="root";    private String password="123";    private String driver="com.mysql.jdbc.Driver";    public Connection getCon() throws Exception{                 Class.forName(driver);                Connection con=DriverManager.getConnection(url, user, password);                return con;    }    public static void getClose(Connection con) throws SQLException{        if(con!=null){            con.close();        }    }}

org.study.accountactivate.dao

package org.study.accountactivate.dao;  import org.study.accountactivate.domail.User;  public interface UserDao {      User findUserByNameOrEmail(String nameOrEmail);      boolean UpdateByName(String userName,String newPassword);}  

org.study.accountactivate.dao.impl

package org.study.accountactivate.dao.impl;  import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Collection;  import java.util.HashMap;  import java.util.Iterator;  import java.util.Map;  import java.util.UUID;  import org.study.accountactivate.dao.UserDao;  import org.study.accountactivate.domail.User;  import com.ningmeng.util.DbUtil;public class UserDaoImpl implements UserDao {      private static UserDaoImpl instance = new UserDaoImpl();      private UserDaoImpl() {}      public static UserDaoImpl getInstance() {          return instance;      }      Map<Integer,User> users = new HashMap<Integer, User>();      int nextId = 1;      @Override      public User findUserByNameOrEmail(String nameOrEmail) {          User user=new User();        DbUtil db=new DbUtil();        String sql="select * from user where email=?";        PreparedStatement ps;        try{            Connection conn=db.getCon();            ps=conn.prepareStatement(sql);            ps.setString(1, nameOrEmail);            ResultSet rs=ps.executeQuery();            if(rs.next()){                user.setUserName(rs.getString(2));                user.setPassword(rs.getString(3));                user.setEmail(rs.getString(5));            }               return user;        }catch(SQLException e)        {            e.printStackTrace();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return null;    }     public boolean UpdateByName(String userName,String newPassword){        boolean flag=false;        DbUtil db=new DbUtil();        String sql="update user set password=? where userName=?";        PreparedStatement ps;        try{            Connection conn=db.getCon();            ps=conn.prepareStatement(sql);            ps.setString(1,newPassword);            ps.setString(2, userName);            flag=ps.executeUpdate()>0;          }catch(SQLException e)        {            e.printStackTrace();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return flag;    }}  

org.study.accountactivate.domail

package org.study.accountactivate.domail;  public class User {      // 用户名      private String userName;      // 密码      private String password;      // email      private String email;      // 是否激活      public String getUserName() {          return userName;      }      public void setUserName(String userName) {          this.userName = userName;      }      public String getPassword() {          return password;      }      public void setPassword(String password) {          this.password = password;      }      public String getEmail() {          return email;      }      public void setEmail(String email) {          this.email = email;      }  }  

org.study.accountactivate.util

package org.study.accountactivate.util;  import java.io.IOException;  import java.io.InputStream;  import java.util.Date;  import java.util.Properties;  import javax.mail.Authenticator;  import javax.mail.Message.RecipientType;  import javax.mail.PasswordAuthentication;  import javax.mail.Session;  import javax.mail.Transport;  import javax.mail.internet.InternetAddress;  import javax.mail.internet.MimeMessage;  import org.study.accountactivate.domail.User;  public class EmailUtils {      private static final String FROM = "linmao510322@163.com";      /**      * 发送重设密码链接的邮件      */      public static void sendResetPasswordEmail(User user ,String userEmail) {          Session session = getSession();          MimeMessage message = new MimeMessage(session);          try {              message.setSubject("找回您的帐户与密码");              message.setSentDate(new Date());              message.setFrom(new InternetAddress(FROM));              message.setRecipient(RecipientType.TO, new InternetAddress(userEmail));              message.setContent("要使用新的密码, 请使用以下链接启用密码:<br/><a href='" + GenerateLinkUtils.generateResetPwdLink(user) +"'>点击重新设置密码</a>","text/html;charset=utf-8");              // 发送邮件              Transport.send(message);          } catch (Exception e) {              e.printStackTrace();          }      }      public static Session getSession() {          Properties props = new Properties();          props.setProperty("mail.transport.protocol", "smtp");          props.setProperty("mail.smtp.host", "smtp.163.com");          props.setProperty("mail.smtp.port", "25");          props.setProperty("mail.smtp.auth", "true");          Session session = Session.getInstance(props, new Authenticator() {              @Override              protected PasswordAuthentication getPasswordAuthentication() {                  String password = null;                  InputStream is = EmailUtils.class.getResourceAsStream("password.dat");                  byte[] b = new byte[1024];                  try {                      int len = is.read(b);                      password = new String(b,0,len);                  } catch (IOException e) {                      e.printStackTrace();                  }                  return new PasswordAuthentication(FROM, password);              }          });          return session;      }  }  

org.study.accountactivate.util

package org.study.accountactivate.util;  import org.study.accountactivate.domail.User;  /**  * 生成帐户激活、重新设置密码的链接  */  public class GenerateLinkUtils {      /**      * 生成重设密码的链接      */      public static String generateResetPwdLink(User user) {          return "http://localhost:8080/dddd/resetPassword.jsp";    }  }  

org.study.accountactivate.web.servlet

package org.study.accountactivate.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.study.accountactivate.dao.UserDao;import org.study.accountactivate.dao.impl.UserDaoImpl;import org.study.accountactivate.domail.User;import org.study.accountactivate.util.EmailUtils;/** * 发送重设密码申请的链接 */public class ForgotPwdServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);        String Email = request.getParameter("Email");        UserDao userDao = UserDaoImpl.getInstance();        User user = userDao.findUserByNameOrEmail(Email);        if (user == null) {            request.setAttribute("errorMsg", Email + ",不存在!");            request.getRequestDispatcher("/forgotPwd.jsp").forward(request, response);            return;        }        // 发送重新设置密码的链接        EmailUtils.sendResetPasswordEmail(user,Email);        request.setAttribute("sendMailMsg", "您的申请已提交成功,请查看您的"+user.getEmail()+"邮箱。");        request.getRequestDispatcher("/forgotPwdSuccess.jsp").forward(request, response);    }}

org.study.accountactivate.web.servlet

package org.study.accountactivate.web.servlet;  import java.io.IOException;  import java.util.HashMap;  import java.util.Map;  import javax.servlet.ServletException;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import org.study.accountactivate.dao.UserDao;  import org.study.accountactivate.dao.impl.UserDaoImpl;  import org.study.accountactivate.domail.User;  /**  * 重新设置密码  */  public class ResetPasswordServlet extends HttpServlet {      private static final long serialVersionUID = 1L;      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          }      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          doGet(request, response);          String userName = request.getParameter("userName");          String newPassword = request.getParameter("newPassword");          String newPassword2 = request.getParameter("newPassword2");          Map<String,String> errors = new HashMap<String, String>();          if (newPassword == null || "".equals(newPassword)) {              errors.put("newPassword", "新密码不能为空!");          }          if (newPassword2 == null || "".equals(newPassword2)) {              errors.put("newPassword2", "确认新密码不能为空!");          }          if (!newPassword.equals(newPassword2)) {              errors.put("passwordError", "两次输入的密码不一致!");          }          if (!errors.isEmpty()) {              request.setAttribute("errors", errors);              request.getRequestDispatcher("/resetPassword?userName=" + userName).forward(request, response);              return;          }          UserDao userDao = UserDaoImpl.getInstance();           boolean flag = userDao.UpdateByName(userName,newPassword);          request.getRequestDispatcher("/resetPasswordSuccess.jsp").forward(request, response);    }  }  

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  <display-name></display-name>   <welcome-file-list>    <welcome-file>login.jsp</welcome-file>  </welcome-file-list>  <servlet>    <description>找回密码页面</description>    <display-name>ForgotPwdUIServlet</display-name>    <servlet-name>ForgotPwdUIServlet</servlet-name>    <servlet-class>org.study.accountactivate.web.servlet.ForgotPwdUIServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ForgotPwdUIServlet</servlet-name>    <url-pattern>/forgotPwdUI</url-pattern>  </servlet-mapping>  <servlet>    <description></description>    <display-name>ForgotPwdServlet</display-name>    <servlet-name>ForgotPwdServlet</servlet-name>    <servlet-class>org.study.accountactivate.web.servlet.ForgotPwdServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ForgotPwdServlet</servlet-name>    <url-pattern>/forgotPwd</url-pattern>  </servlet-mapping>  <servlet>    <description>重新设置密码</description>    <display-name>ResetPasswordServlet</display-name>    <servlet-name>ResetPasswordServlet</servlet-name>    <servlet-class>org.study.accountactivate.web.servlet.ResetPasswordServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ResetPasswordServlet</servlet-name>    <url-pattern>/resetPassword</url-pattern>  </servlet-mapping>  <servlet>    <description>重新设置密码页面</description>    <display-name>ResetPasswordUIServlet</display-name>    <servlet-name>ResetPasswordUIServlet</servlet-name>    <servlet-class>org.study.accountactivate.web.servlet.ResetPasswordUIServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>ResetPasswordUIServlet</servlet-name>    <url-pattern>/resetPasswordUI</url-pattern>  </servlet-mapping></web-app>

forgotPwd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>重设密码申请</title></head><body>    <form action="${pageContext.request.contextPath}/forgotPwd" method="post">        <span style="color: red">${requestScope.sendMailMsg}</span>        邮箱:<input type="text" name="Email" /><span style="color: red">${requestScope.errorMsg}</span><br/>        <input type="submit" value="提交" /><a href=""></a>    </form></body></html>

forgotPwdSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>重新设置密码申请成功</title></head><body>    <h3>${requestScope.sendMailMsg}</h3></body></html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登陆</title><style type="text/css">    .error {        color: red;        padding-left:2px;    }</style></head><body>        <a href="${pageContext.request.contextPath}/forgotPwd.jsp">忘记密码?</a>&nbsp;</body></body></html>

resetPassword.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>重新设置密码</title><style type="text/css">    .error {        color: red;        padding-left:5px;    }</style></head><body>    <form action="${pageContext.request.contextPath}/resetPassword" method="post">        <span class="error" style="display: block;">${errors.passwordError}</span>        用户名:<input type="text" name="userName" value="${userName}" /><br/>        新密码:<input type="password" name="newPassword" /><span class="error">${errors.newPassword }</span><br/>        确认新密码:<input type="password" name="newPassword2"/><span class="error">${errors.newPassword2 }</span><br/>        <input type="submit" value="修改" />    </form></body></html>

resetPasswordSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>密码修改成功</title></head><body>    <h3>密码修改成功!</h3><a href="${pageContext.request.contextPath }/login">登录</a></body></html>

数据库设计
这里写图片描述

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

0 0
原创粉丝点击