Open In App

JSP – Login and Logout Form

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The full form of the JSP is Java Server Pages. The JSP is a Server Side Technology in Java, which is used for creating dynamic web pages. One more thing is the JSP consists of both HTML tags and JSP tags. These JSP tags are used to insert Java code into the HTML applications. The JSP is working in different stages. We will discuss those steps for clarity in this article.

First The JSP is converted into a servlet with the help of JSP Container before handling the Client’s requests. The JSP provides different services for us to handle dynamic web applications. Those are JSP Tags, JSP Expressions, JSP Error handling, etc.

In this article, we will learn how to create a login page and as well as logout form by using HTML and JSP tags. For creating this project we need to follow some steps.

Step-by-Step Project Creation:

  • First, open IDE for the project creation. Here, we will be using Eclipse IDE.
  • After this, click on File Open, then select the new option.
  • After this, select Dynamic Web Project. It is a project category.
  • After successfully creating the project, now we observe the folder structure.
  • Now in the Web App folder create Required JSP Files. Here, we have created an index.jsp, login.jsp, dashboard.jsp, logout.jsp.
  • Now, implement the required logic in those files.
  • Finally, run this project as Run on Server.
Project Structure

Java Server Pages Execution:

  • When a Client send a request to the Sever, the Server receives the request.
  • When for the first time a JSP page is requested, the JSP Engine on the server complies the JSP file into Servlet.
  • Here, the Servlet is a Java class that will handle subsequent requests for the same JSP pages.
  • Once, the Servlet is generated, it is executed to generate dynamic content and during this process java code embedded within the JSP is executed.
  • After this, the dynamic content generated by the Servlet is sent back to the Client in the from the of an HTTP response.
  • Next the Client receives, response and render the HTML content received from the Server.
  • Finally displaying the response to the Client.

Index.jsp:

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="ISO-8859-1">
    <title>Login and Logout Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
   
<title>Insert title here</title>

    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 50px;
        }
        .form-login {
            max-width: 330px;
            padding: 15px;
            margin: auto;
        }
        .form-login .form-control {
            position: relative;
            box-sizing: border-box;
            height: auto;
            padding: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <%-- Check if user is logged in --%>
        <%
            String username = (String) session.getAttribute("username");
            if (username == null) {
        %>
        <!-- Login Form -->
        <form class="form-login" method="post" action="login.jsp">
            <h2 class="mb-3">Login</h2>
            <% if (request.getParameter("error") != null) { %>
                <div class="alert alert-danger" role="alert">
                    Invalid username or password!
                </div>
            <% } %>
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" id="username" name="username" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" id="password" name="password" class="form-control" required>
            </div>
            <button class="btn btn-primary" type="submit">Sign in</button>
        </form>
        <% } else { %>
        <!-- Logout Form -->
        <form class="form-login" method="post" action="logout.jsp">
            <h2 class="mb-3">Welcome, <%= username %>!</h2>
            <button class="btn btn-primary" type="submit">Logout</button>
        </form>
        <% } %>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Output:

Below we can see the login page, here after entering correct username and password, we can login to the dashboard.

login page

Error:

If we enter wrong log in credentials, it will throw validation like below.

Invalid login details

login.jsp:

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
//Default username and password
String defaultUsername = "admin";
String defaultPassword = "password";

// Get the entered username and password from the form
String username = request.getParameter("username");
String password = request.getParameter("password");

// Check if entered username and password match the default values
if (username != null && password != null && username.equals(defaultUsername) && password.equals(defaultPassword)) {
    // If authentication succeeds, set the username in session and redirect to dashboard.jsp
    session.setAttribute("username", username);
    response.sendRedirect("dashboard.jsp");
} else {
    // If authentication fails, redirect back to index.jsp with an error parameter
    response.sendRedirect("index.jsp?error=1");
}
%>


dashboard.jsp:

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>dashabord</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
   

<style>
        body {
            background-color: #f8f9fa;
            padding-top: 50px;
        }
        .container {
            max-width: 600px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="mb-3">Dashboard</h2>
        <%-- Check if user is logged in --%>
        <%
            String username = (String) session.getAttribute("username");
            if (username != null) {
        %>
        <p>Welcome, <%= username %>!</p>
        <p><a href="logout.jsp">logout</a></p>
        <% } else { %>
        <p>Please log in to access the dashboard.  <a href="login.jsp">login</a></p>
        <% } %>
        
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Output:

After log in, we will redirect to Dashboard. Refer the below output image for better understanding.

Dashboard


Invalid Access:

If some one try to access the dashboard, they have to log in first using the credentials. Otherwise, they will get invalid access like below.

Invalid Access

logout.jsp:

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
    // Invalidate the session and redirect to index.jsp
    session.invalidate();
    response.sendRedirect("index.jsp");
%>

Output:

After logout, the output will be:

After Logout

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads