Nearby lessons

32 of 34

Servlet - Examples: Session Management

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Session management programs using Session API, Cookies, URL Rewriting, and Hidden Form Fields.

Session Management by using Session API

Eg: HttpSession session = req.getSession();

First this method will check is there any session aleady associated with request object or not.

If the request does not associated with any session, then this method creates a new session object

and returns it.

If the request already associated with session object then existing session object will be returned.

There is a guarentee that this method will always return session object.It may be newly created or

already existing one.

Example01
JCode Cell
1 
2 public HttpSession getSession()
3

Session Management by using Session API

If the argument is true then this method simply acts as getSession().

If the argument is false, then this method first checks whether the request associated with any

session or not.If the request already associated with session then this method returns existing

session object.

If the request does not associated with any session then this method returns null without creating

any new session object.

Example02
JCode Cell
1 
2 public HttpSession getSession(boolean b)
3

Case Study

Q. Which of the following are equal?

Example03
JCode Cell
1 
2 HttpSession session =req.getSession(false);
3 if(session==null)
4 {
5 forward request to login page
6 }
7 else
8 {
9 display inbox page
10 }
11

Case Study

Answer: nd 3

Invalidating session object:

We can invalidate a session by using the following 2 ways

Example04
JCode Cell
1 
2 session = req.getSession();
3 session = req.getSession(false);
4 session = req.getSession(true);
5 session = resp.getSession();
6

Case Study

invalidate() method:

HttpSession interface defines invalidate() method to invalidate session explicitly.

public void invalidate()

whenever we are clicking logout button internally this method will be executed.

session.invalidate()

  • Timeout mechanism:

If we are not performing any operation on the session object for a pre defined amount of time

then the session will be expired automatically. This predefined amount of time is called session

timeout.

We can configure session timeout either server level or web application level or a particular

session object level.

  • Session Timeout at Server Level:

Most of the web servers provide default support for session timeout. Mostly it is 30 minutes.

We are allowed to change this server level session timeout based on our requirement.

This session timeout applicable for all sessions created in that server of all web applications.

  • Configuring session timeout at web application level:

If we are not satisfied with server level session timeout then we have to configure at application

level.

We can configure session time out at application level in web.xml as follows...

Example05
JCode Cell
1 
2 By using invalidate() method
3 By Timeout mechanism
4

Case Study

<session-config> is the child tag of <web-app> and hence we can place anywhere within

<web-app>

The unit to the <session-timeout> is minutes

zero or -ve value indicates that session never expires.

This session timeout is applicable for all the session s which are created in that web application.

  • Setting session timeout for a particular session object:

We can set session timeout for a particular session object by using the following method of

HttpSession.

public void setMaxInactiveInterval(int seconds)

The argument is in seconds

-ve value indicates that session never expires

zero value indicates that session will expire immediately.

This session timeout is applicable only for a particular session object on which we call this method.

Comparison between 2 Session Timeout Mechanisms:

Property<session-timeout>setMaxInactiveInterval()
1) ScopeIt is applicable only for a

It is applicable for all Sessions particular Session Object, on

Example06
JCode Cell
1 
2 <web-app>
3 ...
4 <session-config>
5 <session-timeout>10</session-timeout>
6 </session-config>
7 </web-app>
8

Case Study

Minutes

Indicates that Session never

Indicates that Session neverexpires

expires

Indicates that Session never

expires

Q. How we can implement Log out mechanism?

2 ways.

1st way:

session.invalidate();

2nd way:

session.setMaxInactiveInterval(0);

public class LogOutServlet extends HttpServlet

{

doGet(..)...

{

HttpSession session = req.getSession(false);

if(session != null)

{

session.invalidate();

}

}

}

Note:

If we configured session timeout in all 3 ways then timeout at particular session object will be

considered.

Example07
JCode Cell
1 
2 Units which are created in that Web which we called this Method
3 0 Value Application Seconds
4 -ve Value Sessions will expire immediately
5

Important Methods of HttpSession

To check whether the session object is newly created or not

Example08
JCode Cell
1 
2 public boolean isNew()
3

Important Methods of HttpSession

to expire a session forcefully

Example09
JCode Cell
1 
2 public void invalidate()
3

Important Methods of HttpSession

To set session timeout for a particular session object

Example10
JCode Cell
1 
2 public void setMaxInactiveInterval(int seconds)
3

Important Methods of HttpSession

Returns the session timeout value in seconds

Example11
JCode Cell
1 
2 public int getMaxInactiveInterval()
3

Important Methods of HttpSession

Returns session id

Example12
JCode Cell
1 
2 public String getId()
3

Important Methods of HttpSession

Returns the time when the session was created in milli seconds since Jan 1st 1970.

If we are passing this long value to the Date constructor then we will get exact Date and time.

