Saturday 6 September 2014

Add ServletContextListener using WebListener Annotation

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

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

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

Run SampleApp then 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