Skip to content
Related Articles

Related Articles

Servlet – Login and Logout Example using Cookies

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 25 Feb, 2022

Cookies are a piece of textual information that is stored in key-value pair format in the client’s browser during multiple requests.

Why do we use cookies?

  • We use Cookies as one of the techniques of Session Tracking / State Management.
  • Session Tracking is a way to maintain state (data) of a user. It is also known as State Management.
  • We use session tracking because HTTP is a stateless protocol. In stateless, the server treats each request as a new request because it will not remember that the requests are being sent by the same client.
  • Hence, using cookies we can create a login/logout module and the server can store our data.

Working of a Cookie

  • The client sends a request “req1” to the server. After processing the request “req1”, the server sends “response+cookies”.
  • These cookies are saved on the client’s browser.
  • Now, if the client sends another request “req2+cookies” to the server, then first the server will check the cookie and it will know that this is an already logged-in user and will not treat this request “req2+cookies” as a new request. Then further processing will be done by the server.
  • That’s how a state will be established.

How to use cookies in java?

  • To create cookies, use the Cookies class in javax.servlet.http package.
  • To make a cookie, create an object of the cookie class and pass a name-value pair.

How to attach a cookie to a response?  

  • To attach a cookie to a response, use addCookie(cookie) method of response interface.

How to fetch a cookie when a client sends another request (i.e., req2+cookie) ?  

  • Cookie will come through a request so we will take help from the request object.
  • request.getCookies() method will return an array of cookies.
  • getName() and getValue() methods of Cookie class are used to fetch the key and its corresponding value from the array of cookies.
  • If no cookies are found, then it will return null means the client is a new user and the request is also new.

How to delete a cookie?

  • A cookie is deleted to log out the user.
  • In the key-value pair, pass an empty string.
  • Also, use setMaxAge() method of Cookie class to indicate after how long the cookie should expire.

Note: To run the following programs, the author created a Dynamic Web Project in Eclipse IDE and executed it using Apache Tomcat Server v9.0. 

Example: Login and Logout module using Cookies

A. File: index.html 

  • This page includes links to three other pages for navigation – login page, logout servlet and profile servlet.
  • Click on login.html and enter username and password (i.e., gfg). From the login page, you will be redirected to GFGLoginServlet.java

Example:

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GFG</title>
</head>
<body>
 
 
 
<p>
<a href="login.html" style="font-size:25px;">Login |</a>
 
<a href="GFGLogoutServlet" style="font-size:25px;"> Logout |</a>
 
<a href="GFGProfileServlet" style="font-size:25px;"> Profile </a>
</p>
 
 
 
</body>
</html>

 
 

Output: index.html is as follows: 

 

index.html

 

B. File: link.html

 

link.html is the same as index.html because we will include link.html page’s content using RequestDispatcher in GFGLoginServlet.java and GFGLogoutServlet.java

 

Example:

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GFG</title>
</head>
<body>
 
 
 
<p>
<a href="login.html" style="font-size:25px;">Login |</a>
 
<a href="GFGLogoutServlet" style="font-size:25px;"> Logout |</a>
 
<a href="GFGProfileServlet" style="font-size:25px;"> Profile </a>
</p>
 
 
 
</body>
</html>

 
 

C. File: login.html 

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GFG</title>
</head>
<body>
<form action="GFGLoginServlet">
<pre>
User name: <input type="text" name="user_name" placeholder="Enter your name">
 
Password: <input type="password" name="password" placeholder="Enter password">
 
<button type="submit" value="login">Login</button>
</pre>
</form>
</body>
</html>

 
 

Output: login.html is as follows:  

 

login.html

 

Implementation: 

 

Case: GFGLoginServlet.java 

  • Here, the password will be checked.
    • If the password is correct (i.e., gfg), then cookie will be created.
    • Else contents of login.html will be displayed asking the user to login again as the password was incorrect.
  • Content of link.html will be displayed at the top in either case.

 

Java




// Java Program to Illustrate Login in Servlets
 
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
// Annotation
@WebServlet("/GFGLoginServlet")
 
// Class
// Extending HttpServlet class
public class GFGLoginServlet extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
 
        PrintWriter out = response.getWriter();
        request.getRequestDispatcher("link.html")
            .include(request,
                     response); // This statement includes
                                // link.html in this servlet
 
        String name = request.getParameter("user_name");
        String password = request.getParameter("password");
 
        if (password.equals("gfg")) {
            out.println(
                "<h1>Welcome " + name
                + ", you have successfully logged in!</h1>");
            // creating cookie
            Cookie c = new Cookie("username", name);
            // attaching cookie to response object
            response.addCookie(c);
        }
        else {
            out.println(
                "Sorry invalid username or password!");
            request.getRequestDispatcher("login.html")
                .include(request, response);
            // Above statement includes login.html for the
            // user to re-login if username or password is
            // invalid.
        }
    }
 
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

 
 

Output: GFGLoginServlet.java is as follows:

 

GFGLoginServlet.java

GFGProfileServlet.java

  • Here, accessing the profile page means actually sending another request to the user (i.e., req2+cookie).
    • If the cookie does not exist (i.e., null), then contents of login.html will be displayed asking the user to login.
    • Else cookie will be fetched using getName() function and the required cookie name (i.e., username) will be matched. Upon finding the cookie name, cookie value will be fetched using getValue() function.
  • Contents of link.html will not be displayed on this page.

 

Java




import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/GFGProfileServlet")
public class GFGProfileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
 
        PrintWriter out = response.getWriter();
 
        String name = "";
 
        // request object will return an array of cookies
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            out.println(
                "<h1> You are a new user, kindly login. </h1>");
            request.getRequestDispatcher("login.html")
                .include(request, response);
            // Above statement includes login.html for the
            // user to re-login if username or password is
            // invalid.
        }
        else {
            for (Cookie c : cookies) {
                String tempName
                    = c.getName(); // For every cookie, add
                                   // cookie name to the
                                   // tempName.
               
                if (tempName.equals("username"))
                // If tempName and username (that we had set
                // in the cookie c in GFGLoginServlet) are
                // same, then this is an already logged in
                // user and the request is not from a new
                // user. So let the user access profile page.
 
                {
                    name = c.getValue(); // From the (name,
                                         // value) pair of
                                         // cookie, fetch
                                         // value
                    out.println(
                        "<a href='GFGLogoutServlet' style='font-size:25px;'>Logout </a>");
                    out.println(
                        "<h1>Welcome to your profile, "
                        + name);
                }
            }
        }
    }
 
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

 
 

Output: GFGProfileServlet.java is as follows:

 

GFGProfileServlet.java

Case: GFGLogoutServlet.java

  • Here, the cookie will be deleted in order to end the session.
    • Along with cookie name (i.e., username), null value will be passed.
    • Inside setMaxAge() function, we will set the expiration date of the cookie, to specify after how long the cookie will expire.
    • Using response.addCookie() function, we will attach this cookie with the response to send it to the client’s browser.

 

Example

 

Java




// Java Program to Illustrate Logout in Servlets
 
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
// Annotation
@WebServlet("/GFGLogoutServlet")
 
// Class
// Extending HttpServlet class
public class GFGLogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
 
        PrintWriter out = response.getWriter();
        request.getRequestDispatcher("link.html")
            .include(request,
                     response); // This statement includes
                                // link.html in this servlet
 
        // cookie with blank value is used to delete
        // a cookie to sign out the user
        Cookie c = new Cookie("username", "");
       
        // setMaxAge will set the expiration of cookie.
        // This cookie will expire in 0seconds
        c.setMaxAge(0);
       
        // Attach cookie to response
        response.addCookie(c);
 
        out.println("<h1>You have logged out!</h1>");
    }
 
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

 
 

Output: GFGLogoutServlet.java is as follows: 

 

GFGLogoutServlet.java

Note: While running the module, if the user clicks on “Profile” when s/he is not logged in, in that case, user will be redirected to login.html and won’t be allowed to access profile as the session is not created. 

Exceptions

  • <space> is not allowed in cookies.
  • If we try to send “Geeks” as cookie value, it is acceptable.
  • But “Geeks for Geeks” will throw an IllegalArgumentException because <space> is not allowed in cookies.
  • “Geeks_for_Geeks” is allowed.

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!