Eg:

long ms = session.getCreationTime();

Date d = new Date(ms);

SOP(d);

Example13
JCode Cell
1 
2 public long getCreationTime()
3

Important Methods of HttpSession

Returns the time when the client accessed session recently in milli seconds since 1970 Jan 1st.

Example14
JCode Cell
1 
2 public long getLastAccessedTime()
3

Important Methods of HttpSession

Returns the ServletContext object to which this session belongs

HttpSession interface defines the following methods to perform attribute management in session

scope.

Example15
JCode Cell
1 
2 public ServletContext getServletContext()
3

Important Methods of HttpSession

Note: Once session expired,we are not allowed to call most of above methods.Otherwise we will

get RE saying IllegalStateException

Example16
JCode Cell
1 
2 public void setAttribute(String name,Object value)
3 public Object getAttribute(String name)
4 public void removeAttribute(String name)
5 public Enumeration getAttributeNames()
6

Demo Program for session management by using Session API

Example17
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session1/test1">
5 <h1>Enter Books Information</h1>
6 <pre>
7 <h2>Name:<input type="text" name="name">
8 Value:<input type="text" name="value">
9 </h2></pre>
10
11 <input type="submit" value="Add To Cart"/>
12 </form>
13 <a href="/session1/test2">Show My Cart</a>
14 </body>
15 </html>
16

SessionServlet1.java

Example18
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class SessionServlet1 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
10 {
11 PrintWriter out=resp.getWriter();
12 HttpSession hs=req.getSession();
13 if(hs.isNew())
14 {
15 out.println("<h2>New Session got created with session ID:"+hs.getId()+"</h2>");
16 }
17 else
18 {
19 out.println("<h2>Existing Session only using with session ID:"+hs.getId()+"</h2>");
20 }
21 String name=req.getParameter("name");
22 String value=req.getParameter("value");
23 hs.setAttribute(name,value);
24 //hs.setMaxInactiveInterval(120);
25 RequestDispatcher rd = req.getRequestDispatcher("login.html");
26 rd.include(req,resp);
27 }
28 }
29

SessionServlet2.java

session1

|-login.html

|-WEB-INF

|-classes

|-SessionServlet1.class

|-SessionServlet2.class

How the session id exchanging b/w Client and Server:

req 1

resp 1 + set-cookie:JSESSIONID=12345Session

Object

req 2 + cookie:JSESSIONID=12345

Client : Server

:

:

Whenever browser sends a request to server,If server wants to remember client information for

the future purpose,then Server will create Session object and store required information in the

form of attributes.Server sends the corresponding sessionid as the part of response.For this server

will use setCookie response header.

Browser will retrieve that session id and will send with every consecutive request to the

server.For this browser will use cookie request header.

Hence session id exchanging b/w client and server with setCookie response header and cookie

request header.

Demo Program to demonstrate how session id is exchanging b/w client and server:

login.html:

Example19
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.util.*;
6 import javax.servlet.annotation.*;
7 @WebServlet("/test1")
8 public class SessionServlet2 extends HttpServlet
9 {
10 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
11 {
12 PrintWriter out=res.getWriter();
13 HttpSession hs=req.getSession(false);
14 if(hs == null)
15 {
16 out.println("<h2> No session information is available</h2>");
17 }
18 else
19 {
20 Enumeration e = hs.getAttributeNames();
21 out.println("<table border=2><tr><th>Session AttributeName</th><th>Sesion Attribute value</th></tr>");
22 while(e.hasMoreElements())
23 {
24 String name = (String)e.nextElement();
25 String value = (String)hs.getAttribute(name);
26 out.println("<tr><td>"+name+"</td><td>"+value+"</td></tr>");
27 }
28 out.println("</table>");
29 long l1 = hs.getCreationTime();
30 long l2 = hs.getLastAccessedTime();
31 int l3 = hs.getMaxInactiveInterval();
32 out.println("<h3>The creation time is "+new Date(l1)+"</h3>");
33 out.println("<h3>The last accessed time is "+new Date(l2)+"</h3>");
34 out.println("<h3>Max inactive interval is :"+l3+"</h3>");
35 }
36 }
37 }
38

SessionServlet2.java

Example20
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session2/test1">
5 <h1>Enter session information</h1>
6 <pre>
7 <h2>Name:<input type="text" name="uname">
8 Value:<input type="text" name="uvalue">
9 </h2></pre>
10
11 <input type="submit"/>
12 </form>
13 <a href="/session2/test2">RequestHeader Information</a>
14 </body>
15 </html>
16

SessionServlet1.java

