Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML

Search:
   Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML Facing Programming Problem? Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java Servlets
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
HttpSessionAttributeListener Example
As we know that the Session is used to maintain the session between request. Session object is responsible to hold the conversational state across multiple requests.
 
 

HttpSessionAttributeListener Example

                         

As we know that the Session is used to maintain the session between request. Session object is responsible to hold the conversational state across  multiple requests.

The listener HttpSessionAttributeListener is an interface and extends the java.util.EventListener class. This listener will be called by the container whenever there there will be change to the attribute list on the servlet session of a web application. This listener is used when we want to know when a attribute has been added in a session, when a attribute has been removed and when it is replaced by another attribute. We can also say that this attribute is  used when the developer is interested to be notified when the session attribute changes. Now you may be wondering what is an attribute. An attribute is an object set or you can simply say that it is name/value pair where the name refers to a String and a value refers to the Object.

javax.servlet.http.HttpSessionAttributeListener interface has following methods:

  1. attributeAdded(HttpSessionBindingEvent event): It notifies whenever a new  attribute is added to the servlet session.
  2. attributeRemoved(HttpSessionBindingEvent event): It notifies whenever the attribute is removed from the servlet session.
  3. attributeReplaced(HttpSessionBindingEvent event): It notifies whenever the attribute gets replaced on the servlet session.

In the above methods you can see that we have used HttpSessionBindingEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of  in a session.

The class HttpSessionBindingEvent has two methods:

  1. getName() : This method returns the name of the attribute that has been change in the session.
  2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute.
  3. getSession(): This method will return the session that has been changed.

The code of the program is given below:

import javax.servlet.*;
import javax.servlet.http.*;

public class SessionAttributeListenerExample
implements HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent 
sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
// Log some information
System.out.println("[SessionAttr] "+new java.util.Date()+
" Attribute added, session "+session+": "
+sessionBindingEvent.getName()+"="+
sessionBindingEvent.getValue());

public void attributeRemoved(HttpSessionBindingEvent 
sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
System.out.println(new java.util.Date()+" Attribute removed, 
session "+session+": "+sessionBindingEvent.getName());

public void attributeReplaced(HttpSessionBindingEvent 
sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
// Log some information
System.out.println(new java.util.Date()+" Attribute 
replaced, session "+session+": "+sessionBindingEvent
.getName()+"="+sessionBindingEvent.getValue());
}
}

 

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class AttributeSessionForSession extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
session.setAttribute("dog", "Labrador");
session.setAttribute("name", "moti");
session.setAttribute("age","5");
String str1 = (String)session.getAttribute("dog");
pw.println("The breed of the dog is " + str1);
String str2 = (String)session.getAttribute("age");
pw.println("The age of the dog is " + str2);
session.removeAttribute("name");
}
}

The output of the program is given below:

The output on the server will look like this:

Download this example.

 

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

3 comments so far (
post your own) View All Comments Latest 10 Comments:

Hi Roseindia team...

please tell me why you wrote SessionAttributeListenerExample class what is the use of this class, rather the output is only coming from AttributeSessionForSession this class... so what makes the difference if i will not use 1'st program and will use only second program... will it make any big problem in real time programming...

Posted by sunny on Saturday, 05.24.08 @ 04:01am | #60808

Hi,
Really I thanks to this roseindia website...There is no website having these resources..surely...My best wish and thanks to RoseIndia...

Jaihind...

Posted by Chithambaram.P on Wednesday, 03.19.08 @ 13:39pm | #53303

HI, I'D PROVED THIS CODE AND IT WORKS, THANKS, BUT IF I WANT TO SHOW THE OBJECT SESSION TO AN ADMINISTRATOR WHO HAS BEEN LOGIN TO MY APPLICATION LIKE THIS:
HI user_name | you are [admin] IN this app | these are all THE USERS CONECTED RIGTH NOW ->omm79/ADMIN
->jlmm /user
->bebo /user
I'M TRIYING YO DO SOMETHIG BUT ALL I GOT IS JUST WATCH THE SESSION INFO IN THE SERVER SIDE COMMAND-WINDOW, AND I'LL APRETIATE IF THERE IS AN EXAMPLE TO CHECK, TAHNKS.

Posted by oscar on Saturday, 05.12.07 @ 01:50am | #15681

Latest Tutorials:
Styles in HTML
Style Tags Used in HTM
Check Box in HTML
Action Submit Html
Cascading Style Sheet(
Horizontal Rule Attrib
Horizontal Rule in HTM
Show Hyperlink in HTML
Unordered Lists
Paragraph in HTML
Password Field in HTML
Radio Buttons in HTML
Set Background Colors
Table & the Border att
Text Area in HTML
Text Field in HTML
Use of Text Field
Table Caption in HTM
J2ME Servlet Example
J2ME Cookies Example
J2ME Frame Animation2
J2ME Frame Animation
J2ME RMS Read Write
J2ME Record Data Base
J2ME Audio Record
J2ME Record Listener
J2ME Text Box Example
J2ME Timer Animation
J2ME Vector Example
J2ME Video Control Exa
J2ME Event Handling Ex
J2ME HashTable Example
J2ME Icon MIDlet Examp
J2ME Image Item Exampl
J2ME Image Example
J2ME Item State Listen
J2ME Key Codes Example
J2ME KeyEvent Example
J2ME Label Example
J2ME Random Number
J2ME Read File
J2ME RMS Sorting Examp
J2ME Timer MIDlet Exam
Custom Item in J2ME
Creational Design Patt
Design Patterns
Throwing Run time exce
Grid in Echo3
Creating Table in Echo
JPA Introduction
Java bigdecimal toBigI
Java bigdecimal shortV
Java bigdecimal shortV
Java bigdecimal signum
Java bigdecimal stripT
Java bigdecimal subtra
Java bigdecimal subtra
Java bigdecimal toBigI
Java bigdecimal toEngi
Java bigdecimal toPlai
Java bigdecimal toStri
Java bigdecimal ulp ex
Java bigdecimal unscal
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal setSca
Java bigdecimal setSca
Java bigdecimal scaleB
Java bigdecimal scale
Java bigdecimal round
Java bigdecimal remain
Java bigdecimal remain
Java bigdecimal precis
Java bigdecimal pow me
Java bigdecimal pow ex
Java bigdecimal plus m
Java bigdecimal plus e
Java bigdecimal negate
Java bigdecimal negate
Java bigdecimal multip
Java bigdecimal multip
Java BigDecimal movePo
Java bigdecimal movePo
Java bigdecimal min ex
Java bigdecimal max ex
CheckBox component in
Visibility of Componen
Loading delay componen
Simple input applicati
Opening a new window i
Hello World in Echo3 f
Use of Local Inner cla
JSP bean set property
Java Method Synchroniz
Java Method Return Val
JAVA Method Wait
JDBC vs ORM
Java BigDecimal divide
Java BigDecimal divide
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.