Я пытаюсь написать программу входа в систему, но при смене пароля я должен проверить, в порядке ли текущий пароль, и мое имя пользователя, которое является текстовым полем, возвращает значение null, мое первое имя пользователя работает (при успешном входе в систему), но есть проблема со вторым, поэтому я действительно застрял в своем коде.
package sample;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javax.swing.*;
import java.io.IOException;
import java.sql.*;
import java.util.Optional;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Controller {
@FXML
private PasswordField currentpassword;
@FXML
private PasswordField newPassword;
@FXML
private TextField userName;
@FXML
private PasswordField password;
@FXML
private Button loginButt;
@FXML
private GridPane mainfxml;
Connection con = null;
PreparedStatement preparedStatement;
PreparedStatement savePrePared;
PreparedStatement SidePrepared;
public void initialize() {
}
@FXML
public void loginsuccessful(ActionEvent event) {
String query = "SELECT * FROM login WHERE username = ? " + " AND password = ? ";
try {
con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\mkara\\Desktop\\userpass\\javatest.db");
String pass = password.getText();
preparedStatement = con.prepareStatement(query);
String uname = userName.getText();
preparedStatement.setString(1, uname);
preparedStatement.setString(2, pass);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
loginButt.setOnMouseClicked(mouseEvent -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("login_page.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle(uname + "'s Profile");
stage.setScene(scene);
stage.initOwner(mainfxml.getScene().getWindow());
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
} else {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("faild ");
alert.setHeaderText(null);
alert.setContentText("your login was faild try agin");
alert.showAndWait();
return;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void changepassword(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("passwordChange.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("Change your password");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
public void saveNewPass(ActionEvent event) {
try {
con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\mkara\\Desktop\\userpass\\javatest.db");
String cupass = currentpassword.getText();
String newpass = newPassword.getText();
System.out.println("Cupass" + cupass);
System.out.println("newpass" + newpass);
String uname = userName.getText();
System.out.println(uname);
String query = "SELECT password FROM login WHERE username =" + uname;
String insertNewPass = "UPDATE login set password = " + newpass + "WHERE username =" + uname;
savePrePared = con.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
//if the field were blank
if ((cupass == null) || (newpass == null)) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Empty fields");
alert.setContentText("You did not enter your passwords ");
alert.setHeaderText(null);
alert.showAndWait();
return;
}
while (resultSet.next()) {
String dbpass = resultSet.getString("password");
if (dbpass.equals(cupass)) {
SidePrepared = con.prepareStatement(insertNewPass);
ResultSet resultSet1 = preparedStatement.executeQuery();
if (resultSet1.next()) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Password changed!");
alert.setContentText("Your Password has changed!");
alert.setHeaderText(null);
alert.showAndWait();
return;
}
}//if current pass is wrong
else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Wrong information!");
alert.setContentText("Your Current password is wrong ");
alert.setHeaderText(null);
alert.showAndWait();
return;
}}
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void logout(ActionEvent event){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("exite");
alert.setContentText("Are you sure you want to exite? ");
alert.setHeaderText(null);
Optional<ButtonType> result = alert.showAndWait();
if(result.isPresent() && (result.get() == ButtonType.OK)) {
alert.close();
Platform.exit();
}else{
return;
}
}
}
мой основной f xml
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.PasswordField?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<Label text="Username" GridPane.rowIndex="0" GridPane.columnIndex="0"/>
<TextField fx:id="userName" GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label text="Password" GridPane.rowIndex="1" GridPane.columnIndex="0"/>
<PasswordField fx:id="password" GridPane.rowIndex="1" GridPane.columnIndex="1"/>
<Button fx:id="loginButt" text="Login" GridPane.rowIndex="2" GridPane.columnIndex="1" onAction="#loginsuccessful" />
</GridPane>
мой пароль смена f xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane xmlns:fx="http://javafx.com/fxml"
fx:controller="sample.Controller" alignment="center" hgap="10" vgap="10">
<Label text="Enter your Current Password:" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
<PasswordField fx:id="currentpassword" GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label text="Enter your new password:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<PasswordField fx:id="newPassword" GridPane.rowIndex="1" GridPane.columnIndex="1"/>
<Button text="Save" GridPane.rowIndex="5" GridPane.columnIndex="5" onAction="#saveNewPass"/>
</GridPane>
моя страница входа f xml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<Button text="Logout" GridPane.rowIndex="0" GridPane.columnIndex="0"/>
<Button text="Change your password" GridPane.rowIndex="3" GridPane.columnIndex="0" onAction="#changepassword"/>
</GridPane>
Main
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Login page");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
try {
Connection con = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\mkara\\Desktop\\userpass\\javatest.db");
Statement statement = con.createStatement();
statement.execute("CREATE TABLE IF NOT EXISTS login"
+ "(username TEXT,password text)");
// statement.execute("INSERT INTO login(username,password)" + "VALUES('mahdi','123456')");
ResultSet results = statement.executeQuery("SELECT * FROM login");
while (results.next()) {
System.out.println(results.getString("username") + " "
+ results.getString("password"));
}
results.close();
statement.close();
con.close();
} catch (SQLException e) {
System.out.println("something went wrong" + e.getMessage());
e.printStackTrace();
}
}
}
, и у меня эта ошибка
Caused by: java.lang.NullPointerException