• JSP
  • JavaScript
  • Spring
  • Struts
  • Java IO
  • RubyonRails
  • Servlet
  • jQuery
  • PHP

  • <

    Cookies in JSP

    In jsp Cookies are stored on the client machine by the server. It is mainly used to identify a user or machine by theserver.


    There are two types of Cookies in JSP:

    Persistent cookies: This cookies are permanent.

    Session cookies: This cookies are temporary and ends when browser closed.

    Jsp Cookies Example


    index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Jsp Cookies</title>
    </head>
    <body>
    <form action="cookie.jsp" method="GET">
    Username: <input type="text" name="uname">
    <br />
    Email: <input type="text" name="email" />
    <input type="submit" value="Submit" />
    </form>
    </body>
    </html>
    

    In this file we add cookies using new Cookie function, set cookie expire time and retrive cookies.

    cookie.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%
             
       Cookie uname = new Cookie("uname",
     			  request.getParameter("uname"));
       Cookie email = new Cookie("email",
    			  request.getParameter("email"));
     
       
       uname.setMaxAge(60*60*10); 
       email.setMaxAge(60*60*10); 
     
       // Add both the cookies in the response header.
       response.addCookie( name );
       response.addCookie( email );
    %>
     
     
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Guru Cookie JSP</title>
    </head>
    <body>
     
    <b>Username:</b>
       <%= request.getParameter("uname")%>
    <b>Email:</b>
       <%= request.getParameter("email")%>
     
    </body>
    </html>
    

    OutPut:
    capture

    capture
















    © copyright 2017-2021 Completedone pvt ltd.