Wednesday, March 25, 2020

Servlet Cookies

Servlet Cookies

Servlets Cookie class


The javax.servlet.http.Cookie class provides all the useful methods for handling the cookies with Java Servlets.

Cookies in Servlet

Cookies are one of the techniques to implement session tracking. A cookie is a tiny piece of information that persists between the multiple client requests. We can store the state information to manage a session between the user and the server. Cookies are a set of information residing on your web browser. They stores user information from a website. Cookies are passed from server to client and back again in the HTTP headers of requests and responses.

Cookie parameters


  • The name of the cookie
  • The value of the cookie
  • The expiration date of the cookie
  • The path the cookie is valid for
  • The domain the cookie is valid for
  • The version
  • The comment (purpose/description of the cookie)


How Cookie works



We can add cookies with the response from the servlet. Cookies are stored in the cache of the browser. After that, if the request is sent by the user, the cookie is added with the request by default.


Types of Cookies


There are two types of cookies in servlets.

Non-persistent cookies

The non-persistent cookie is valid for a single session only. These cookies are removed every time when the user closes the browser.

Persistent cookies 

Persistent cookies are valid for multiple sessions. Persistent cookies are retained even when the user closes the browser. These are removed only if user logout or sign-out.

Benefits of Cookies


  • A simple and easy technique of maintaining the state
  • Cookies are maintained on the client-side.

Drawbacks of Cookies


  • If cookies are disabled in the browser, the session will not be maintained.
  • Only textual data can be stored in Cookie object, as key-value pairs.

Creating the cookie object

The constructor of Cookie class can be used to create the cookies,
  • Cookie() creates an empty cookie.
  • Cookie(String name, String value) instantiates a cookie object with a specified name and value.


Cookie Class Methods

There are few important methods defined in Cookie class,


Method Description
public String getName() Returns the name of the cookie. The name of the cookie cannot be changed after creation.
public String getValue() to get the value of a cookie
public void setName(String name) to set the name of the cookie
public void setValue(String value) to set the value of a cookie
public void setDomain(String pattern) to set the domain in which this cookie would be visible.
public void getDomain() to get the domain, where this cookie is visible
public void setComment(String purpose) to describe the purpose of a cookie
public String getComment() to get the purpose of a cookie is a string
public void setMaxAge(long time) time in seconds before this cookie expires
public String getMaxAge() to get the max-age attribute value of a cookie
public void setSecure(boolean secure) A cookie can only be sent over a secure protocol like https if this value is set to be true. Otherwise, it can be transmitted using any protocol.
public boolean getSecure() Returns true setSecure() is set Ture, otherwise returns false.
public void setPath(String path) the path where this cookie is returned
public void getPath() to get the path value of a cookie
public int getVersion() this method returns 0 if the cookie complies with the original Netscape specification, it will return 1 if the cookie complies with RFC 2965/2109
public void setVersion(int version) sets version as 0 for original Netscape specification, sets version as 1 for RFC 2965/2109

Cookies Example


We can create a simple application to demonstrate cookies. This example has 2 HTML, 3 Java Servlets.

  1. index.html
  2. login.html
  3. LoginServlet.java
  4. ProfileServlet.java
  5. LogoutServlet.java


index.html


<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor="yellow">
<h2>
<a href="login.html">login</a>
<a href="http://localhost:8087/TestCookies/LogoutServlet">logout</a>
<a href="http://localhost:8087/TestCookies/ProfileServlet">Profile</a>
</h2>
</body>
</html>


login.html


<html>
<head>
<title>Login</title>
</head>
<body bgcolor="yellow">
<form method="post" action="LoginServlet">
<input type="text" placeholder="Enter Name" name="name"><br>
<input type="password" placeholder="Enter Passwod" name="pass"></br>
<input type="submit" value="login"><br>
</form>
<br>
New User?
<a href="">Sign up</a>
</body>

</html>

LoginServlet.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
  
    }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           String name=request.getParameter("name");
           String pass=request.getParameter("pass");
           if(name.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("123"))
           {
                Cookie cookie=new Cookie("name",name);
                response.addCookie(cookie);
                pout.append("<h3>You are successfully logged in</h3>");
           }else
           {
                pout.append("<h3>Wrong Username or password</h3>");
           }
      pout.append("</body></html>");
    RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}



ProfileServlet.java


import java.io.IOException;
import java.io.PrintWriter; 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProfileServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
      
    public ProfileServlet() {
        super();
    }

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           Cookie[] ck=request.getCookies();
           if(ck!=null)
           {
                String name=ck[0].getValue();
                pout.append("<h3>Welcome "+name+"</h3>"); 
           }else
           {
                pout.append("<h3>You are not logged in.</h3>");
           }
           pout.append("</body></html>");
       RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}



LogoutServlet.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogoutServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
      
    public LogoutServlet() {
        super();
    }
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html");
           PrintWriter pout=response.getWriter();
           pout.append("<html><body>");
           Cookie cookie=new Cookie("name", "");
           cookie.setMaxAge(0);
           response.addCookie(cookie);
           pout.append("<h3>You are logged out successfully</h3>");
           pout.append("</body></html>");
       RequestDispatcher rd=request.getRequestDispatcher("index.html");
           rd.include(request, response);
     }

}




Result: