5/20/2009

ServeltContextListener

ServletContextListener handles ServletContextEvents.
ServletContextEvent notifies the creation or deletion of context.

Methods:
contextInitialized(ServletContextEvent sce)
contextDestroyed(ServletContextEvent sce)

The listener is for setting common information in the application.
The information set in it can be used in everypage.
In a distributed environment, a ServletContext is created in each JVM, and therefore setting global information in the ServletContext attributes is not recommended.


<Sample>
web.xml
    <listener>
        <display-name>Context Listener</display-name>
        <listener-class>listener.ListenerSample1</listener-class>
    </listener>
_________

ListenerSample.java
public class ListenerSample1 implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.setAttribute("message", "Good Morning");
    }
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.removeAttribute("message");
    }
}
_________

sample.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:out value="${applicationScope.message}" />
</body>
</html>

<Result>http://localhost:8080/SCWCD/sample.jsp
Good Morning