ValidateLogin.java
public boolean testLogin(LoginHandler user)
{
String query = null;
try
{
stmt = connect.createStatement();
query = "SELECT * FROM users WHERE UserName = '"+user.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
if(rs.getString(2).equals(user.getUsername()) && rs.getString(3).equals(user.getPassword()))
{
this.closeDB();
return true;
}
else
{
JOptionPane.showMessageDialog(null,"Login Failed: Invalid Password");
}
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Login Failed: Invalid Username");
}
this.closeDB();
return false;
}
LoginHandler.java
public boolean verifyUser()
{
if(super.testLogin(this))
{
mainWindow mainwindow = new mainWindow();
mainwindow.setVisible(true);
return true;
}
return false;
}
i already saved username and password fields in my database..
how can i retrieve them in my loginWindow???
everytime i enter the username and password.. the message it displays is : "Login Failed: Invalid Password"
anyone help please??
try this
PreparedStatement ps = connect.prepareStatement("SELECT * FROM users WHERE UserName =?");
ps.setString(1,user.getUsername());
rs = ps.executeQuery();
use column name instead of index value
uname & pass are variable
while (rs.next()) {
uname=rs.getString("UserName");
pass=rs.getString("Password");
}
if(uname.equals(user.getUsername()) && pass.equals(user.getPassword()))
{
this.closeDB();
return true;
}
Related
private boolean checkingDataBase(String email) {
String query = String.format("SELECT email FROM users where email = '%s'", email);
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
String s = "";
if (rs.getString("email").isEmpty()){
System.out.println("true");
return true;
}
else {
System.out.println("faaalse");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} return false;
}
I think, I'm doing everything wrong. Can anyone show a way how to make it right
I have to do a Login form with Java, using three layer architecture and a database, I'm using SQL Server.
In my DA class I have this code: Basically what I'm trying to do is to send the jText user and jText password to the setPassword and setUser from the BL class.
u.setLogin(jtxtUsuario.getText());
u.setContrasenia(jtxtPassword.getText());
DA.DB.getConexion();
if (DA.DB.getStatus()) {
new jfrmInterno().setVisible(true);
}else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
In my BL class I have this code: In the method "validarUsuario" im sending the user and pass to the "setUsuario" method in the DA class.
public void setLogin(String login) {
if(login != null && login.length() > 3) {
_login = login;
}else {
_login = "Usuario Incorrecto";
}
}
public String getLogin() {
return _login;
}
public void setContrasenia(String contrasenia) {
if(contrasenia != null && contrasenia.length() > 6) {
_contrasenia = contrasenia;
}else {
_contrasenia = "Contraseña Incorrecta";
}
}
public String getContrasenia() {
return _contrasenia;
}
public void validarUsuario() {
admin.setUsuario(getLogin(), getContrasenia());
}
public Colegio() {
this("","");
}
public Colegio(String login, String contrasenia) {
setLogin(login);
setContrasenia(contrasenia);
}
}
The problem I have is in the DA class, I dont know how I can use the jText user and password and validate it against the user and password I have in the DB from the DA class. I create a method in the DA class called "setUsuario" which receives the user and password from the jText, but after that I dont know what else I can do, the idea is if the user and password are correct it should open a new Jframe.
public static Connection getConexion() {
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
status = true;
}catch (SQLException e) {
}
return cn;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
In your DA class, you have to check if there is a record exists or not in the database like this,
public static boolean getConexion() { // change it to boolean because it returns boolean value
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (rs.next) {
status = true;
}
} catch (SQLException e) {
}
return status;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
And in your view, you can pass the values to setUsuario() method and then call the getConexion() method which returns true if the user exists as shown below,
DA.DB.setUsuario(jtxtUsuario.getText(), jtxtPassword.getText());
if (DA.DB.getConexion()) {
new jfrmInterno().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
And I can't see the DA.DB.getStatus() method, so I have coded inside the getConexion() method to show what you are missing and this is not a GOOD PRACTICE to code inside the Database Connection and it should be in a separate class.
I have been working with a java database for this class I'm just trying to search and see if the entry with the same name the user inputs exists. It used to work but for some, it keeps saying it doesn't exist in the database even if it does. If someone could give me a solution it would be greatly appreciated.
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
name = txtSearch.getText();
sr.setSearch(name);
try {
String url = "jdbc:derby://localhost:1527/Cookbook";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT * from RECIPES where NAME = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
boolean found = false;
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase(name)) {
JOptionPane.showMessageDialog(null, "Found " + name);
found = true;
break;
}
}
if (found) {
this.dispose();
modifyingRecipe m = new modifyingRecipe();
m.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Item Not Found!");
}
} catch (SQLException ex) {
Logger.getLogger(CookbookApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
Greeting to everyone.
I'm currently making Java restaurant project using MVC for portfolio. Right now, I'm stuck at login form. My problem is I forget how to logging in as a user (Admin or Customer) in MySQL.
In my login form, there are username textfield, password field, login and exit button.
There's no user type because there's only one admin. I don't want to deal with multiple admin.
The name of database is restaurant. Right now, there's only one table: user. There are some data I manually inserted.
After login successful, view will change to Admin or User depending on user type.
These are ControllerLogin and Database. The database I copy paste from another project from my classmate.
public class ControllerLogin extends MouseAdapter implements ActionListener {
private ViewLogin view;
private Database db;
public ControllerLogin() {
view = new ViewLogin();
db = new Database();
view.addActionListener(this);
view.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source.equals(view.getBtnLogin())) {
btnLoginActionPerformed();
}
if (source.equals(view.getBtnExit())) {
btnExitActionPerformed();
}
}
public void btnLoginActionPerformed() {
}
public void btnExitActionPerformed() {
System.exit(0);
}
}
public class Database {
private Connection conn;
private Statement stmt;
private ResultSet rs;
public void connect() {
String url = "jdbc:mysql://localhost/restaurant";
String user = "root";
String pass = "";
try {
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
}
Edit 1:
I searched video how to make login form and found one. I tried to code it on my program, but it's still wrong said that "java.lang.NullPointerException."
public void btnLoginActionPerformed() {
db.connect();
String sql = "Select * from user where username=? and password=?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, view.getUsername());
pst.setString(2, view.getPassword());
rs = pst.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome");
} else {
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Access Denied", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You can achieve that by using below code
public void btnLoginActionPerformed() {
db.connect();
String sql = "Select * from user where username=? and password=?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, view.getUsername());
pst.setString(2, view.getPassword());
rs = pst.executeQuery();
if (rs.next()) {
if(view.getUsername.equals("Admin"))
{
JOptionPane.showMessageDialog(null, "Welcome admin");
}else
{
JOptionPane.showMessageDialog(null, "Welcome user");
}
} else {
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Access Denied", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This question already has answers here:
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 5 years ago.
I have a database and it has a table user which consists of many attributes like name ,email,etc. Also it has username and password in VARCHAR datatype. I wrote two classes LoginModel and Controller. controller has method loginit through which it checks if login method from LoginModel returns true or not. I am not able to find out why LoginModel always returns false. Please help.
Here are my methods :
from class LoginModel
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
return false;
}
}
from class Controller
public void loginit() throws SQLException {
String userid = uid.getText();
String userpass = upass.getText();
try {
if (loginmodel.login(userid, userpass)) {
lblstatus.setText("YES");
}
else
lblstatus.setText("Invalid");
} catch (SQLException e) {
lblstatus.setText("No");
e.printStackTrace();
}
}
It is a JavaFX application. userid and userpass are ids of text-field and password-field respectively. lblstatus is label which always shows Invalid, can't figure out why!
Here is snapshot of my database
remove return false from the finally block. It will executed in case of execption and in case you get no exception.
finally {
preparedStatement.close();
resultSet.close();
return false;
}
Change your code to:
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
}
return false;
}