Nearby lessons

18 of 34

Servlet - Session Management (Cookies)

📌 What You Will Learn
  • Understand Session Management by using Cookies
  • Understand Demo Program for session Management by using Cookies
  • Understand Demo Program how cookies are exchanging b/w client and server
  • See complete working code examples

Session Management (Cookies) is an essential part of the Java Servlet technology. This lesson explains Session Management by using Cookies, Demo Program for session Management by using Cookies and CookieDemoServlet1.java with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.

Session Management by using Cookies

Cookie is a small amount of information(key-value pair),which is created by server and maintained

by client.

Whenever browser sends first request,if server wants to remember client information for the

future purpose, then server will creates Cookie object with the required information and sends to

the browser as the part of response.

Browser stores that cookie in the local file system and sends to the server with every consecutive

request.By accessing that cookie server can able to remember client information.

Server will use setCookie response header to send cookies to the client. Browser will use cookie

request header to send cookies to the server.

Hence by using setCookie response header and cookie request header cookies are exchanging b/w

client and server. It is exactly same as exchanging sessionid b/w client and server.

req 1

resp 1 + setCookie=C1

req 2 + Cookie=C1

resp 2 + setCookie=C2

req 2 + Cookie=C1 + C2

ClientServer

We can create a Cookie object by using Cookie class Constructor.

Cookie c = new Cookie(String name,String value);

Eg:

Cookie c = new Cookie("durga","10");

After creating Cookie object,we have to add that object to the response by using addCookie()

method.

resp.addCookie(c);

At server side we can retrieve cookies send by the client from request object by using getCookies()

method.

Cookie[] c = req.getCookies();

If the request does not associated with any cookies then this method returns null.

Important methods of Cookie class:

Session Management by using Cookies

returns the name of the Cookie

Example02
JCode Cell
1 
2public String getName()
3

Session Management by using Cookies

returns the value of the Cookie

Example03
JCode Cell
1 
2public String getValue()
3

Session Management by using Cookies

Returns the max age of the Cookie in seconds.

Example04
JCode Cell
1 
2public int getMaxAge()
3

Session Management by using Cookies

To set max age of the cookie.

setting max age as -1,then cookies will be expired automatically whenever browser window

closed.

-1 is the default value.

Example05
JCode Cell
1 
2public void setMaxAge(int seconds)
3

Demo Program for session Management by using Cookies

cookie.html:

Demo Program for session Management by using Cookies

Example07
JCode Cell
1 
2<html>
3<body>
4<form action="/session3/test1">
5<h1>Enter cookie information</h1>
6<pre>
7Name:<input type="text" name="uname">
8Value:<input type="text" name="uvalue">
9</pre>
10<input type="submit"/>
11</form>
12<a href="/session3/test2">View Cookies</a>
13</body>
14</html>
15

CookieDemoServlet1.java

Example08
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class CookieDemoServlet1 extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10{
11PrintWriter out=res.getWriter();
12String name=req.getParameter("uname");
13String value=req.getParameter("uvalue");
14Cookie c = new Cookie(name,value);
15c.setMaxAge(180);
16res.addCookie(c);
17out.println("<h2>Cookie added successfully</h2>");
18RequestDispatcher rd = req.getRequestDispatcher("cookie.html");
19rd.include(req,res);
20}
21}
22
Output

<h2>Cookie added successfully</h2>
      

CookieDemoServlet2.java

session3

|-cookie.html

|-WEB-INF

|-classes

|-CookieDemoServlet1.class

|-CookieDemoServlet2.class

Example09
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import java.util.*;
6import javax.servlet.annotation.*;
7@WebServlet("/test2")
8public class CookieDemoServlet2 extends HttpServlet
9{
10public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
11{
12PrintWriter out=res.getWriter();
13Cookie[] c = req.getCookies();
14if(c == null)
15{
16out.println("<h2> No cookies are assiciated with the request</h2>");
17}
18else
19{
20out.println("<table border=2><tr><th>Cookie Name</th><th>Cookie Value</th></tr>");
21for(Cookie c1: c)
22{
23String name = c1.getName();
24String value = c1.getValue();
25out.println("<tr><td>"+name+"</td><td>"+value+"</td></tr>");
26}
27out.println("</table>");
28}
29}
30}
31
Output

</table>
      

Demo Program how cookies are exchanging b/w client and server

cookie.html:

Demo Program how cookies are exchanging b/w client and server

CookieDemoServlet1.java

Example11
JCode Cell
1 
2<html>
3<body>
4<form action="/session4/test1">
5<h1>Enter cookie information</h1>
6<pre>
7Name:<input type="text" name="uname">
8Value:<input type="text" name="uvalue">
9</pre>
10<input type="submit"/>
11</form>
12<a href="/session4/test2">View Request Headers</a>
13</body>
14</html>
15

