Simple Login Application using Servlet
This example will show step by step procedure to develop Simple Login Application using Servlet technology.
In this tutorial, We will show you how to develop simple login application using Servlet, JSP, and JDBC. The example has been tested with MySQL and Apache Tomcat Server environment and output has been shared in the same post.
1. Project Structure
2. Table Query
Before going to develop simple login application using servlet, make sure that user data are available in the database you can apply the following SQL query to database or else you can develop simple registration application using servlet to insert the user data to database. In this example we are using MySQL database server.
Step 1 : Create the Database
CREATE DATABASE dineshkrish;
Step 2 : Create the Table
CREATE TABLE user_details (userId INT NOT NULL, userName VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255), name VARCHAR(255), emailId VARCHAR(255), phone VARCHAR(30), PRIMARY KEY(userId));
Step 3 : Insert the User Records
- INSERT INTO user_details (userId, userName, password, name, emailId, phone) VALUES (1, ‘dineshkrish’, ‘mypassword’, ‘Dinesh Krishnan’, ‘dinesh@example.com’, ‘+91 9941937705’);
- INSERT INTO user_details (userId, userName, password, name, emailId, phone) VALUES (2, ‘jonnypeter’, ‘mypassword’, ‘Johnathan James’, ‘john@example.com’, ‘+91 8989898989’);
- INSERT INTO user_details (userId, userName, password, name, emailId, phone) VALUES (3, ‘willsmith’, ‘mypassword’, ‘Will Smith’, ‘smith@example.com’, ‘+91 7979797979’);
Servlet Class (LoginServlet.java)
package com.dineshkrish.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dineshkrish.dto.UserDetails; import com.dineshkrish.service.AuthenticationService; /** * * @author Dinesh Krishnan * */ public class LoginServlet extends HttpServlet { private String userName = null; private String password = null; @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // getting the input from user userName = request.getParameter("userName"); password = request.getParameter("password"); // simple validation if((userName != null && !userName.isEmpty()) && (password != null && !password.isEmpty())) { // defining the object for AuthenticationService AuthenticationService service = new AuthenticationService(); // validating the user input UserDetails userDetails = service.validateUser(userName, password); // dispatching the result based on the outcome if(userDetails != null && userDetails.isValidUser()) { HttpSession session = request.getSession(); RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp"); // setting user details object in session based on the valid outcome session.setAttribute("userDetails", userDetails); dispatcher.forward(request, response); } else { RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); // setting error message request.setAttribute("errorMessage", "you have given invalid username or password :( "); dispatcher.forward(request, response); } } else { RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); // setting error message request.setAttribute("errorMessage", "please make sure username or password is not empty :( "); dispatcher.forward(request, response); } } }
Data Transfer Object (UserDetails.java)
package com.dineshkrish.dto; /** * * @author Dinesh Krishnan * */ public class UserDetails { private int userId; private String userName; private String password; private String name; private String emailId; private String phone; private boolean validUser; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public boolean isValidUser() { return validUser; } public void setValidUser(boolean validUser) { this.validUser = validUser; } }
Business Service Object (AuthenticationService.java)
package com.dineshkrish.service; import com.dineshkrish.dao.UserDetailsDAO; import com.dineshkrish.dto.UserDetails; /** * * @author Dinesh Krishnan * */ public class AuthenticationService { public UserDetails validateUser(String userName, String password) { // defining the dao object UserDetailsDAO dao = new UserDetailsDAO(); // calling the validate user method return dao.validateUser(userName, password); } }
Database Utility Class (DBUtils.java)
package com.dineshkrish.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author Dinesh Krishnan * */ public class DBUtils { private static final String DRIVERNAME = "com.mysql.jdbc.Driver"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; private static final String CONNECTION_URL = "jdbc:mysql://localhost:3306/dineshkrish"; private static Connection connection; public static Connection getConnection() { try { // loading the driver Class.forName(DRIVERNAME); // getting the connection connection = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (SQLException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return connection; } }
Data Access Object (UserDetailsDAO.java)
package com.dineshkrish.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.dineshkrish.dto.UserDetails; import com.dineshkrish.util.DBUtils; /** * * @author Dinesh Krishnan * */ public class UserDetailsDAO { public UserDetails validateUser(String userName, String password) { // getting the connection from DBUtils final Connection connection = DBUtils.getConnection(); String sql_query = "SELECT USERID, NAME, EMAILID, PHONE FROM USER_DETAILS WHERE USERNAME = ? AND PASSWORD = ?"; UserDetails userDetails = null; try { PreparedStatement stmt = connection.prepareStatement(sql_query); stmt.setString(1, userName); stmt.setString(2, password); // executing the query ResultSet rs = stmt.executeQuery(); while(rs.next()) { // defining the UserDetails object userDetails = new UserDetails(); // setting the all attributes to object from database userDetails.setUserId(rs.getInt("userId")); userDetails.setUserName(userName); userDetails.setName(rs.getString("name")); userDetails.setEmailId(rs.getString("emailId")); userDetails.setPhone(rs.getString("phone")); userDetails.setValidUser(true); } } catch(Exception ex) { System.out.println(ex.getMessage()); } return userDetails; } }
Login Page (index.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login | My Application</title> <link rel="stylesheet" href="css/style.css" /> </head> <body> <%! String errorMessage = null; %> <% if(request.getAttribute("errorMessage") != null) { errorMessage = (String)request.getAttribute("errorMessage"); if(!errorMessage.isEmpty()) { %> <div class="alert"> <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span> <% out.println(errorMessage); %> </div> <% } } %> <form action="authenticate" method="post"> <div class="loginBox"> <h1>Login</h1> <p> Please enter Username and Password :) </p> <input class="field" type="text" placeholder="Your Username" name="userName" /> <input class="field" type="password" placeholder="Your Password" name="password" /> <input class="loginBtn" type="submit" value="Login" /> </div> </form> </body> </html>
Success Page success.jsp
<%@page import="com.dineshkrish.dto.UserDetails"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Dash Board | My Application</title> <link rel="stylesheet" href="css/style.css" /> </head> <body> <%! UserDetails userDetails = null; String name = null; %> <% if(session.getAttribute("userDetails") != null) { userDetails = (UserDetails)session.getAttribute("userDetails"); name = userDetails.getName(); } %> <h1>Hello <%=name %>, Welcome to Application</h1> <br/> <!-- Your design should goes here --> <h3>You can design this page better than me... :))</h3> </body> </html>
Style Sheet (style.css)
@CHARSET "ISO-8859-1"; body { background-color: #ffde85; } .loginBox { width:300px; margin:auto; border:1px #CCC solid; padding:0px 30px; background-color: #43928a; color:#FFF; } .field { background: #1b1b1b; border:1px #03306b solid; padding:10px; margin:5px 25px; width:215px; color:#FFF; } .loginBox h1, p, .chbox, .btn { margin-left:25px; color:#fff; } .loginBtn { background-color: #a50601; border:1px #03306b solid; padding:10px 30px; font-weight:bold; margin:25px 25px; color:white; cursor: pointer; } /* The alert message box */ .alert { padding: 20px; background-color: #f44336; /* Red */ color: white; margin-bottom: 15px; } /* The close button */ .closebtn { margin-left: 15px; color: white; font-weight: bold; float: right; font-size: 22px; line-height: 20px; cursor: pointer; transition: 0.3s; } /* When moving the mouse over the close button */ .closebtn:hover { color: black; }
Configuration File (web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LoginApplication</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Authentication</servlet-name> <servlet-class>com.dineshkrish.controller.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Authentication</servlet-name> <url-pattern>/authenticate</url-pattern> </servlet-mapping> </web-app>
Download Source Code
You can download the source code here
Final Output 🙂
The output screen shot describe the simple login application using servlet.
References
1. Java EE HttpServletRequest Interface
2. Java EE HttpServletResponse Interface
3. Java EE ServletException Class
4. Java IOException Class
5. Java Connection Interface
6. Java DriverManager Class
7. Java PreparedStatement Interface
8. Java ResultSet Interface
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet