08 November 2016

Struts 2 Framework: Reset Password & Send Email

Reset Password & Send Email (Forgot password)



Cấu trúc project như sau:
Create Database như sau:
getpassword.jsp
getpassword.jsp
Java Struts 2 Framework 2016
<%-- 
    Document   : resetpassword
    Created on : Nov 3, 2016, 8:20:55 PM
    Author     : Lonely
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib  uri="/struts-tags" prefix="s"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <style>
            #bg{background-color: #bce4f7; width: 25%; margin: auto;}
        </style>
    </head>
    <body >
        <div id="bg"><h2>Forgot password</h2>
            <s:form action="getPassword" method="POST">
                <s:textfield name="username" label="Username" placeholder="Enter your username"/>
                <s:textfield name="email" label="Email" placeholder="Enter your email"/>
                <s:submit value="Get Password"/>
            </s:form>
        </div>>
    </body>
</html>
index.jsp
Java Struts 2 Framework 2016
<%-- 
    Document   : index
    Created on : Nov 3, 2016, 8:33:47 PM
    Author     : Lonely
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Welcome to the ShopABC !</h1>
        <h2> 
            <font color="red">Chúc mừng bạn đã reset password thành công!
            <br/> Vui lòng kiểm tra Email của bạn !
            </font>
        </h2>
    </body>
</html>
ActionSupport: GetPasswordActionSupport.java
GetPasswordActionSupport.java
Java Struts 2 Framework 2016
package controller;

import com.opensymphony.xwork2.ActionSupport;
import model.GetPasswordDAO;

/**
 *
 * @author Lonely
 */
public class GetPasswordActionSupport extends ActionSupport {

    private String username;
    private String email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public GetPasswordActionSupport() {
    }

    @Override
    public String execute() throws Exception {
       GetPasswordDAO g = new GetPasswordDAO();
       if(g.checkUser(username, email)){
           return g.updatePassword(username, email) ? "success" : "error";
       }
       return "fail";
    }

}
GetPasswordDAO.java
  • checkUser: username + email có thì true và không thì false
  • updatePassword: Reset password và gửi đến email đó với tin nhắn
GetPasswordDAO.java
Java Struts 2 Framework 2016
package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lonely
 */
public class GetPasswordDAO {

