Java Project JSP JDBC Java Program Core Java Demo MORE

How to change password in JSP


To change password in JSP you must have a table in the database that contain the current password(the password you going to change).

In this example my current password is "Admin@123" and i am going to change into as "Admin@12345".

login.sql

CREATE TABLE `login` (                
    `id` int(10) NOT NULL,                       
    `currentPassword` varchar(10) DEFAULT NULL,      
    `Newpass` varchar(10) DEFAULT NULL,      
    PRIMARY KEY (`id`)                           
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

index.html

<html>
<form action="changePassword.jsp" method="post">
<table>
<tr><td>Current Password</td><td><input type="password" name="current" ></td></tr>
<tr><td>New Password</td><td><input type="password" name="new"></td></tr>
<tr><td>Confirm Password</td><td><input type="password" name="confirm"></td></tr>
<tr><td><input type="submit" value="Change Password"></td></tr>
</table>
</form>
</html>

changePassword.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%
String currentPassword=request.getParameter("current");
String Newpass=request.getParameter("new");
String conpass=request.getParameter("confirm");
String connurl = "jdbc:mysql://localhost:3306/user";
Connection con=null;
String pass="";
int id=0;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connurl, "root", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from login where password='"+currentPassword+"'");
while(rs.next()){
id=rs.getInt(1);
pass=rs.getString(3);
}
System.out.println(id+ " "+pass);
if(pass.equals(currentPassword)){
Statement st1=con.createStatement();
int i=st1.executeUpdate("update login set password='"+Newpass+"' where id='"+id+"'");
out.println("Password changed successfully");
st1.close();
con.close();
}
else{
out.println("Invalid Current Password");
}
}
catch(Exception e){
out.println(e);
}
%>

Output

Current Password
New Password
Confirm Password