Hello friends! Here I will tell how to create a login application in java using a simple Servlet. Generally in a login application we validate a user against the existing user credentials in the database. If the username and password match with any existing records in the database, then user is logged-in the database, else “Username or password mismatch” error is shown to the user.
When we run the “LoginProject” the following things happen.
1)When the application is ran in the browser, WebContainer checks the web deployment descriptor (web.xml) and checks for the tag . Then web container picks the jsp file mentioned in the tag and renders it in the web browser. Here in our application we have given “login.jsp” as welcome file. So, when we run the application “login.jsp” file is rendered first.
2)When user gives details (username and password) and clicks on login button the request goes to the WebContainer with the URL (action attribute mentioned in form tag). Web Container checks “web.xml” file for the matching URL. If found it picks the Servlet class name from tag and calls the doGet()/doPost() method of the Servlet class. Here we are making POST request, hence doPost() method is called.
3)In doPost() method after retrieving the username and password, doLogin() method of LoginService class is called.
4)In doLogin() method we get the database connection(here we are using MYSQL database) and querying the database for any matching record having the username and password entered by the user. If any record exists then we send SUCCESS else FALSE to the LoginServlet class.
5)Based upon the response from doLogin() method we redirect to the respective jsp page, i.e. to success.jsp or failure.jsp.
Create USER table with below sample code and insert one demo record.
CREATE TABLE USER (
id INT NOT NULL AUTO_INCREMENT,
USER_NAME VARCHAR2(40) NOT NULL,
PASSWORD VARCHAR2(40) NOT NULL,
PRIMARY KEY (id)
//Insert Demo data into the User Table
INSERT INTO USER ('id', 'USER_NAME', 'PASSWORD') VALUES (NULL, 'demo', 'demo');
Application Folder Structure
Below i will described step by step working flow of the application.
This is the home page of the application. It contains a