I'm creating a web application. I'm using netbeans 7.4 and MySQL 6.1 for my database. I want to change the user's password. The structure of the password that is saved in the database is in md5. So, I have to convert the user's input for current password into md5 first and check the database if there's any match. Right now, I have a form structure in my ChangePassword.jsp. In the form are three fields for the current, new and retype password. Then through a servlet, I am manipulating these pieces of information.
The connection to the database is fine and I can already manage to encrypt the current password into md5. But, when I added a while(rs.next()) loop in my program to loop for all the results of my query, it doesn't work. So it won't forward to the desired jsp. Any suggestions on how I can do this? Any help will be much appreciated. Thanks in advance. This is my code.
try{
ServletContext context = getServletContext();
String currentPassword = request.getParameter("currentPassword");
String newPassword = request.getParameter("newPassword");
String tryNewPassword = request.getParameter("retypePassword");
String pswrd = "";
//For Password Encryption into md5
String md5 = null;
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(currentPassword.getBytes(), 0, currentPassword.length());
md5 = new BigInteger(1, digest.digest()).toString(16);
//Database Connection
Class.forName(context.getAttribute("dbdriver").toString());
String db = context.getAttribute("connstr").toString();
Connection conn = DriverManager.getConnection(db);
Statement stmt = conn.createStatement();
stmt = conn.createStatement();
//Check Database Connection
if (conn != null) {
JOptionPane.showMessageDialog(null, "Connected!");
} else {
JOptionPane.showMessageDialog(null, "Not Connected!");
}
String query = "SELECT password FROM accounts WHERE password='"+md5+"'";
ResultSet rs = stmt.executeQuery(query);
JOptionPane.showMessageDialog(null, "Entering while loop");
while(rs.next()){
if(md5CurrentPasswrd.equals(rs.getString(1))){
if(newPassword == tryNewPassword){
digest.update(newPassword.getBytes(), 0, newPassword.length());
md5NewPasswrd = new BigInteger(1, digest.digest()).toString(16);
String queryUpdate = "UPDATE accounts SET password='"+md5NewPasswrd+"' /n"
+ " WHERE password='"+md5CurrentPasswrd+"'";
PreparedStatement prepStmt = conn.prepareStatement(queryUpdate);
prepStmt.executeUpdate();
response.sendRedirect("/Project1/PasswordSaved.jsp");
}else{
response.sendRedirect("/Project1/PasswordNotSaved.jsp");
}
}else{
response.sendRedirect("/Project1/PasswordNotSaved.jsp");
}
pswrd = rs.getString(1);
JOptionPane.showMessageDialog(null, "Running while loop");
}
JOptionPane.showMessageDialog(null, "End of while loop");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ChangePassword.class.getName()).log(Level.SEVERE, null, ex);
}
Related
I am using Mysql netbeans . I have created a db table "userdetails_summertrainingproject" . In the login form I have two fileds to fill one is "UUId_JTextField" and other is "Password1_JPasswordField". I want to compare that the password value entered by the user is same as that in db for the particular UUId entered by the user. UUid is unique.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = new String(password1);
if(rs.getString(query)==pass1){
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
}
catch(Exception e){
System.out.println("Exception in Login:"+e.getMessage());
}
Above is the code I am using.
The Exception is:
Exception in Login:Column 'SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;' not found.
Try this code, you missed rs.next()
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = Arrays.toString(password1);
rs.next();
if (rs.getString("password").equals(pass1)) {
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
I think it is batter to use another method for get connection string. otherwise you have to write bellow code again and again.
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
EDIT:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
String query = "SELECT UUId FROM userdetails_summertrainingproject;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String UUId = rs.getString("UUId");
System.out.println("UUId " + UUId);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class and add this code. then check this code is working or not.
please make sure port, database name, user and password is correct.
If this is give com.mysql.jdbc.CommunicationsException: Communications link failure. most probably your port is incorrect.
I am use these two libraries.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query="SELECT password FROM tryingtable WHERE name=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
prepstmt.setString(1,jtf.getText());
ResultSet rs=prepstmt.executeQuery();
rs.next();
String result=rs.getString("password");;
char[] pass = jpf.getPassword();
String password1= new String(pass);
if(result.equals(password1))
JOptionPane.showMessageDialog(null, "go!!");
else
JOptionPane.showMessageDialog(null, "no!!");
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
e.getStackTrace();
}
when you want to compare password field to textfield use
char[] pass_char = passwordField.getPassword();
String pass_string = new String(pass_char);
Above code will give you your password field value in string form, then
if(pass_string.equals(textfield))
JOptionPane.showMessageDialog("Password match");
else
JOptionPane.showMessageDialog("Password did not match");
I'm very new to JAVA so this is probably an easy solution.
I'm looking to design a login system using differnt users from a database.
They are seperated by a "Yes" column in the database.
It currently signs in the manager using the IF statement but stops there and won't sign in when using credetials of a staff member.
signIn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
// Gets text from textfields and assigns them to variables
s1 = tfUsername.getText();
s2 = tfPassword.getText();
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM login WHERE UName= '"+s1+"' and PWord = '"+s2+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next())
{
String Username = rs.getString("UName");
String Password = rs.getString("PWord");
String staff = rs.getString("Staff");
String management = rs.getString("Management");
if(Username.equals(s1) & Password.equals(s2) & management.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1 );
ManagerDashboard.main(args);
signInFrame.setVisible(false);
}
if(Username.equals(s1) & Password.equals (s2) & staff.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1);
StaffDashboard.main(args);
signInFrame.setVisible(false);
}
}
else
{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
// SQL Catch block to catch errors
catch(SQLException s){
}
// Catch block to catch ActionListener errors
catch (Exception e1){
}
};
});
code in update button
String password = new String(oldPass.getPassword());
String newPassword = new String(newPass.getPassword());
String realpass = zz.getText();
String us = z.getText();
if(password.equals(realpass))
{
System.out.println("ok");
String query = "UPDATE user SET password = '"+newPassword+"' WHERE username = '"+us+"'";
try{
Statement st = (Statement) con.prepareStatement(query);
int i = st.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null, "Ooopps! I guess you should call your programmer. ^^");
}
}catch(Exception e){
System.out.println(e);
}
}
code in log in
Methods m = new Methods();
String pass = new String (password.getPassword());
String user = username.getText();
if(m.logInUser(user, pass)==true){
form2 f = new form2();
f.setUser(user);
f.setPass(pass);
f.setVisible(true);
this.dispose();
}....and so on....
code for method log in user
public boolean logInUser(String user, String pass){ //true = nakarecord na sa database login form
try{
String query = "Select * from user where username = ? && password = aes_encrypt('"+pass+"', 'nicanor')";
PreparedStatement pst = (PreparedStatement) con.prepareStatement(query);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}
else{
return false;
}
}
catch(Exception e){
System.out.println(e);
return false;
}
}//logInUser
it says successfully connected in sql and the database is updated but i cant see the next form that should pop up after i entered the updated password
There are few problems with your code:
(1) In your update() logic, you are using the mix of PreparedStatement and Statement together, rather use always use PreparedStatement to bind the input parameters, otherwise they (statements/queries) are prone to SQL injection attacks.
You can refer the below code with inline comments to bind the input parameters with PreparedStatement:
//Write the SQL query with ? to bind the parameters in PreparedStatement
String query = "UPDATE user SET password = ? WHERE username = ?";
PreparedStatement pstmt = null;
try{
//create the PreparedStatement object
pstmt = con.prepareStatement(query);
//bind the input parameters using setString()
pstmt.setString(1, newPassword);
pstmt.setString(2, us);
//execute the prepare statement now
int i = pstmt.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password
is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null,
"Ooopps! I guess you should call your programmer. ^^");
}
} catch(Exception e){
System.out.println(e);
} finally {
if(pstmt != null)
pstmt.close();
if(con != null)
con.close();
}
Also, remember that database resources are costly and you need to close the resources in the finally block as shown above, otherwise you will end up with resource leaks.
(2) In your logInUser() logic, you are using && which is incorrect, rather in sql you need to use AND operator as shown below:
String query = "Select * from user where username = ?
AND password = aes_encrypt('"+pass+"', 'nicanor')";
try {
Connection c = DB.getCon();
Statement s = c.createStatement();
s.executeUpdate("INSERT INTO login(LogID, UserName, Password) VALUES('"+jTextField1.getText()+"', '"+jTextField2.getText()+"', '"+jPasswordField1.getPassword()+"')");
} catch (Exception e) {
e.printStackTrace();
}
autoGen();
clear();
I code this to my new login account creating form but the password is save like encrypted then i code login page like this it want do anything and there is no errors
String user = jTextField1.getText();
String pass = new String(jPasswordField1.getPassword());
try {
ResultSet rs = DB.getCon().createStatement().executeQuery("select * from login where UserName='" + user + "' and Password = '" + pass + "'");
if (rs.first()) {
if (rs.first()) {
Main_Page pat1 = new Main_Page();
pat1.setVisible(true);
Login_Page.this.setVisible(false);
} else {
jLabel6.setText("Login faild");
}
}`enter code here`
} catch (Exception e) {
e.printStackTrace();
}
please anyone help me
Examining the code you provided, one problem appears to be that you have redundant/nested if statements with no else clause on the outer if statement. This would cause the behavior you described if the account was not found in the query. Try removing the outer if statement.
I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?
Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement
You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says
Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.
Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`