Servlets - SPLessons

Servlet HttpSession Listener

Chapter 24

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Servlet HttpSession Listener

Servlet HttpSession Listener

shape Description

Servlet HttpSession Listener, HttpSessionEvent is a class gives cautions when session object is changed, HttpSessionInterface is an interface which will be in dynamic mode when a session is made or devastated. By using this event developer can perform some actions such as log in or log out details. The HttpSessionInterface will have methods needs to be imported while performing any task by using session events, following are the methods.

public void sessionCreated(HttpSessionEvent e)//invoked when session object is created.
public void session destroyed(ServletContextEvent e)//invoked when session invalidated.

shape Example

Servlet HttpSession Listener, Following is an example to calculate current logged-in users.

index.html


<form action="servlet1">
	Name:<input type="text" name="username">
	Password:<input type="password" name="userpass">
    <input type="submit" value="login"/>
</form>

Here the developer just created the two text boxes to enter the Name and Password.
web.xml

<web-app> 
  
  <listener>
  <listener-class>sessionevent1.CountUserListener</listener-class>
  </listener>
  
  <servlet>
     <servlet-name>First</servlet-name>
    <servlet-class>sessionevent1.First</servlet-class>
  </servlet>
  <servlet>
      <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>sessionevent1.LogoutServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>First</servlet-name>
    <url-pattern>/servlet1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/logout</url-pattern>
  </servlet-mapping>
  
</web-app>

Make sure to mention the URL of the servlet here and that should be same with HTML form.
CountUserListener.java

package sessionevent1;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountUserListener implements HttpSessionListener{
	ServletContext ctx=null;
	static int total=0,current=0;
	
	public void sessionCreated(HttpSessionEvent e) {
	total++;
	current++;
	
	ctx=e.getSession().getServletContext();
	ctx.setAttribute("totalusers", total);
	ctx.setAttribute("currentusers", current);
	
	}

	public void sessionDestroyed(HttpSessionEvent e) {
			current--;
			ctx.setAttribute("currentusers",current);
	}

}

Here CountUserListener is the class that implementing the HttpSessionListener, sessionCreated(HttpSessionEvent se) Receives the notification that a session has been created.
First.java

package sessionevent1;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
	
		String n=request.getParameter("username");
		out.print("Welcome "+n);
		
		HttpSession session=request.getSession();
		session.setAttribute("uname",n);
		
		ServletContext ctx=getServletContext();
		int t=(Integer)ctx.getAttribute("totalusers");
		int c=(Integer)ctx.getAttribute("currentusers");
		out.print("total users= "+t);
		out.print("current users= "+c);
		
		out.print("<a href='logout'>logout</a>");
		
		out.close();
	}

}

The setContentType(String) is defined in ServletResponse interface and inherited by HttpServletResponse interface. request.getParameter() method in the servlet class, to retrieve the input values from HTML page. request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).
LogoutServlet.java

package sessionevent1;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
	
		HttpSession session=request.getSession(false);
		session.invalidate();
		
		out.print("You are successfully logged out");
		
		
		out.close();
	}

}

The PrintWriter is an abstract class for writing to character streams. Methods implement are write(char[], int, int), flush(), and close()). Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).
Output
Following is the generated page when compile the code where user has to enter details.

Entered details will be visible in this page.
When user click on logout the page will be logged out.

Difference Between HttpSessionAttributeListener And HttpSessionBindingListener

shape Description

The HttpSessionBindingListener interface is executed by objects that need to be advised when objects are bound to a session or unbound from a session when they bound or unbound to the session. HttpSessionBindingListeners execute the valueBound and valueUnbound techniques.

In HttpSessionAttributeListener, the class that executes this interface must be determined in the Deployment Descriptor. At whatever point any session characteristics are included, evacuated and supplanted, it will be advised. HttpSessionAttributeListeners execute the attributeAdded, attributeRemoved and attributeReplaced strategies. A web application which has a HttpSessionAttributeListener would typically have one such audience which would deal with all characteristics and all sessions.


Summary

shape Key Points

  • Servlet HttpSession Listener – HttpSessionListener is an interface.
  • HttpSessionEvent is a class.
  • Servlet HttpSession Listener – The get() can not carry huge amount of information through the browser.
  • Servlet HttpSession Listener – The post() takes huge information to pass.