I'm trying to create an application using JavaFX. I want to get current logged userid and username, after successful login. I want to display it is in the home page. How can i do this? please help
MediaController.java
#FXML
private Label tf_getname;
#FXML
void happyButton(ActionEvent event) {
DbConnect dbconnect=new DbConnect();
Connection conn=dbconnect.getConnection();
String username = tf_getname.getText();
// String source1 = event.getSource().toString(); //yields complete string
//String source2 = event.getPickResult().getIntersectedNode().getId(); //returns JUST the id of the object that was clicked
// System.out.println("Full String: " + source1);
// System.out.println("Just the id: " + source2);
// System.out.println(" " + source2);
try {
String sql = "SELECT name FROM users WHERE name='"+username+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
tf_getname.setText(rs.getString("name"));
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
Let me get this straight, you have the user login, then change the scene to a main window, but you want to remember the user that logged in and display that username on the homepage?
Sounds like you will have to pass data between scenes.
For that you will need to approach this in OOP. Have a object class representing your user with all the getters and setters.
public class User {
private String email;
public User(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
When you connect to the database at login, validate user then instantiate an object of the "User" class for example, then pass it to the mainwindow scene your are loading.
public class LoginController implements Initializable {
public User user;
// All your FXML code
#FXML
void handleLogin(ActionEvent actionEvent) throws IOException {
// Do your validation and then call the changeToMainWindow()
changeToMainWindow();
}
}
Have a "initData" class or something in the mainwindowcontroller.
Like
public void initData(User user) {
selectedUser = user;
labelUser.setText(selectedUser.getEmail());
}
Then from your login class, upon validation, send the data to the mainwindow before changing your scene by instantiating your User, then passing the object to the initData method from your second scene.
//User validation, then:
// Get the FXMLLoader then
//Instantiate the mainwindow controller:
public void changeToMainWindow() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("mainwindow.fxml"));
Parent root = loader.load();
Scene mainScene = new Scene(root);
// access the controller
MainWindowController mainWindowController = loader.getController();
mainWindowController.initData(user);
Stage primaryStage = (Stage) loginButton.getScene().getWindow();
primaryStage.setScene(mainScene);
primaryStage.show();
}
Then upoin login, use the changeToMainWindow() method and it'll pass the user.
In the above example I am simply passing email, but you get the point.
I think there is something wrong with your statement. Try out the following way to set up and execute a Statement.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from test");
while(rs.next()){
System.out.println(rs.getString("name"));
con.close();
}
}catch(Exception e){
}
Related
first of all I know this is duplicated question. But I've search and tried from stackoverflow listed on Google to quora but still cant resolve my Get method still return null.
This is my class loginModel.java under package com.hello.model
public class loginModel {
public String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
}
This is my loginView.java under package com.hello.view
import com.hello.model.loginModel;
public class loginView extends javax.swing.JFrame {
loginModel login = new loginModel();
public loginView() {
initComponents();
this.setLocationRelativeTo(null);
loginFunction();
}
private void loginFunction(){
String username = usernameText.getText();
String password = passwdText.getText();
String query = "select * from access where username = '" +username+ "' AND password = '" +password+"'";
databaseConnect db = new databaseConnect();
try (Connection con = DriverManager.getConnection(db.url, db.user, db.password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if(rs.next()) {
if(username.equals(rs.getString("username")) && password.equals(rs.getString("password"))){
JOptionPane.showMessageDialog(null, "login Success");
String name = rs.getString("name");
String privilege = rs.getString("privilege");
login.setUsername(name);
menu = new menuView();
menu.setVisible(true);
this.setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null, "username or password incorrect");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want call my username from menuView.java under package com.hello.view after login success
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
}
As per my question when I call Get method from loginModel, messagebox return null.
I've tried:
Put system.out.println directly in loginModel.java, value return
and call system.out.println in menuView.java at the same time but value return null. How?
Send string between jframe with menu = menuView(username) in loginView.java and retrieve in menuView.java, value return null
Using no model and create set string in loginView and call it in
menuView, value return null
I need values that I want to use in another class/package/jframe. Am I doing wrong?
I am not well versed in Swing but I can see the problem, just not the exact solution.
Your code creates an instance of loginModel in both the menuView and in loginView. Then in loginView is sets the name in the instance it has, in in menuView it gets the name from its own instance.
You need to create a single instance of the model and share it between the two views.
In a pojo way I would pass the loginModel to both "views" in a constructor.
menu = new menuView(login);
And in menuView
public menuView(loginModel login) {
this.login = login;
}
Your menuView instance isn't using the loginModel class that you instantiate in loginView, it's using the new one you created using new menuView() when you initialized the login variable in the menuView class. You just need to add a setter method for the loginModel attribute in the menuView class like this:
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
public void setLogin(loginModel loginModel) {
this.login = loginModel;
}
}
Then call the setter in loginView.loginFunction like this:
... code before
login.setUsername(name);
menu = new menuView();
menu.setLogin(login);
menu.setVisible(true);
this.setVisible(false);
... code after
Notice the only changes to your code are the added setLogin method on the menuView class and the call to menu.setLogin(login) in loginView.loginFunction.
You need to think in stages/steps. Login is a single step, it has one of two outcomes, success or failure.
Your app needs to perform this step and take appropriate action based on the outcome of the result.
You also need to think about "separation of responsibility" - in this case, it's not really the responsibility of the loginView to perform the login operation, it just coordinates the user input.
The responsibility actually falls to the LoginModel
// Just a custom exception to make it easier to determine
// what actually went wrong
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
// LoginModel ... that "does" stuff
public class LoginModel {
private String username;
DatabaseConnect db;
public LoginModel(DatabaseConnect db) {
this.db = db;
}
// I would consider not doing this. You need to ask what reasons would
// the app need this information and expose it only if there is really a
// reason to do so
public String getUsername() {
return username;
}
public boolean isLogedIn() {
return username != null;
}
public void validate(String username, String password) throws SQLException, LoginException {
String query = "select * from access where username = ? AND password = ?";
try ( Connection con = DriverManager.getConnection(db.url, db.user, db.password); PreparedStatement st = con.prepareStatement(query)) {
st.setString(1, username);
st.setString(2, password);
try ( ResultSet rs = st.executeQuery()) {
if (rs.next()) {
this.username = username;
} else {
throw new LoginException("Invalid user credentials");
}
}
}
}
}
This is an overly simplified example, as the actual responsibility for performing the login should fall to the controller, which would then generate the model, but I'm getting ahead of myself.
Because the flow of the app shouldn't be controlled/determined by the login view, the LoginView should itself be a dialog. This way, it can be shown when you need it, it can perform what ever operations it needs and then go away, leaving the rest of the decision making up to who ever called it
public class LoginView extends javax.swing.JDialog {
private LoginModel model;
public LoginView(LoginModel model) {
initComponents();
setModal(true);
this.model = model;
this.setLocationRelativeTo(null);
}
// This will get executed when the user taps some kind of "perform login button"
private void loginFunction() {
String username = usernameText.getText();
String password = passwdText.getText();
try {
model.validate(username, password);
dispose()
} catch (SQLException ex) {
// This should probably be considered a fatal error
model = null;
dispose();
} catch (LoginException ex) {
JOptionPane.showMessageDialog(this, "Login vaild");
}
}
}
This then means you might put it together something like this...
DatabaseConnect db = new DatabaseConnect();
LoginModel model = new LoginModel(db);
LoginView loginView = new LoginView(model);
// Because we're using a modal dialog, the code execution will wait here
// till the window is disposed/closed
loginView.setVisible(true);
if (loginView.model != null) {
// model is now valid and can continue to be used
// in what ever fashion you need
} else {
JOptionPane.showMessageDialog(null, "Fatal Error");
}
This takes you a step closer to a more decoupled solution, where you feed information to the classes when they need it, rather than the classes making decisions about what they should create/use.
It also moves you a step closer to re-usable classes, as they do their specific job and nothing more.
You might find taking the time to read up on "model-view-controller" will help you better understand this approach
I am trying to create program which will display or hide button depended on role of the user, depend if user is Administrator or someone else.
So in this case i am passing String from "Login" frame to "Menu" frame and if is String equal to my requirement, it show button, if is not, then hide button, on "Menu" frame. Now this is working with string. But how to do same thing but to pull Role from database? I have that field in database but i don't know how exactly to do that. - My fields in database are username, password and role.
Thanks!
Login frame
JButton btnLogin = new JButton("Login !");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String username = textUsername.getText();
String password = passwordField.getText();
String S = "Administrator";
String query = "SELECT * FROM ADMINISTRATION where username=? and password=?;";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet set=stmt.executeQuery();
if (set.next()) {
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(S);
stmt.close();
connection.close();
}
else {
JOptionPane.showMessageDialog(contentPane, "Pogrešno korisničko ime ili lozinka !", "Greška !", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Menu frame
public void Proba(String S) {
if (S.equals("Administrator")) {
btnOption.setVisible(true);
}
else {
btnOption.setVisible(false);
}
}
Ok, I'm assuming this is an academic project.
So, you have a ResultSet and you are iterating over it, when you call the "next" method you move to the next (in this case the first) row.
Now you have a row, you need to call a method that retrieves a String value from a column (in this case role), check the documentation:
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
You have a "getString" method that needs a column name, and will return the string valuo from that column.
An example could be:
if (set.next()) {
String role = set.getString("role");
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(role);
stmt.close();
connection.close();
}
This question already has answers here:
Pass data between classes
(2 answers)
Closed 5 years ago.
Given a login window which requires 2 inputs from the user: username & password.
After being identified successfully the user gets redirected to the main window.
Here I want to display his or her username but I'm receiving null.
This is my current code:
Login class:
private void LoginUser(String username, String password)
{
user = username;
pass = password;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = MainEngine.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT username FROM users WHERE username ='"+user+"' AND password ='"+getMD5Hex(pass)+"'");
if(rs.next()) // Successful login
{
Window_AfterLogin window_afterlogin = new Window_AfterLogin();
window_afterlogin.setVisible(true);
this.dispose();
}
else
{
label_info.setText("Wrong credentials");
}
}
catch(Exception e)
{
System.err.println(e);
}
}
public String getUserName()
{
return user;
}
Note: user and pass variables are global.
Window_AfterLogin class:
public Window_AfterLogin() {
initComponents();
Window_Login window_login = new Window_Login();
System.out.println(window_login.getUserName());
}
Your Window_AfterLogin() constructor initializes another Window_Login which means there is the username, which you try to retrieve by window_login.getUserName() - null.
In your after login code you could add another field username:
public Window_AfterLogin{
private String username;
public Window_AfterLogin(String username){
initComponents();
this.username = username;
}
}
Where inside your LoginUser class you have to change the code accordingly:
if(rs.next()) // Successful login
{
Window_AfterLogin window_afterlogin = new Window_AfterLogin(user);
window_afterlogin.setVisible(true);
this.dispose();
}
Note:
Your application is vulnerable to SQL-Injections. Please read about prepared statements and how SQL-Injections work in theory and try to prevent them.
https://de.wikipedia.org/wiki/SQL-Injection
https://www.tutorialspoint.com/javaexamples/jdbc_prepared_statement.htm
In the constructor, you are creating a new instance of the Window_Login class and not setting the username.
I am stuck with this for a while and I am not sure how to fix this. The problem is my SQL query does not get the input from javaFX textfield and passwordfield(I am building a login window).
If I enter the values manually rather than getting them from a textfield the program work fine, otherwise nothing happens when you press login button. The problem occurs at the following lines, of course with no error messages:
preparedStatement.setString(1,txtUserName.getText());
preparedStatement.setString(2,txtPassword.getText());
Here is the full code:
public class LoginWindow implements Initializable{
#FXML
private TextField txtUserName;
#FXML
private PasswordField txtPassword;
#FXML
private Button btnLogin;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
// Setting the login button.
#FXML
private void setBtnLogin(ActionEvent event) {
try {
connection = DBUtilities.getConnection();
String sqlQuery = "SELECT * FROM user_login_details WHERE User_Name = ? AND User_Password = ?";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1,txtUserName.getText());
preparedStatement.setString(2,txtPassword.getText());
resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
DBUtilities.showInforMsg("Logged in:", "You have logged in!");
} else {
DBUtilities.showErrorMsg("Error:", "Invalid username or password");
}
}catch (Exception exception) {
exception.printStackTrace();
}finally {
DBUtilities.closePreparedStatement(preparedStatement);
DBUtilities.closeResultSet(resultSet);
DBUtilities.closeConnection(connection);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
btnLogin.setOnAction(this::setBtnLogin);
}
}
Thank you very much. I simply did not gave any ID to the passwordfield.
You can debug by first trying to print the string from your input fields:
String username = txtUserName.getText();
String password = txtPassword.getText();
System.out.println("User name = " + username);
System.out.println("Password = " + password);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
If the username and password are null then make sure, those fields controller are well bound to the FXML document.
I have two syntax error in my login form panel code and here is it :
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
boolean result =false;
try{ Koneksi objKoneksi = new Koneksi();
Connection kon = objKoneksi.bukaKoneksi();
Statement stat = kon.createStatement();
String username = id.getText();
String password = pass.getText();
String query = "select * from userid where id='" +id+ "'and pass='"+pass+"'";
result=stat.executeQuery(query).next();
} catch (SQLException e)
{
System.out.println(e.toString());}
if(result){
JOptionPane.showMessageDialog(null,"LOGIN SUCCESS");
this.setVisible(false);
new Aplikasi().show();
this.parent.setVisible(true);
this.dispose();}
else {
error.setText("ERROR LOGIN");}
}
There is a Strikethrough on Show() method and a red balloon in the line this.parent.setVisible(true) said Parent is not public in Component; cannot be accessed from outside packages.
What could go wrong here?
thanks before
PS: I'm newbie and English is not my Native Language
A strike through most likely means that the method you are calling is deprecated.
The error saying parent is not public means that the field parent in this object cannot be accessed directly. If I'm not wrong you can call getParent() to get access to it.