import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; 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 javax.servlet.*; import javax.servlet.annotation.WebListener; @WebListener public class ContextListener1 implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); /* Add Context Listener */ System.out.println("Adding Context Attribute listener"); context.addListener(ContextAttrListener.class); System.out.println("Context Listener1 Initialized"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("Context Listener1 Destroyed"); } }
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"); } } }
context.addListener(ContextAttrListener.class);
Above
statement add the Attribute listener ' ContextAttrListener' to the
servlet context.
Run
' SampleApp', server console has messages like below.
Info: Adding Context Attribute listener Info: Context Listener1 Initialized Info: Attribute com.sun.enterprise.web.WebModule.DeploymentContext Removed Info: Attribute com.sun.enterprise.web.WebModule.isDistributable Removed Info: Attribute com.sun.enterprise.web.WebModule.enableHA Removed Info: Attribute com.sun.jsp.taglibraryCache Added Info: Attribute com.sun.jsp.tagFileJarUrlsCache Added Info: Loading application [servlet] at [/servlet] Info: servlet was successfully deployed in 258 milliseconds. Info: Adding Attribute to Servlet Context Info: Attribute myName Added Info: Replacing Attribute from Servlet Context Info: Attribute myName Replaced Info: Removing Attribute from Servlet Context Info: Attribute myName Removed
No comments:
Post a Comment