In this example, we use the Scanner class to read login details from the console and validate it with hardcoded data. You can also use the database to validate a userName and password.
Java Scanner - Login Example
In the below example
- we read userName and password input from the console
- valid with hardcoded username and password
- we display a login success message if a username and password matches otherwise we display an error message.
package com.java.tutorials.projects.login;
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print(" Enter user name => ");
String userName = scanner.nextLine();
System.out.print(" Enter password => ");
String password = scanner.nextLine();
if ("ramesh".equals(userName) && "password".equals(password)) {
System.out.println(" User successfully logged-in.. ");
} else {
System.out.println(" In valid userName of password ");
}
}
}
}
Output:
Enter user name => ramesh
Enter password => password
User successfully logged-in..
Reference
https://www.javaguides.net/2020/03/java-scanner-tutorial-reading-login-and-registration-user-input.htmlFree Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course