    public boolean checkUser(String username, String email) {
        try {
            String sql = "SELECT * FROM user WHERE username=? and email=?";
            Connection conn = DBUtil.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, email);
            ResultSet rs = stmt.executeQuery();
            int count = 0;
            while (rs.next()) {
                count++;
            }
            if (count == 1) {
                return true;
            }
        } catch (SQLException ex) {
            Logger.getLogger(GetPasswordDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public boolean updatePassword(String username, String email) {
        try {
            String sql = "UPDATE user SET password=? WHERE username=? and email=?";
            Connection conn = DBUtil.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            String password = new RadomString().randomString(6);
            stmt.setString(1, password);
            stmt.setString(2, username);
            stmt.setString(3, email);
            SendEmail s = new SendEmail();
            s.sendEmail(email, password);
            return stmt.executeUpdate() >0;
        } catch (SQLException ex) {
            Logger.getLogger(GetPasswordDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
}
RadomString.java
RadomString.java
Java Struts 2 Framework 2016
package model;

import java.security.SecureRandom;

public class RadomString {

    static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static SecureRandom rnd = new SecureRandom();

    String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        }
        return sb.toString();
    }
}
SendEmail.java
  • Nhập email và password của bạn vào làm mặc định
  • addTable(textMessage) gọi method này để lấy ra html form gửi đến email ta mong muốn

SendEmail.java
Java Struts 2 Framework 2016
package model;

import java.awt.Color;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import static model.Editor.*;

public class SendEmail {

    private final String emailSubject = "The new password send to from giai-ma.blogspot.com";

    public void sendEmail(String emailToAddress, String textMessage) {

        final String username = "giai-ma.@gmail.com";//Enter your email
        final String password = "admin123"; //Enter your password 

        Properties props = new Properties();

        props.put("mail.smtp.user", "username");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");

        props.setProperty("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {
            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailToAddress));
            message.setSubject(emailSubject);
            message.setContent(addTable(textMessage), "text/html; charset=UTF-8");
            // send the email
            Transport.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
} 
Editor.java
Java Struts 2 Framework 2016
package model;

//import java.awt.Color;

/**
 *
 * @author Lonely
 */
public class Editor {

//    public static String addColorHead(String msg, Color color) {
//
//        String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
//        String style = "font-family: cursive;";
//        String href = "<a href=" + "https://giai-ma.blogspot.com" + ">" + msg + " </a>";
//        String colorMsg = "<span><h3 style=" + style + " ><FONT COLOR=\"" + hexColor + "\">" + href + "</FONT></h3></span>";
//
//        return colorMsg;
//    }

    public static String addTable(String msg) {
        String colorMsg = "<table style=\"height: 108px;\" border=\"1\" width=\"487\">\n"
                + "<tbody>\n"
                + "<tr>\n"
                + "<td style=\"text-align: center;\" colspan=\"2\">\n"
                + "<h1><span style=\"color: #ff0000;\"><a title=\"Click v&agrave;o đ&acirc;y để trở về trang ch&iacute;nh\" href=\"http://giai-ma.blogspot.com/\">http://giai-ma.blogspot.com/</a></span></h1>\n"
                + "</td>\n"
                + "</tr>\n"
                + "<tr>\n"
                + "<td style=\"text-align: center;\" colspan=\"2\">\n"
                + "<h1><span style=\"color: #ff0000;\">Ch&uacute;c mừng bạn đ&atilde; c&oacute; mật khẩu mới</span></h1>\n"
                + "</td>\n"
                + "</tr>\n"
                + "<tr>\n"
                + "<td style=\"text-align: center;\" colspan=\"2\">\n"
                + "<h3 style=\"text-align: left;\">Ch&uacute;ng t&ocirc;i đ&atilde; thay đổi mật khẩu của bạn c&aacute;ch đ&acirc;y v&agrave;i ph&uacute;t. Ch&uacute;ng t&ocirc;i đ&atilde; nhận được y&ecirc;u cầu từ&nbsp;bạn.</h3>\n"
                + "<h3 style=\"text-align: left;\">Ch&uacute;ng t&ocirc;i khuy&ecirc;n bạn h&atilde;y đổi mật khẩu ngay khi c&oacute; thể để tr&aacute;nh qu&ecirc;n lần nữa. Trong trường hợp c&oacute; dấu hiệu spam ch&uacute;ng t&ocirc;i sẽ kh&oacute;a t&agrave;i khoản của bạn&nbsp;</h3>\n"
                + "</td>\n"
                + "</tr>\n"
                + "<tr>\n"
                + "<td style=\"text-align: center;\" colspan=\"2\">\n"
                + "<h2>&nbsp;&nbsp;Mật khẩu mới của bạn l&agrave;:&nbsp;<span style=\"text-decoration: underline; color: #3366ff;\">" + msg + "</span></h2>\n"
                + "</td>\n"
                + "</tr>\n"
                + "<tr>\n"
                + "<td style=\"text-align: center;\" colspan=\"2\">\n"
                + "<h2><span style=\"color: #ff0000;\">Cảm ơn bạn đ&atilde; xem thư n&agrave;y!</span><img src=\"https://blogger.googleusercontent.com/img/proxy/AVvXsEhelKJf7Ht5gm4QchBIisA_J9XR-sQ6wpW7cmk5gpqNeH6pDZNWAoiniIOANutokjWx5bKmMXDLskQp-Wn5782_laa6nhhK4fXdo72wKXhz7ebjEftiw4b9i-HfoTgcrgGBjxaGCFyT_BU=s0-d\" alt=\"giai-ma.com\" width=\"460\" height=\"306\" /></h2>\n"
                + "</td>\n"
                + "</tr>\n"
                + "</tbody>\n"
                + "</table>";
        return colorMsg;
    }
} 
Connect data: DBUtil.java
Java Struts 2 Framework 2016
package model;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;

/**
 *
 * @author Lonely
 */
public class DBUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/struts", "root", "1234567");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

}
Download (zip import NetBeans)

1 nhận xét:

 

BACK TO TOP

Xuống cuối trang