Example21
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class SessionServlet1 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10 {
11 PrintWriter out=res.getWriter();
12 HttpSession hs=req.getSession();
13 if(hs.isNew())
14 {
15 out.println("<h2>New Session got created with session ID:"+hs.getId()+"</h2>");
16 }
17 else
18 {
19 out.println("<h2>Existing Session only using with session ID:"+hs.getId()+"</h2>");
20 }
21 String name=req.getParameter("uname");
22 String value=req.getParameter("uvalue");
23 hs.setAttribute(name,value);
24 //hs.setMaxInactiveInterval(120);
25 RequestDispatcher rd = req.getRequestDispatcher("login.html");
26 rd.include(req,res);
27 }
28 }
29

RequestHeaderDemoServlet.java

session2

|-login.html

|-WEB-INF

|-classes

|-SessionServlet1.class

|-RequestHeaderDemoServlet.class

Note:

If the required session information is very less then creating a seperate session object and

maintaining that object at server side is not recommended b'z it creates performance problems.

To resolve this,we should go for Cookies concept,where session information is maintained at client

side & server is not responsible to maintain session info.

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

Session Management by using Cookies

returns the name of the Cookie

Example23
JCode Cell
1 
2 public String getName()
3

Session Management by using Cookies

returns the value of the Cookie

Example24
JCode Cell
1 
2 public String getValue()
3

Session Management by using Cookies

Returns the max age of the Cookie in seconds.

Example25
JCode Cell
1 
2 public 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.

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

Demo Program for session Management by using Cookies

Example27
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session3/test1">
5 <h1>Enter cookie information</h1>
6 <pre>
7 Name:<input type="text" name="uname">
8 Value:<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

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

    <h2>Cookie added successfully</h2>
          

CookieDemoServlet2.java

session3

|-cookie.html

|-WEB-INF

|-classes

|-CookieDemoServlet1.class

|-CookieDemoServlet2.class

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

    </table>
          

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

CookieDemoServlet1.java

Example30
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session4/test1">
5 <h1>Enter cookie information</h1>
6 <pre>
7 Name:<input type="text" name="uname">
8 Value:<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

