Cookie in Java Web Application:-  It is used to store application data under browser cookies folder which can be used to store application information in client machine.cookie always will be created into client machine and use system memory but session always will be created by server side and use server memory to contain application but by default session data also managed by cookie.

Remember me option is the best example of cookie because of when we click on remember me option under application then userid and password will be stored into cookie folder of particular web browser means chrome and firefox  cookie folder will be different.

Java provide cookie class to store information under cookie.cookie syntax is common for JSP and Servlet.

Cookie ref = new Cookie("key","value");
response.addCookie(ref);
ref.setMaxAge(time);

Get data from cookie folder

Cookie arrayname[] = request.getCookies();

<%--
    Document   : CookieDemo
    Created on : Dec 11, 2019, 5:01:38 AM
    Author     : Hp
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="t1" />
            <br>
            <input type="submit" name="btnsubmit1" value="Create Cookie" />
            <br>
             <input type="submit" name="btnsubmit2" value="Get Cookie" />
        </form>
        <%
            if(request.getParameter("btnsubmit1")!=null)
            {
                Cookie c = new Cookie("abc",request.getParameter("t1"));
                c.setMaxAge(256000*1000);
                response.addCookie(c);
               
           
            }
            if(request.getParameter("btnsubmit2")!=null)
            {
               Cookie c[] = request.getCookies();
               for(int i=0;i<c.length;i++)
               {
                  if(c[i].getName().equals("abc"))
                  {
                     out.print(c[i].getValue());
                  }
              
               }
               
           
            }
           
            %>
    </body>
</html>







Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post