Saturday 6 September 2014

Add ServletContextListener using Deployement Descriptor

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        try(PrintWriter out = res.getWriter()){
            System.out.println("Application started");
            out.println("Hiiiii");
        }
    }
}

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListenerEx implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Context Initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Context Destroyed");
    }
}

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>ServletContextListener</description>
        <listener-class>ContextListenerEx</listener-class>
    </listener>
</web-app>

you can see messages like below in server console.
Info:   Context Initialized
Info:   Loading application [servlet] at [/servlet]
Info:   servlet was successfully deployed in 318 milliseconds.
Info:   Application started

Stop the server, then you can see the message ' Context Destroyed'.
Info:   Context Initialized
Info:   Loading application [servlet] at [/servlet]
Info:   servlet was successfully deployed in 318 milliseconds.
Info:   Application started
Info:   Server shutdown initiated
Info:   Unregistered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishImpl@145f97d from service registry.
Info:   FileMonitoring shutdown
Info:   JMXStartupService: Stopped JMXConnectorServer: null
Info:   JMXStartupService and JMXConnectors have been shut down.
Info:   Context Destroyed



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment