Open In App

Servlet – Login and Logout Example using Cookies

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?

Working of a Cookie

How to use cookies in java?

How to attach a cookie to a response?  

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

How to delete a cookie?

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 



Example:




<!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:

 




<!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 

 




<!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 

 




// 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

 




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

 

Example

 




// 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.

 


Article Tags :