Saturday, 6 September 2014

Add ServletContextAttributeListener using web.xml

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 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");
        }
    }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <listener>
        <description>ServletContextAttributeListener</description>
        <listener-class>ContextAttrListener</listener-class>
    </listener>
</web-app>

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