Generating Password Recovery Backend Code with ChatGPT
This article walks through building a complete password‑recovery feature for a Java web application, detailing the workflow, database schema, validation logic, JSP integration, controller design, and optional email/SMS notification code generated by ChatGPT.
The article demonstrates how to build a complete password‑recovery feature for a Java web application using JSP, JavaBeans and a MySQL database.
It first outlines the recovery workflow: user submits phone or email, the system checks existence, sends a verification code via SMS or email, stores the code, the user enters the code and a new password, the system validates the code, checks password strength and history, updates the password, and redirects to the login page. The flow diagram (Figure 4‑3) is shown.
Database schema creation:
CREATE TABLE password(
id INT AUTO_INCREMENT PRIMARY KEY,
uid INT NOT NULL,
password VARCHAR(100) NOT NULL,
FOREIGN KEY(uid) REFERENCES user(id)
);
CREATE TABLE code(
id INT AUTO_INCREMENT PRIMARY KEY,
uid INT NOT NULL,
code CHAR(6) NOT NULL,
FOREIGN KEY(uid) REFERENCES user(id)
);Validation utility ( ValidateUser.java) checks username, phone, email formats and whether a password is a SHA‑256 hash.
package ebusiness;
import java.util.regex.Pattern;
public class ValidateUser{
public boolean isHash(String str){
if(str!=null && str.length()==64 && str.matches("[a-fA-F0-9]{64}")){
return true; // possible SHA256 hash
}
return false;
}
public String validate(User user){
String usernamePattern="^[a-zA-Z0-9]{5,20}$";
String phonePattern="^1[3-9]\d{9}$";
String emailPattern="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
if(!Pattern.matches(usernamePattern,user.getUsername())){
return "账号必须是5-20位字母或数字";
}
if(!Pattern.matches(phonePattern,user.getPhone())){
return "手机号必须符合中国手机号码格式";
}
if(!Pattern.matches(emailPattern,user.getEmail())){
return "Email格式不正确";
}
if(!isHash(user.getPassword())){
return "密码应该哈希进行存储";
}
return "验证成功";
}
}JavaBean PasswordRecovery handles contact checking, verification‑code sending, and password reset logic. Key methods include checkContact, recoverPassword, sendVerificationCode, sendCodeForSMS, sendCodeForEmial, and database interactions.
package ebusiness;
public class PasswordRecovery{
public String checkContact(String contact){
String phonePattern="^1[3-9]\\d{9}$";
String emailPattern="^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
if(!Pattern.matches(phonePattern,contact) && !Pattern.matches(emailPattern,contact)){
return "您输入的手机号或Email格式不正确!";
}
String query="SELECT * FROM user WHERE phone=? OR email=?";
// database lookup omitted for brevity
// send verification code via SMS or Email
return "验证码已发送到您的手机或邮箱";
}
public String recoverPassword(String contact,String identifyingCode,String newPassword,String confirmPassword){
// verification, password history check, hash, update DB
return "密码重置成功";
}
// other helper methods (sendVerificationCode, sendCodeForSMS, sendCodeForEmial, etc.)
}JSP pages VeriCodePage.jsp and RecoverPage.jsp are updated to delegate business logic to the JavaBean and to handle CSRF tokens.
<%@page import="ebusiness.PasswordRecovery" %>
<%@page import="java.sql.*" %>
<%
String contact=request.getParameter("contact");
String message="";
PasswordRecovery recovery=new PasswordRecovery();
message=recovery.checkContact(contact);
request.setAttribute("contactError",message);
RequestDispatcher dispatcher=request.getRequestDispatcher("RecoverPage.jsp");
dispatcher.forward(request,response);
%>Controller classes ( PasswordRecoveryController.java, PasswordRecovery.java, etc.) manage request/response flow, cookie handling, and redirection. Example excerpt:
package ebusiness;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.zaxxer.hikari.HikariDataSource;
import java.net.URLEncoder;
public class PasswordRecoveryController{
private static final Logger logger=Logger.getLogger(PasswordRecoveryController.class);
private HttpServletResponse response;
private HttpServletRequest request;
public PasswordRecoveryController(HttpServletResponse response,HttpServletRequest request){
this.response=response;
this.request=request;
}
public String sendVerificationCode() throws SQLException, IOException{
String contact=request.getParameter("contact");
PasswordRecovery PR=new PasswordRecovery();
try{
String info=PR.sendVerificationCode(contact);
if(info.matches("-?\\d+(\\.\\d+)?")){
CookiesManager myusername=new CookiesManager("uid",info,response,request);
myusername.setCookie();
response.sendRedirect("RecoverPage.jsp");
} else if(info.equals("-1")){
return "系统发生错误,请查看日志!";
} else {
String encodedMessage=URLEncoder.encode(info,"UTF-8");
response.sendRedirect("VeriCodePage.jsp?error="+encodedMessage);
}
}catch(Exception e){
logger.error(e.getMessage());
}
return "0";
}
public String recoverPassword() throws SQLException, IOException{
String identifyingCode=request.getParameter("identifyingCode");
String newPassword=request.getParameter("newPassword");
CookiesManager userId=new CookiesManager("uid",response,request);
String uid=userId.getCookie();
if(uid==null||uid.isEmpty()){
return "请输入验证码后再进入";
}
int uidi=Integer.parseInt(uid);
UserRepository mysql=new UserRepository();
HikariDataSource dataSource=mysql.dataSource;
PasswordRecovery passwordrecovery=new PasswordRecovery();
String info=passwordrecovery.recoverPassword(identifyingCode,newPassword,mysql,uidi);
if(info.equals("0")){
userId.clearCookie();
response.sendRedirect("LoginPage.jsp");
} else {
String encodedMessage=URLEncoder.encode(info,"UTF-8");
response.sendRedirect("RecoverPage.jsp?error="+encodedMessage);
}
Util util=new Util();
util.closePool(dataSource);
return "0";
}
}The article also provides auxiliary code for sending emails (JavaMail) and SMS (Twilio, Alibaba Cloud, Tencent Cloud), including Maven dependencies and example classes ( EmailSender, SmsSender, SendSms).
// Maven dependency for JavaMail
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
public class EmailSender{
public String[] sendMail(){
// SMTP setup and send logic
return new String[]{"0","发送成功"};
}
}
// Twilio SMS example
public class SmsSender{
public static final String ACCOUNT_SID="your_account_sid";
public static final String AUTH_TOKEN="your_auth_token";
public static void main(String[] args){
Twilio.init(ACCOUNT_SID,AUTH_TOKEN);
Message message=Message.creator(new PhoneNumber("+1234567890"),new PhoneNumber("+0987654321"),"Hello, this is a test message from Java!").create();
}
}Finally, it discusses refactoring suggestions: using GET for user‑facing pages, POST for business logic, and reorganising controllers for registration, login and password recovery. Example changes to RegisterPage.jsp and RegisterController.java illustrate how error handling and redirection are streamlined.
Overall, the piece walks through problem definition, database design, validation, code generation, integration into JSP pages, and optional communication channels, offering a reproducible implementation.
Flow diagram:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Woodpecker Software Testing
The Woodpecker Software Testing public account shares software testing knowledge, connects testing enthusiasts, founded by Gu Xiang, website: www.3testing.com. Author of five books, including "Mastering JMeter Through Case Studies".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
