I'm practicing a simple Java GUI by making a login system without a database, but my if statement using .equals doesn't work because it always says incorrect password.
contains() work but I think it's not that secure
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if(user.equals("username") && pass.equals("password") ){
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}
As #MadProgrammer pointed out that equals() is a case sensitive method.
"password1" is NOT EQUAL to "PASSWORD1" //The strings should match with case.
Also to avoid NullPointerException a better way is
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if ("username".equals(user) && "password".equals(pass)) {
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}
Related
This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 6 years ago.
I have the following method in a test environment, I'm trying to attach the variable count "loginAttempts"
to the JOptionPane window so the user would know how many failed login attempts they've had so far.
Essentially, I want to concatenate another string and a variable to this line if possible .
JOptionPane.showMessageDialog(null, "Enter a valid username and a password. You've had ||loginAttempts|| "failed login attempts", "Error", JOptionPane.ERROR_MESSAGE);
Here's the method out of the application"
private void loginButton(java.awt.event.ActionEvent evt) {
username = userName.getText();
password = userPassword.getText();
if (username.equals(finalusername) && password.equals(finalpassword) && loginAttempts <= 3) {
loginSuccess = true;
} else {
loginSuccess = false;
loginAttempts = loginAttempts + 1;
}
if (loginSuccess) {
JOptionPane.showMessageDialog(null, "You have successfully logged in", "Success", JOptionPane.DEFAULT_OPTION);
} else if (loginAttempts > 3) {
JOptionPane.showMessageDialog(null, "You have had 3 failed login attempt, your account has been locked","Locked", JOptionPane.ERROR_MESSAGE);
} else if (!loginSuccess) {
JOptionPane.showMessageDialog(null, "Enter a valid username and a password", "Error", JOptionPane.ERROR_MESSAGE);
}
}
You can concatenate this way (replace the last else with that ) :
} else if (!loginSuccess) {
JOptionPane.showMessageDialog(null, "Enter a valid username and a password, Number of attempts : "+loginAttempts , "Error", JOptionPane.ERROR_MESSAGE);
}
I am trying to make it so that if the username and / or password aren't correct, the program will run it over again, instead of just doing the print command in the else statement. I tried putting another while loop in the else statement and nesting the if statement inside that checks the username and password inside of it, but then I realized I would have to copy all the code from the if statement into the else statement, which obviously seems like it is not the correct solution and is probably very clunky. What is the right way to refer the program back to run from the start or something?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
Think about the below logic
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
If command equals calculator then how can it equal renameUser
You should have it
if (....) {
}
else if (...) {
}
statement or as a switch statement
This snippet here is increasing the cyclomatic complexity of your software making it hard to make a decision, if you want to change that later, you have more chances to break the code than success
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
try to design something more like a witch case logic
Example:
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}
i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.
So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}
Trying to write some code which checks if something has been entered in a form in the JSP, and if it hasn't, assigns it the value from the session.
Once this has been done an object is made from all of the parameters.
Written all the code but the
User user = new User(username, firstname, surname, password); comes up with a cannot **find symbol error**
I realise that this is because it isn't in any of the ifs. Will anyone show me how I can change the code so that it can use these values?
The code:
try {
User sessionuser =(User)session.getAttribute("User");
String username = sessionuser.getUsername();
if (request.getParameter("firstname").equals (null)){
String firstname = sessionuser.getFirstname();
}
else{String firstname = request.getParameter("firstname");
}
if (request.getParameter("surname").equals (null)){
String surname = sessionuser.getSurname();
}
else{String surname = request.getParameter("surname");
}
String password = request.getParameter("password");
User user = new User(username, firstname, surname, password);
//this.updateUser(user);
this.updateUser(username, firstname, surname, password);
//user.updateUser();
session.setAttribute("User", user);
request.setAttribute("u", user);
request.getRequestDispatcher("UpdateUser.jsp").forward(request, response);
A quick hint
if (request.getParameter("firstname").equals (null)){
...
if (request.getParameter("surname").equals (null)){
...
This can never be true, it can be false or throw NullPointerException. Use == instead of equals()
Lets take a snippet of your code and tell you why you are getting the error
if (request.getParameter("firstname").equals (null)){
String firstname = sessionuser.getFirstname();
}
In here, you are instantiating the string firstname in the if statement, when the condition is true, the string is created but is only accessible inside the if statement.
What you should do is
String firstname = sessionuser.getFirstname();
if (request.getParameter("firstname") != null){
firstname = request.getParameter("firstname");
}
You are defining the variables firstname and surname in the if/else construct, which is prevented by the compiler. In this case, yes, it will be defined, but in other cases it might not, and the compiler doesn't spend too much time on static code analysis, it will prevent such behaviour without further investigating.
Instead of defining the variable in if/else, use a default, in this case you can use:
String surname = sessionuser.getSurname();
if (request.getParameter("surname") != null){
surname = request.getParameter("surname");
}
Note that I switched the conditions a bit.
Also, your if will never be true, it will either be false or throw NullPointerException. Use request.getParameter("surname") == null instead.
You need to declare your variables outside the blocks in the if/else chains.
Use something like:
String surname = request.getParameter("surname");
if (surname == null) {
surname = sessionuser.getSurname();
}
Repeat for the other items.
Local variables are only available in the block in which you define them (and its sub-blocks). The way you're doing it, your creating variables inside the if and else blocks that are discarded (cannot be referred to) at all outside those blocks.
If you need to test if these parameters are either null or empty strings, do the if checks like this:
if ((surname == null) || ("".equals(surname))) { ... }
Don't use == to compare strings, that's not reliable - it compares references, not the string contents.
Alternatively, you can save yourself bit of typing and get rid of IF-ELSE blocks. You can use method like StringUtils.defaultString.
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#defaultString(java.lang.String,%20java.lang.String)
One line for one field will do:
String firstName = StringUtils.defaultString(request.getParameter("firstname"), sessionuser.getFirstname())
Do the same for other fields.
This function basically replaces your IF-ELSE block. As a bonus, you won't make a mistake declaring variable inside IF-ELSE block :)
You could use string variables and then check to see if it is NULL or not.
String test = request.getParameter("test");
if (username.equals(""))
{
//todo
}
Should be like this I think
try {
User sessionuser =(User)session.getAttribute("User");
String username = sessionuser.getUsername(),firstname="",surname="",password="";
if (request.getParameter("firstname") == ""){
firstname = sessionuser.getFirstname();
}
else{firstname = request.getParameter("firstname");
}
if (request.getParameter("surname") == ""){
surname = sessionuser.getSurname();
}
else{surname = request.getParameter("surname");
}
password = request.getParameter("password");
User user = new User(username, firstname, surname, password);
//this.updateUser(user);
this.updateUser(username, firstname, surname, password);
//user.updateUser();
session.setAttribute("User", user);
request.setAttribute("u", user);
request.getRequestDispatcher("UpdateUser.jsp").forward(request, response);
You can also use null instead of ""