Example31
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class CookieDemoServlet1 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10 {
11 PrintWriter out=res.getWriter();
12 String name=req.getParameter("uname");
13 String value=req.getParameter("uvalue");
14 Cookie c = new Cookie(name,value);
15 //c.setMaxAge(120);
16 res.addCookie(c);
17 out.println("<h2>Cookie added successfully</h2>");
18 RequestDispatcher rd = req.getRequestDispatcher("cookie.html");
19 rd.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.
Example32
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import java.util.*;
6 import javax.servlet.annotation.*;
7 @WebServlet("/test2")
8 public class RequestHeaderDemoServlet extends HttpServlet
9 {
10 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11 {
12 PrintWriter out = resp.getWriter();
13 out.println("<h1>Request Headers Information</h1></hr>");
14 out.println("<table border=2><tr><th>HeaderName</th><th>Header values</th></tr>");
15 Enumeration e = req.getHeaderNames();
16 while(e.hasMoreElements())
17 {
18 String hname = (String)e.nextElement();
19 out.println("<tr><td>"+hname+"</td><td>"+ req.getHeader(hname)+"</td></tr>");
20 }
21 out.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.

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

RequestHeaderDemoServlet.java

Returns url by appending JSESSIONID.

Example34
JCode Cell
1 
2 public 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.

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

RequestHeaderDemoServlet.java

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

Example36
JCode Cell
1 
2 public boolean isRequestedSessionIdfromURL()
3 public boolean isRequestedSessionIdfromCookie()
4

Demo Program for session management by url rewriting

Example37
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session5/test1">
5 <h1>Enter session information<br>
6 Name:<input type="text" name="uname"><br>
7 <input type="submit"/></h1>
8 </form>
9 </body>
10 </html>
11

SessionServlet1.java

Example38
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class SessionServlet1 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10 {
11 PrintWriter out=res.getWriter();
12 String name=req.getParameter("uname");
13 out.println("<h1>Welcome to Durga Software Solutions</h1>");
14 out.println("<a href=/session5/test2?name="+name+">Click here to get user name</a>");
15 }
16 }
17

SessionServlet2.java

session5

|-login.html

|-WEB-INF

|-classes

|-SessionServlet1.class

|-SessionServlet2.class

Advantages of URL Rewriting:

There is no chance of disabling url rewriting technique. Hence it will work always.

Limitations of URL Rewriting:

1.It is very difficult to rewrite all urls to append session information.Hence it is the most painful

technique.

2.URL Rewriting will work only for dynamic documents.

Session Management by using Hidden Form Fields

It is not official technique from SUN Micro Systems.It is just Programmer's trick to remember client

information.

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an

user.

In such case, we store the information in the hidden field, which is required for future purpose.

We can declare hidden form field as follows..

<input type="hidden" name="uname" value="chitu">

Advantage of Hidden Form Field

It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

  • It is maintained at server side.
  • Extra form submission is required on each page.
  • Session information should be text data
Example39
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test2")
7 public class SessionServlet2 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10 {
11 PrintWriter out=res.getWriter();
12 String name = req.getParameter("name");
13 out.println("<h1>Hi "+name+" Good Morning...");
14 }
15 }
16

Demo Program for session management by hidden form fields

Example40
JCode Cell
1 
2 <html>
3 <body>
4 <form action="/session7/test1">
5 <h1>Enter Name<br>
6 Name:<input type="text" name="uname"><br>
7 <input type="submit"/></h1>
8 </form>
9 </body>
10 </html>
11

SessionServlet1.java

Example41
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class SessionServlet1 extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10 {
11 PrintWriter out=res.getWriter();
12 String name=req.getParameter("uname");
13 out.println("<h1>Welcome "+name+"<br>");
14 out.println("Please provide your age<br>");
15 out.println("<form action="/session7/test2">");
16 out.println("<input type="hidden" name="uname' value='"+name+"'>");
17 out.println("Enter Age:<input type="text" name="age"><br>");
18 out.println("<input type="submit" value="submit age">");
19 out.println("</form>");
20 }
21 }
22

SessionServlet2.java

Example42
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.util.*;
6 import javax.servlet.annotation.*;
7 @WebServlet("/test2")
8 public class SessionServlet2 extends HttpServlet
9 {
10 public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
11 {
12 PrintWriter out=res.getWriter();
13 String name = req.getParameter("uname");
14 String age = req.getParameter("age");
15 out.println("<h1>Hi "+name+" Plz enter your Girl Friend Name...");
16 out.println("<form action='/session7/test3'>");
17 out.println("<input type="hidden" name="uname" value='"+name+"'>");
18 out.println("<input type="hidden" name="uage" value='"+age+"'>");
19 out.println("Enter Girl Friend Name:<input type="text" name="ugfriend"><br>");
20 out.println("<input type="submit" value="submit Girl Friend Name">");
21 out.println("</form>");
22 }
23 }
24

SessionServlet3.java

throws ServletException,IOException

Example43
JCode Cell
1 
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.util.*;
6 import javax.servlet.annotation.*;
7 @WebServlet("/test3")
8 public class SessionServlet3 extends HttpServlet
9 {
10 public void doGet(HttpServletRequest req,HttpServletResponse res)
11

SessionServlet3.java

session7

|-login.html

|-WEB-INF

|-classes

|-SessionServlet1.class

|-SessionServlet2.class

|-SessionServlet3.class

Listeners

Objective:

  • Describe web container event life cycle model for the request,session and web application.

2.Create and configure Listener class for each scope

3.Create and configure attribute listener for each scope

4.For the given scenario identify proper attribute listener?

In the web application there may be a chance of occuring several events like

Request object creation

Request object Destruction

Session object creation

Session object Destruction

Context object creation

Context object destruction

Attribute addition in request scope

Attribute Removal in request scope

Attribute Replacement in request scope

.....

whenever these events occur,if we want to do particular operation automatically then we should

go for listeners.

i.e Listener listens the events and will perform certain operations automatically.

All Listeners are divided into 3 groups

  • Request Listeners:

These listen events related to request.

There are 2 types of Request Listeners

  • ServletRequestListener
  • ServletRequestAttributeListener
  • Session Listeners:

These listen the events related to session. There are 4 types of session listeners.

  • HttpSessionListener
  • HttpSessionAttributeListener
  • HttpSessionBindingListener
  • HttpSessionActivationListener
  • Context Listeners:

These listen events related to context.

There are 2 types of context listeners

Example44
JCode Cell
1 
2 {
3 PrintWriter out=res.getWriter();
4 String name = req.getParameter("uname");
5 String age = req.getParameter("uage");
6 String gfriend = req.getParameter("ugfriend");
7 out.println("<h1>Your Total Information is:<br>");
8 out.println("Name:"+name+"<br/>");
9 out.println("Age:"+age+"<br/>");
10 out.println("Girl Friend Name:"+gfriend+"<br/>");
11 out.println("Thanks for providing Complete information</h1>");
12 }
13 }
14

SessionServlet3.java

This listener listens life cycle events of request object like creation and destruction.

This interface defines the following 2 methods.

1.public void requestInitialized(ServletRequestEvent e)

This method will be executed automatically at the tine of request object creation. i.e just before

starting service() method.

Example45
JCode Cell
1 
2 ServletContextListener
3 ServletContextAttributeListener.
4 ServletRequestListener(I):
5

SessionServlet3.java

This method will be executed automatically at the time of request object destruction. ie just

after completing service() method.

Example46
JCode Cell
1 
2 public void requestDestroyed(ServletRequestEvent e)
3
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets