I'm doing a Login form using SQL Server and using three layer architecture, I debugged the project and basically it works like this: I put the user and password in the jframe, the user and pass are sent to the BL method and then to DA, when I put the user and pass correctly the Query is executed and "resultado" value is 1, then it goes back to the GUI but when its validated "getResultado" the value of "resultado" is 0, therefore I can't login.
This is my GUI method:
u.validarLogin(jtxtUsuario.getText(), String.valueOf(jpsfContrasenia.getPassword()));
if (admin.getResultado() == 1) {
new jfrmInterno().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta", "", JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jpsfContrasenia.setText("");
}
}
This is my BL method:
public void validarLogin(String user, String pass) {
if (user != null && pass != null) {
admin.setUsuario(user, pass);
}else {
System.out.println("Incorrecto");
}
}
This is my DA method:
public int setUsuario(String user, String pass) {
this.getConexion();
String usuario = user;
String password = pass;
try {
Statement ejecutor = cn.createStatement();
ResultSet rs = ejecutor.executeQuery("SELECT * FROM [dbo].[Login] where NombreUsuario = '" + usuario + "' AND Contrasenia= '" + password + "'");
if (rs.next()) {
resultado = 1;
} else {
resultado = 0;
}
} catch (Exception e) {
}
return resultado;
}
public int getResultado() {
return resultado;
}
To simplify the code, do this;
1. Add a return type to your BL method
public int validarLogin(String user, String pass) {
int resultado = 0;
if (user != null && pass != null) {
resultado = admin.setUsuario(user, pass);
}else {
System.out.println("Incorrecto");
}
return resultado;
}
Then change your GUI method to this;
int resultado = u.validarLogin(jtxtUsuario.getText(), String.valueOf(jpsfContrasenia.getPassword()));
if (resultado == 1) {
new jfrmInterno().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta", "", JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jpsfContrasenia.setText("");
}
}
This should definitely work as now you are returning the result as a variable every time validation BL method is being called.
Forgive me in case of any typos.
Related
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'm facing the problem about insert user in database. Im using Restful and JDBC to parse data to android, I have two classes to perform insert user following as:
Register.java
#Path("/register")
public class Register {
#GET
#Path("/doregister")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
int retCode = registerUser(name, uname, pwd);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside check registerUser method() ");
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
if(DBConnection.insertUser(name, uname, pwd)){
System.out.println("RegisterUSer if");
result = 0;
}
} catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}
catch (Exception e) {
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
DBConnect.java
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "INSERT into ACCOUNT(name, username, password) values('"+name+ "',"+"'"
+ uname + "','" + pwd + "')";
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
My table ACCOUNT:
When I debugged on Eclipse, I see the result return is fine, but If I use Advanced rest client tool to get data, it happened an exception:
URL Json:
http://localhost:9999/webserver/register/doregister?name=tester&username=tester#gmail.com&password=test12345
status of result response:
{
"tag": "register",
"status": false,
"error_msg": "Error occured"
}
I have found and tried a lot of ways but not found the cause
How to fix the problem and insert user into database? Thank so much !
I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.
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;
}
I'm trying to retrieve the user access privileges associated with a username in a MySQL database. However I'm getting a Null Pointer Exception. Anyone know why? I've attached the parts of the classes associated with the method.
JIOS_Login_Controller.java:
public class JIOS_Login_Controller extends javax.swing.JFrame {
static private JIOSModel model;
private JIOS_Login_Controller home;
static private String username;
static private String password;
static private String a;
public JIOS_Login_Controller() {
initComponents();
username = null;
password = null;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "Select * From user_Tbl";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/abnd251?user=####&password=########");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String user = jTextField1.getText();
String pwd = new String(jPasswordField1.getPassword());
while (rs.next()) {
String uname = rs.getString("Username");
String pword = rs.getString("Password");
if ((user.equals(uname)) && (pwd.equals(pword))) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
setUsername();
String user = new String(getUsername());
ArrayList<UPosition> list = null;
try {
list = model.getPositions(user);
} catch (SQLException ex) {
Logger.getLogger(JIOS_Login_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
for (UPosition p : list) {
a = p.getPosition();
}
new JIOS_Home_Controller().setVisible(true);
dispose();
}
});
} else {
if ((user == null ? (uname) != null : !user.equals(uname)) && (pwd.equals(pword))) {
JOptionPane.showMessageDialog(this, "Incorrect Username");
} else {
if ((user.equals(uname)) && (pwd == null ? (pword) != null : !pwd.equals(pword))) {
JOptionPane.showMessageDialog(this, "Incorrect Password");
} else {
if ((user == null ? (uname) != null : !user.equals(uname)) && (pwd == null ? (pword) != null : !pwd.equals(pword))) {
JOptionPane.showMessageDialog(this, "Incorrect Username and Password");
}
}
}
}
}
} catch (ClassNotFoundException | SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
static public String getPosition(){
return a;
}
JIOS_Home_Controller.java:
public class JIOS_Home_Controller extends javax.swing.JFrame {
private JIOSModel model;
private JIOS_Home_Controller home;
static private String username;
static private String password;
static private String access;
private String position;
public JIOS_Home_Controller() {
initComponents();
user.setText(""+ JIOS_Login_Controller.getUsername() +"");
userPosition.setText(""+ JIOS_Login_Controller.getPosition() +"");
}
JIOSModel.java:
public ArrayList<UPosition> getPositions(String user) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<UPosition> list = new ArrayList<>();
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/abnd251?user=####&password=########");
stmt = con.prepareStatement("SELECT Position FROM user_tbl WHERE Username= '"+ user +"' ");
rs = stmt.executeQuery();
while (rs.next()) {
UPosition p = new UPosition();
p.setPosition(rs.getString("Position"));
list.add(p);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException se) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException se) {
}
}
}
return list;
}
Can anyone help me, I've been stuck on this for days!!
P.S. I know my SQL statements aren't brilliant and are subject to SQL injection attacks (So I've been told) but thats not the issue here!
You need to initialize your
JIOSModel model;
Something like this:
model = new JIOSModel();