Demo Program how cookies are exchanging b/w client and server

Example12
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class CookieDemoServlet1 extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10{
11PrintWriter out=res.getWriter();
12String name=req.getParameter("uname");
13String value=req.getParameter("uvalue");
14Cookie c = new Cookie(name,value);
15//c.setMaxAge(120);
16res.addCookie(c);
17out.println("<h2>Cookie added successfully</h2>");
18RequestDispatcher rd = req.getRequestDispatcher("cookie.html");
19rd.include(req,res);
20}
21}
22
Output

<h2>Cookie added successfully</h2>
      

RequestHeaderDemoServlet.java

session4

|-cookie.html

|-WEB-INF

|-classes

|-CookieDemoServlet1.class

|-RequestHeaderDemoServlet.class

Persistant cookies vs non-persistant cookies:

If we are setting max age to the cookie,then such type of cookies are called persistant cookies or

permanent cookies. These will be stored in the local file system of the client.

If we are not setting max age ,then such type of cookies are called temporary cookies or non-

persistant cookies.These cookies will be stored in the browser's cache and not visible in the local

file system. Once we close the browser, automatically these cookies will be expired.

Advantages of Cookies:

  • Very easy to implement
  • Persist across server restarts also
  • All browsers and servers provide automatic support for cookies.

Disadvantages of Cookies:

  • Cookies can be enabled or disabled at client side to meet security constraints.

If the cookies are disabled then session management by using cookies is not possible.

2.The number of cookies supported by any browser is always fixed.

  • The max size of the cookie is also fixed. Hence we can not store huge amount of information by

using Cookies.

  • Cookie data is always String type.

Differences b/w Session API and Cookies:

Session APICookies
1) Session Information will be maintained at1) Session Information will be maintained at
Server side.Client side.
2) Best suitable if we want to store huge2) Best suitable if we want to store less amount
amount of Information.of Information.
Example13
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import java.util.*;
6import javax.servlet.annotation.*;
7@WebServlet("/test2")
8public class RequestHeaderDemoServlet extends HttpServlet
9{
10public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11{
12PrintWriter out = resp.getWriter();
13out.println("<h1>Request Headers Information</h1></hr>");
14out.println("<table border=2><tr><th>HeaderName</th><th>Header values</th></tr>");
15Enumeration e = req.getHeaderNames();
16while(e.hasMoreElements())
17{
18String hname = (String)e.nextElement();
19out.println("<tr><td>"+hname+"</td><td>"+ req.getHeader(hname)+"</td></tr>");
20}
21out.println("</table></body></html>");
22}
23}
24

RequestHeaderDemoServlet.java

If Cookies are disabled at Client Side then what will happend?

If the cookies are disabled at client side then browser is unable to see Set-Cookie response header.

Hence browser wont get any cookies or session id send by server.

If the cookies are disabled at client side then browser unable to send Cookie request header.Hence

server wont get any cookies or session id from the request and every request is treated as new

request. Due to this total session management fails.

To overcome this problem,we should go for the most powerful and painful technique: URL

REWRITING.

Session Management by URL REWRITING

URLs can be re written or encoded to include session information.This technique is called url

rewriting.

URL Rewriting=URL+Session Info

Eg: url;JSESSIONID=1234

HttpServletResponse defines the following methods to append session id to the url.

Example14
JCode Cell
1 
2Session Information need not be String Type. 3) Session Information should be String Type.
3Network Problems won't be raised. 4) There may be a chance of Network Problems.
4Security is more. 5) Security is less.
5

RequestHeaderDemoServlet.java

Returns url by appending JSESSIONID.

Example15
JCode Cell
1 
2public String encodeURL(String url)
3

RequestHeaderDemoServlet.java

Returns url by appending session id.

This can be used as argument to sendRedirect() method.

The above 2 methods will append JSESSIONID to the url iff cookies are disabled at client side.

If the cookies are enabled,these methods return the same url without appending JSESSIONID.

At server side we can identify whether sessionid is coming as the part of url or from the Cookie

request header by using the following methods of HttpServletRequest.

Example16
JCode Cell
1 
2public String encodeRedirectURL(String url)
3

RequestHeaderDemoServlet.java

By using these methods we can identify underlying session management technique.

Example17
JCode Cell
1 
2public boolean isRequestedSessionIdfromURL()
3public boolean isRequestedSessionIdfromCookie()
4
📝 Key Takeaways
  • Key ideas of Servlet - Session Management (Cookies) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3