java—如何将值从dao发送回servlet?

qmb5sa22  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(347)

我对如何进行有个问题。用户输入电子邮件并单击忘记密码。然后servlet将调用dao来检查电子邮件是否存在,如果存在,dao将重置密码。我希望dao将重置密码发送回servlet,并重定向另一个servlet以将电子邮件发送回具有重置密码的用户。有人能解释我怎么做吗?
下面是我的支票

public class CheckEmailForgotDao{

String url = "jdbc:mysql://localhost:3308/mywebapp";
String username = "root";
String password = "root";
String sql = "SELECT * FROM users WHERE email=?";

public boolean check(String uname) {

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, username, password);
        PreparedStatement st = con.prepareStatement(sql);
        st.setString(1, uname);

        ResultSet rs = st.executeQuery();

        if (rs.next()) {

            String randomPassword = RandomStringUtils.randomAlphanumeric(10);
            String resetsql = "UPDATE users SET password = ? WHERE email = ?";
            PreparedStatement resetst = con.prepareStatement(resetsql);
            resetst.setString(1, randomPassword);
            resetst.setString(2, uname);

            System.out.println(resetst);
            resetst.executeUpdate();

        }

        return true;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

}

下面是我的servlet

@WebServlet("/forgotpassword")
public class ResetPasswordServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public ResetPasswordServlet() {
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String recipient = request.getParameter("email");
    String uname = recipient;

    CheckEmailForgotDao dao = new CheckEmailForgotDao();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (dao.check(uname)) {

        request.getRequestDispatcher("/SendEmailResetPassword").include(request, response);

    } else {

        request.getRequestDispatcher("index.html").include(request, response);
        out.println("<script>document.getElementById('err-forgot').innerHTML= 'Email does not exist!'; </script>");

    }

}

}
rfbsl7qr

rfbsl7qr1#

我终于可以做到了。下面是我的代码。
-forgotpasswordservlet->checkemailforgot
-checkemailforget->检查电子邮件是否存在->重置密码->
-forgotpasswordservlet-forgotpasswordservlet->通过电子邮件查询密码->emailforgotdao
-emailforgotdao->sendmail->forgotpasswordservlet->显示已发送的电子邮件

@WebServlet("/forgotpassword")
public class ResetPasswordServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public ResetPasswordServlet() {
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String recipient = request.getParameter("email");
    String uname = recipient;

    CheckEmailForgotDao dao = new CheckEmailForgotDao();

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();     

    if (dao.check(uname)) {

        String url = "jdbc:mysql://localhost:3308/mywebapp";
        String username = "root";
        String password = "root";
        String sql = "SELECT * FROM users WHERE email=?";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, username, password);
            PreparedStatement st = con.prepareStatement(sql);
            st.setString(1, uname);

            ResultSet rs = st.executeQuery();

            if (rs.next()) {
                String newpassword = rs.getString(3);

                EmailForgotDao emaildao = new EmailForgotDao();
                if (emaildao.sendemailforgot(uname, newpassword)) {

                    request.getRequestDispatcher("index.html").include(request, response);
                    out.println(
                            "<script>document.getElementById('msg-forgot').innerHTML= 'Reset password sent!'; </script>");

                }
            } else {
                request.getRequestDispatcher("index.html").include(request, response);
                out.println(
                        "<script>document.getElementById('msg-forgot').innerHTML= 'Error!'; </script>");
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

    } else {

        request.getRequestDispatcher("index.html").include(request, response);
        out.println("<script>document.getElementById('msg-forgot').innerHTML= 'Email does not exist!'; 
 </script>");

    }

}

上面的servlet使用下面的checkemailforgotdao来检查电子邮件是否存在。
1.如果存在,此dao将重置密码并返回true。
如果它不存在,这个dao将返回false,servlet将显示email不存在。
3.如果下面的checkemailforgotdao返回true,servlet将查询并获取新的重置密码。
4.然后servlet将使用它调用另一个emailforgottao。

public class CheckEmailForgotDao{
 String url = "jdbc:mysql://localhost:3308/mywebapp";
 String username = "root";
 String password = "root";
 String sql = "SELECT * FROM users WHERE email=?";

 public boolean check(String uname) {

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, username,password);
        PreparedStatement st = con.prepareStatement(sql);
        st.setString(1, uname);

        ResultSet rs = st.executeQuery();

        if (rs.next()) {

            String randomPassword = RandomStringUtils.randomAlphanumeric(10);
            String resetsql = "UPDATE users SET password = ? WHERE email = 
  ?";
            PreparedStatement resetst = con.prepareStatement(resetsql);
            resetst.setString(1, randomPassword);
            resetst.setString(2, uname);

            System.out.println(resetst);
            resetst.executeUpdate();

        }

        return true;

    } catch (Exception e) {

        e.printStackTrace();
    }

    return false;
    }

下面emailforgotdao将发送电子邮件并返回true。然后servlet将显示reset password sent!
如果由于错误返回false,servlet将显示error。

public class EmailForgotDao {

public static class SMTPAuthenticator extends Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("youremail@gmail.com", 
"yourpassword");
    }
}

public boolean sendemailforgot(String uname, String newpassword) {

    String d_uname = "youremail@gmail.com";
    String d_password = "yourpassword";
    String d_host = "smtp.gmail.com";
    int d_port = 465;

    String m_to = uname;
    String m_from = "soemoesmarttoy1@gmail.com";
    String m_subject = "Your Password has been reset";
    String m_text = "Hi your new password is " + newpassword;
    String abc = "text/plain";

    Properties props = new Properties();

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session ses = Session.getDefaultInstance(props, auth);

    MimeMessage msg = new MimeMessage(ses);

    try {
        msg.setContent(m_text, abc);
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(m_from));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

        Transport transport = ses.getTransport("smtps");
        transport.connect(d_host, d_port, d_uname, d_password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        return true;

    } catch (Exception e) {
        System.out.println(e);

    }

    return false;
}
}

相关问题