Monday, December 30, 2024
Google search engine
HomeLanguagesJavaServlet – Cookies

Servlet – Cookies

Cookies are the textual information that is stored in key-value pair format to the client’s browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used. When the client generates a request, the server gives the response with cookies having an id which are then stored in the client’s browser. Thus if the client generates a second request, a cookie with the matched id is also sent to the server. The server will fetch the cookie id, if found it will treat it as an old request otherwise the request is considered new.

Cookie creation in Client-Server request-response model

Using Cookies in Java

  • In order to use cookies in java, use a Cookie class that is present in javax.servlet.http package.
  • To make a cookie, create an object of Cookie class and pass a name and its value.
  • To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface.
  • To fetch the cookie, getCookies() method of Request Interface is used.

Methods in Cookies

  • clone(): Overrides the standard java.lang.Object.clone method to return a copy of this Cookie.
  • getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
  • getDomain(): Gets the domain name of this Cookie.
  • getMaxAge(): Gets the maximum age in seconds of this Cookie.
  • getName(): Returns the name of the cookie.
  • getPath(): Returns the path on the server to which the browser returns this cookie.
  • getSecure(): Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.
  • getValue(): Gets the current value of this Cookie.
  • getVersion(): Returns the version of the protocol this cookie complies with.
  • setValue(String newValue): Assigns a new value to this Cookie.
  • setVersion(int v): Sets the version of the cookie protocol that this Cookie complies with.

Example

The name of the Institute is passed to Servlet 2 from Servlet 1 using Cookies.

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <!-- css-->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
                                 integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
                               crossorigin="anonymous">
          
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <form action="servlet1" method="POST">
            <div class="container-fluid ">
              
            <div class="jumbotron">
                <div class="container col-sm-4">
            <h2>Enter your institute's name</h2>
            <input type="text" name="name"  style="font-size:30px;">
            <br>
            <br>
            <!-- button to redirect to servlet1 -->
            <button type="submit" style="font-size:20px;" class="center">
                Go !
            </button>
            <br><br>
            </div>
            </div>
            </div>
        </form>
    </body>
</html>


Index.html output

Java




import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
public class Servlet1 extends HttpServlet {
  
    protected void
    processRequest(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Servlet1</title>");
            out.println("</head>");
            out.println("<body>");
  
            // Creating a string to store the name
            String name = request.getParameter("name");
            out.println("<h1> Hello, welcome to " + name
                        + " </h1>");
            out.println(
                "<h1><a href =\"servlet2\">Go to Servlet2</a></h1>");
            // Creating a cookie
            Cookie c = new Cookie("user_name", name);
            response.addCookie(c);
  
            out.println("</body>");
            out.println("</html>");
        }
    }
}


Servlet1.java output

Java




import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
public class Servlet2 extends HttpServlet {
  
    protected void
    processRequest(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Servlet2</title>");
            out.println("</head>");
            out.println("<body>");
  
            // Fetching cookies(if found more than one)
            // Array of Cookies
            Cookie[] cookies = request.getCookies();
            boolean f = false;
            String name = "";
            if (cookies == null) {
                out.println(
                    "<h1>You are new user, go to home page and submit your institute's name");
                return;
            }
            else {
                for (Cookie c : cookies) {
                    String tname = c.getName();
                    if (tname.equals("user_name")) {
                        f = true;
                        name = c.getValue();
                    }
                }
            }
            if (f) {
                out.println("<h1> Hello, welcome back "
                            + name + " </h1>");
                out.println("<h2>Thank you!!</h2>");
            }
            else {
                out.println(
                    "<h1>You are new user, go to home page and submit your institute's name");
            }
  
            out.println("</body>");
            out.println("</html>");
        }
    }
}


Servlet2.java output

If one runs the servlet2 link in incognito mode directly, cookies are not recognized and it is treated as a new user.

Servlet2.java output in incognito mode

Disadvantages of cookies

  • Space character and image are considered invalid.
  • Security is less.
RELATED ARTICLES

Most Popular

Recent Comments