Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Cookie Tutorial in Java Web Application, Cookies Tutorial in JSP and Servlet:-


A cookie in Java Web Application:- 

 It is used to store application data under the browser cookies folder which can be used to store application information in the 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 a cookie because when we click on the remember me option under application then userid and password will be stored into the cookie folder of a particular web browser means chrome and firefox cookie folder will be different.

Java provides a cookie class to store information under the cookie. cookie syntax is common for JSP and Servlet.

Set data on Cookie Folder:-

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

Get data from the cookie folder

Cookie arrayname[] = request.getCookies();


Example of Cookie to set and Get data:-

1)  Create a JSP Web page:-

<%@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

POST Answer of Questions and ASK to Doubt

Previous Post Next Post