Saturday 6 September 2014

Add ServletContextAttributeListener Using WebListener Annotation


import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ContextAttrListener implements ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("Attribute " + event.getName() + " Added");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        System.out.println("Attribute " + event.getName() + " Removed");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        System.out.println("Attribute " + event.getName() + " Replaced");
    }
}

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.*;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        try(PrintWriter out = res.getWriter()){
            ServletContext context = req.getServletContext();
            
            System.out.println("Adding Attribute to Servlet Context");
            context.setAttribute("myName", "Krishna");
            
            System.out.println("Replacing Attribute from Servlet Context");
            context.setAttribute("myName", "abcd");
            
             System.out.println("Removing Attribute from Servlet Context");
            context.removeAttribute("myName");
        }
    }
}

Run ' SampleApp', server console has messages like below.

Info:   Attribute myName Added
Info:   Replacing Attribute from Servlet Context
Info:   Attribute myName Replaced
Info:   Removing Attribute from Servlet Context
Info:   Attribute myName Removed





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment