Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

Tuesday, August 06, 2013

How to Track Session Attribute - HttpSessionAttributeListener Example

If You want to track session Attribute like whether there is new session attribute added,removed or replaced during application lifecycle then HttpSessionAttributeListener is for You !

HttpSessionAttributeListener is abstract interface which comes as part of servlet-api.jar which has abstract method such as attributeAdded,attributeRemoved,attributeReplaced.

How it works : 
  • When new session attribute is added using set then attributeAdded will be called.
HttpSession session = request.getSession();
session.setAttribute("sessionName","LoginIn");
  • If you try to set attribute value to some different value which is already present then attributeReplaced will be called. ex. session.setAttribute("sessionName","LoggedIn");

How to Calculate Total Active Session - HttpSessionListener Example

If you have web application and you want to count total number of active session then HttpSessionListener is for you !

HttpSessionListener is abstract interface provided as part of servlet-api.jar which has abstract method such as sessionCreated and sessionDestroyed which get executed every time when we create new session using httpSession or invalidate session.

By default one session is created. so when you use HttpSession session = request.getSession(); in HttpServlet then it will give you that session. You can invalidate session using session.invalidate();

Listener - ServletContextListener Example

If You want to do something before application starts, then ServletContextListener is for you.

ServletContextListener is abstract interface provided as part of servler-api.jar which provides contextDestroyed and contextInitialized abstract method. One can create class which implements ServletContextListener and write implementation logic for example, logic that does something before web application starts.

Wednesday, July 24, 2013

How to Download File using Servlet

Consider that I have file containing project information available into server and I want to download that file. Using webservices you can also achieve same but Here, I am going to discuss "Download File using Servlet"

Steps to be Performed to Download File using Servlet :
  1. Create Servlet File which will download file available in server
  2. Add Servlet entry into Web.xml or annotate with @WebServlet