ServletContextListener

Hi all,
In our application (environment -- Apache 1.3 , Apache Jserv 1.1.2,
JDK 1.3, JSDK 2.0 and Oracle 8i) .We are useing our own databse pooling.I want to implement ServletContext Listener with Apache Jserv. Can any one give us the details for the below question:
1. How to call my ServletContextClass at the time of apache server startup?
2. When apache server shutdown, we want to release/close the database
connections. How to do it?
Thanks in advance.
regards,
Aseem

Hi
You need to implement ServletContextListener
implement these two methods
1)
public void     contextInitialized(ServletContextEvent ce) {
Open connection .
public void     contextDestroyed(ServletContextEvent ce) {     
Close Connection.
in web.xml
<listener>
<listener-class> Name of the Servlet <listener-class>
</listener>

Similar Messages

  • Create A Connection Pool In the ServletContextListener

    The Specification says that we should create the connection pool in the ServletContextListener. I have the code for creating a connection pool (see below). How do I create it in the ServletContextListener?
    import java.sql.Connection;
    import java.sql.SQLException;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    public class DBConnection
       public static Connection getDBConnection() throws SQLException
          Connection conn = null;
          try
             InitialContext ctx = new InitialContext();
             DataSource ds = ( DataSource ) ctx.lookup( "java:comp/env/jdbc/MySQLDB" );
             try
                conn = ds.getConnection();
             catch( SQLException e )
                System.out.println( "Open connection failure: " + e.getMessage() );
          catch( NamingException nEx )
             nEx.printStackTrace();
          return conn;

    I use the connection pool feature provide by the server I use. Is this what I should do? Please confirm.
    import java.sql.Connection;
    import java.sql.SQLException;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    import javax.servlet.*;
    public class CreateResources implements javax.servlet.ServletContextListener
         public void contextInitialized(ServletContextEvent sce)
              public static Connection getDBConnection() throws SQLException
                   Connection conn = null;
                   try
                        InitialContext ctx = new InitialContext();
                        DataSource ds = ( DataSource ) ctx.lookup( "java:comp/env/jdbc/MySQLDB" );
                        try
                             conn = ds.getConnection();
                        catch( SQLException e )
                             System.out.println( "Open connection failure: " + e.getMessage() );
                  catch( NamingException nEx )
                        nEx.printStackTrace();
                  return conn;
         public void contextDestroyed(ServletCotnextEvent sce)
    }

  • Not able to get the context attribute set in ServletContextListener

    Hi all,
    I have written a simple ServletContextListener and set an attribute in it. when i am trying to retrieve the attribute value in my servlet, I am getting as null. Could anybody please let me know about this if i need to add any more changes.
    Below is the complete code of my sample application
    web.xml
    <web-app>
    <servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.mypackage.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <listener>
    <listener-class>
    com.mypackage.MyContextListener
    </listener-class>
    </listener>
    <context-param>
    <param-name>testMe</param-name>
    <param-value>TestedSuccessfully</param-value>
    </context-param>
    </web-app>
    ContextListener
    package com.mypackage;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    public class MyContextListener implements ServletContextListener{
    public void contextDestroyed(ServletContextEvent arg0) {
    public void contextInitialized(ServletContextEvent arg0) {
    ServletContext context = arg0.getServletContext();
    String testApplication = context.getInitParameter("testMe");
    context.setAttribute("myTest", "mkmmkmmkm");
    Servlet
    package com.mypackage;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class MyServlet extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response){
    ServletContext context = getServletContext();
    if(context != null){
    response.setContentType("text/html");
    try {
    String output = (String) getServletContext().getAttribute("testMe");
    PrintWriter out = response.getWriter();
    out.print("The required value is... "+output);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    OUTPUT
    When accessed with any url as below:
    http://localhost:8080/helloworld/u
    gettting output as "The required value is... null" . Because i set the context attribute, I am expecting not null. Can anybody suggest me on this.

    context.setAttribute("myTest", "mkmmkmmkm");
    String output = (String) getServletContext().getAttribute("testMe");You set "myTest" but try to get "testMe"

  • How to call application module from ServletContextListener

    Hi,
    I've got an application that requires authenticated users. However, before the application starts I'd like to do some DB initialization.
    So I created a ServletContextListener and in contextInitialized method I try to createRootApplicationModule.
    Due to authentication / authorization requirements, createRootApplicationModule fails with:
    ov 12, 2008 12:09:33 AM oracle.adf.share.security.authentication.JAASAuthenticationService doLogin
    INFO: LoginContext.login...
    javax.security.auth.login.LoginException: Invalid null input: name
         at javax.security.auth.login.LoginContext.init(LoginContext.java:229)
         at javax.security.auth.login.LoginContext.<init>(LoginContext.java:367)
         at javax.security.auth.login.LoginContext.<init>(LoginContext.java:444)
         at oracle.adf.share.security.authentication.JAASAuthenticationService.doLogin(JAASAuthenticationService.java:102)
         at oracle.adf.share.security.authentication.JAASAuthenticationService.login(JAASAuthenticationService.java:89)
         at oracle.adf.share.security.authentication.JAASAuthenticationService.login(JAASAuthenticationService.java:71)
         at oracle.jbo.common.UserAznUtil.authenticate(UserAznUtil.java:62)
         at oracle.jbo.common.UserAznUtil.authenticateUser(UserAznUtil.java:29)
         at oracle.jbo.server.ApplicationModuleImpl.prepareSession(ApplicationModuleImpl.java:6387)
         at oracle.jbo.server.ApplicationModuleImpl.prepareSession(ApplicationModuleImpl.java:6356)
         at oracle.jbo.server.ApplicationPoolMessageHandler.doPoolMessage(ApplicationPoolMessageHandler.java:171)
         at oracle.jbo.server.ApplicationModuleImpl.doPoolMessage(ApplicationModuleImpl.java:8377)
         at oracle.jbo.common.ampool.ApplicationPoolImpl.sendPoolMessage(ApplicationPoolImpl.java:4364)
         at oracle.jbo.common.ampool.ApplicationPoolImpl.prepareApplicationModule(ApplicationPoolImpl.java:2421)
         at oracle.jbo.common.ampool.ApplicationPoolImpl.doCheckout(ApplicationPoolImpl.java:2207)
         at oracle.jbo.common.ampool.ApplicationPoolImpl.useApplicationModule(ApplicationPoolImpl.java:3086)
         at oracle.jbo.common.ampool.SessionCookieImpl.useApplicationModule(SessionCookieImpl.java:453)
         at oracle.jbo.common.ampool.SessionCookieImpl.useApplicationModule(SessionCookieImpl.java:424)
         at oracle.jbo.common.ampool.SessionCookieImpl.useApplicationModule(SessionCookieImpl.java:419)
         at oracle.jbo.client.Configuration.getApplicationModule(Configuration.java:1395)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1363)
         at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1335)
    Can I somehow explicitly login a valid user or exclude the specific application module from authorization?
    Regards
    J

    Hi,
    no, the function is not related to user session. It's actually data synchronization between two systems.
    We'd prefere to keep it in middle tier, through web services on one side and AM on the other. This way we are platform / RDBMS independent.
    I could use a fake system user, eg. "sync" with password "sysnc", but how do I "log on" such user in my EJB code? If I could somehow access AM login context and call login with username and password...?
    Edit:
    it also puzzles me that it's possible to have a page within the aplication that allows anonymous access. The only difference in security context seem to be _isHttp property. getUserPrincipaly returns JpsAnonymousUserImpl in both cases, IsAuthenticated() is false in both cases...
    Edited by: Jernej Kase on Nov 13, 2008 8:57 PM

  • Using ServletContextListener for background process in tomcat, problems?

    Hi, I am building a web app using mojarra 1.2, hibernate 3.2, mysql 5 and tomcat 6. Currently, there's a need to run a background process every hour to:
    1) query the database
    2) process information
    3) send emails to (big) list of individuals when matched
    4) update database
    5) must happen during business hour
    For now, my approach to this problem is to hook a Timer object inside a class implements ServletContextListener. So that every hour during business hour will process the steps above when Tomcat started until someone shut down shut down Tomcat or when it crash (hopefully that won't happen).
    I read a few articles, they claimed this is not a good approach because in a managed environment, background thread like this won't be in the scope of the container.
    Due to certain reasons, we can't deploy this part as a separate daemon (e.g: jsvc) yet. We'll need to wait for few other things to occur before can we deploy a full daemon services.
    The question for this post is: What are some of the potential problems we will be dealing with when running background thread like this in tomcat? What are some of the things we'll need to watch out for before real problems arise (e.g size of db connection, # of concurrent process, etc) what are some other pitfalls other experienced when deploying background thread in tomcat?
    We hope this solution will be able to handle what needs to be done until our daemon service is ready.
    Thank you for your opinions

    You can try this.. Which gives more grip... in making threads etc..
    Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
    import static java.util.concurrent.TimeUnit.*;
    class BeeperControl {
    private final ScheduledExecutorService scheduler =
    Executors.newScheduledThreadPool(1);
    public void beepForAnHour() {
    final Runnable beeper = new Runnable() {
    public void run() { System.out.println("beep"); }
    final ScheduledFuture<?> beeperHandle =
    scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
    scheduler.schedule(new Runnable() {
    public void run() { beeperHandle.cancel(true); }
    }, 60 * 60, SECONDS);
    }

  • ServletContextListener implementation

    I'm having difficulties maintaining information about session activity between server restarts.
    I've written some code which works the way I'd like it to on my development machine. But when I upload the application to the production server it doesn't work the same way.
    I've written a class which implements ServletContextListener as well as HttpSessionListener. The class contains a local variable totalSessionCount' which maintains the value of the number of sessions that have been created. I increment this variable in the sessionCreated method.
    And I implement the method contextDestroyed where I write the variable to a properties file. This all works on my development machine.
    For diagnostice purposes, I've written some System.out.println statements in the contextDestroyed method. I notice that on my development machine the method is called once, and the correct values appear in the log.
    public void contextDestroyed( ServletContextEvent event ) {
         System.out.println(" *** SessionContextListener - Context Destroyed" );
         System.out.println(" *** \t\t " + this.totalSessionCount );
    }What appears in the log on my development machine is below...
    *** SessionContextListener - Context Destroyed
    ***               total sessions - 4And so the value 4 appears in the log.
    But on the production server this method is called twice.
    It looks like another instance of this class is created for some reason.
    *** SessionContextListener - Context Destroyed
    ***               total sessions - 3
    *** SessionContextListener - Context Destroyed
    ***               total sessions - 0And it would seem that the second instance is over writing the proper value that is maintained by the first instance of this listener class, because the value 0 appears in the log. Why is a second instance of this listener created on one Tomcat instance but not on the other and how do I control this?
    Any help is appreciated.
    Edited by: nantucket on Sep 25, 2007 2:31 PM
    I found a related thread here
    http://forum.java.sun.com/thread.jspa?forumID=33&threadID=542933
    which gives me the idea to include a little hack
    in my code
    if ( totalSessionCount == 0 ) {
         return;
    }Thereby, preventing the 0 value from being logged, which is the default value
    in the instance of the listener anyway. This helps me move past the issue, but
    I'm still curious as to why I'm getting two instances of my listener.
    Edited by: nantucket on Sep 25, 2007 6:00 PM

    Listener
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSession;
    import java.util.Hashtable;
    import java.util.LinkedList;
    * Created by vijay .dr
    * User: scalar9
    * Date: Sep 22, 2007
    * Time: 2:46:58 PM
    public final class GetAllCurrentUsersAction  implements HttpSessionAttributeListener {
      public static Hashtable current_session_user = new Hashtable ();
      public GetAllCurrentUsersAction() {
      public void attributeAdded(HttpSessionBindingEvent sessionBindingEvent)
          HttpSession session = sessionBindingEvent.getSession();
          current_session_user.put (session.getId()+"","user");
      public void attributeRemoved(HttpSessionBindingEvent sessionBindingEvent)
        HttpSession session = sessionBindingEvent.getSession();
        current_session_user.remove(session.getId()+"");
      public void attributeReplaced(HttpSessionBindingEvent sessionBindingEvent)
    web.xml
        <!-- Listeners -->
         <listener>
              <listener-class>com.scalar.chiptrack.GetAllCurrentUsersAction</listener-class>
         </listener>
    GetSession.jsp
    <%
         Enumeration enum_user = GetAllCurrentUsersAction.current_session_user.elements();
         while ( enum_user.hasMoreElements())
    //display the values in table..some of code is deleted to our personal things....

  • RMI JNDI Lookup in ServletContextListener

    Hi,
    I am attempting to do a JNDI lookup (using the RMIInitialContextFactory) of a session EJB inside a ServletContextListener. But when I do I get an exception saying it cannot find the name I lookup. If I set rmi.debug to true I can see that a 'SocketException: Socket closed' is caught internally. I can also see from the RMI debug that the attempt to load the EJB interface class fails because it is trying to use the application server's classloader and not the web applications classloader. If I put the JAR containing the interface class into the applib directory none of the above occurs.
    Should I be able to do the JNDI lookup within the SerlvetContextListener? Is this a bug?
    Cheers,
    Rich.

    This exception only appears once I turn rmi.debug on. Like I said previously if I put the EJB interfaces JAR into applib it does not occur.
    05/03/14 09:03:56 java.net.SocketException: socket closed
    05/03/14 09:03:56 at java.net.SocketInputStream.socketRead0(Native Method)
    05/03/14 09:03:56 at java.net.SocketInputStream.read(SocketInputStream.java:129)
    05/03/14 09:03:56 at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
    05/03/14 09:03:56 05/03/14 09:03:56 Exception raised when creating initial context:
    at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
    05/03/14 09:03:56 at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2133)
    05/03/14 09:03:56 at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2313)
    05/03/14 09:03:56 at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2380)
    05/03/14 09:03:56 at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2452)
    05/03/14 09:03:56 at java.io.ObjectInputStream$BlockDataInputStream.readByte(ObjectInputStream.java:2601)
    05/03/14 09:03:56 at java.io.ObjectInputStream.readByte(ObjectInputStream.java:845)
    05/03/14 09:03:56 at com.evermind.server.rmi.RMIConnection.readCommand(RMIConnection.java:3455)
    05/03/14 09:03:56 at com.evermind.server.rmi.RMIConnection.run(RMIConnection.java:380)
    05/03/14 09:03:56 at com.evermind.server.rmi.RMIConnection.run(RMIConnection.java:333)
    05/03/14 09:03:56 at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecu
    tor.java:186)
    05/03/14 09:03:56 at java.lang.Thread.run(Thread.java:534)

  • ServletContextListener not receiving event

    Hi
    Running 9.0.3 Enterpise with Webcache on Windows2000.
    I have a test servlet that wait for the ServletContextListener event to fire. This happens on OC4J standalone but not on Enterpise release...
    Here is servlet
    package co.za.mtn.wizard.servlets;
    import javax.servlet.ServletContextListener;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContext;
    public class TestListener implements ServletContextListener
    private ServletContext context = null;
    public void contextInitialized(ServletContextEvent event)
    System.out.println("Doing servlet context listener in TestListener");
    context = event.getServletContext();
    public void contextDestroyed(ServletContextEvent event)
    context = event.getServletContext();
    This is configured in WEB.XML as first element
    <listener>
    <listener-class>co.za.mtn.wizard.servlets.TestListener</listener-class>
    </listener>
    Any ideas as how to get this to fire?
    Tks
    Andre

    adding to the above
    I have two servlets that implements this listener:
    One in AppserverRoot and one in wizprepaid
    Both application are set to auto-start.
    From the log this only fires on the first action to this applciation.
    Here is server.xml
    <?xml version = '1.0'?>
    <!DOCTYPE application-server PUBLIC "-//Evermind//DTD Orion Application-server//EN" "http://xmlns.oracle.com/ias/dtds/application-server.dtd">
    <application-server localhostIsAdmin="true" application-directory="../applications" deployment-directory="../application-deployments" connector-directory="../connectors">
         <rmi-config path="./rmi.xml"/>
         <jms-config path="./jms.xml"/>
         <log>
              <file path="../log/server.log"/>
         </log>
         <transaction-config timeout="30000"/>
         <java-compiler name="modern" in-process="false" extdirs="c:\Oracle9i_App\jdk\jre\lib\ext"/>
         <global-application name="default" path="application.xml"/>
         <application name="AppserverRoot" path="../applications/AppserverRoot.ear" auto-start="true"/>
         <application name="MtnIsis" path="../applications/MtnIsis.ear" parent="AppserverRoot" auto-start="true"/>
         <application name="WizIsis" path="../applications/WizIsis.ear" parent="MtnIsis" auto-start="true"/>
         <application name="wizprepaid" path="../applications/wizprepaid.ear" parent="WizIsis" auto-start="true"/>
         <application name="WizardNis" path="../applications/WizardNis.ear" parent="wizprepaid" auto-start="true"/>
         <application name="WizPPMED" path="../applications/WizPPMED.ear" parent="WizardNis" auto-start="true"/>
         <application name="WizardSMS" path="../applications/WizardSMS.ear" parent="WizPPMED" auto-start="true"/>
         <application name="CheckStatus" path="../applications/CheckStatus.ear" parent="WizardSMS" auto-start="true"/>
         <application name="Wizescalations" path="../applications/Wizescalations.ear" auto-start="true"/>
         <application name="WizIntegration" path="../applications/WizIntegration.ear" parent="CheckStatus" auto-start="true"/>
         <application name="wizmonitor" path="../applications/wizmonitor.ear" auto-start="true"/>
         <global-web-app-config path="global-web-application.xml"/>
         <web-site default="true" path="./default-web-site.xml"/>
         <cluster id="-485368505"/>
    </application-server>
    Tks
    Andre

  • Weblogic, eclipse plugin, ServletContextListener

    I'm new to weblogic and I'm testing some existing tomcat code that's showing some strange behavior inside of eclipse. When I right click in the servers window and debug a weblogic test project I see contextInitialized called twice. During the first call I see some of the api's fail whereas the second call seems to run ok. Is there any way to prevent the two calls? When I launch tomcat, contextInitialized is called once so I would like the same thing to happen inside of weblogic. I know I could go w/ the application life cycle listener but for now I would like to keep the code in the current form. Just to make it clear, this code is called twice:
    public class ContextLoaderListener implements ServletContextListener
    public void contextInitialized(ServletContextEvent contextEvent)
    // called twice, how to skip the first call?
    is there a way to check a property or make a call so that the code only runs twice.
    An example of where this causes problems is when I register a bean during startup:
    call 1: ( beanServer.addNotificationListener(...) )
    INFO: registerNotificationListenerInternal: watchRuntimeName = com.bea:ServerRuntime=AdminServer,Name=DiagnosticsJMXNotificationSource,Type=WLDFWatchJMXNotificationRuntime,WLDFWatchNotificationRuntime=WatchNotification,WLDFRuntime=WLDFRuntime>
    ####<Apr 18, 2012 1:47:05 PM CDT> <Notice> <StdErr> <BUSTX05NLKVB231> <AdminServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1334774825919> <BEA-000000> <Apr 18, 2012 1:47:05 PM com.verizon.vidaas.metrics.MetricsManager registerNotificationListenerInternal
    SEVERE: javax.management.InstanceNotFoundException: com.bea:ServerRuntime=AdminServer,Name=DiagnosticsJMXNotificationSource,Type=WLDFWatchJMXNotificationRuntime,WLDFWatchNotificationRuntime=WatchNotification,WLDFRuntime=WLDFRuntime
    call2: ( beanServer.addNotificationListener(...) )
    INFO: registerNotificationListenerInternal: watchRuntimeName = com.bea:ServerRuntime=AdminServer,Name=DiagnosticsJMXNotificationSource,Type=WLDFWatchJMXNotificationRuntime,WLDFWatchNotificationRuntime=WatchNotification,WLDFRuntime=WLDFRuntime>
    <no exception here>
    So, call2 works but for some strange reason call1 doesn't so if I could skip call1, then maybe that would fix the issue?
    One final note: this is not an issue when run outside of eclipse.
    thanks,
    Paul.

    Hi Paul --
    The ServletContextListener should be getting called once per ServletContext creation. That's the behaviour the Servlet specifications prescribes and we follow.
    I just did a quick test on WLS 12c and saw it getting called once per deployment/activation of the web module.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package sab.demo.otn2377518;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    * Web application lifecycle listener.
    * @author sbutton
    @WebListener()
    public class TestContextListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.printf("%s:%s\n",
                    this.getClass().getName(),
                    getMethodName());
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.printf("%s:%s\n",
                    this.getClass().getName(),
                    getMethodName());
        private String getMethodName() {
            return  Thread.currentThread().getStackTrace()[2].toString();
    }<Apr 23, 2012 5:48:38 PM CST> <Notice> <LoggingService> <BEA-320401> <The log file has been rotated to /Users/sbutton/Java/wls-1211update-dev/domain/servers/AdminServer/logs/access.log00163. Log messages will continue to be logged in /Users/sbutton/Java/wls-1211update-dev/domain/servers/AdminServer/logs/access.log.>
    <Apr 23, 2012 5:48:40 PM CST> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STANDBY.>
    <Apr 23, 2012 5:48:40 PM CST> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STARTING.>
    sab.demo.otn2377518.TestContextListener:sab.demo.otn2377518.TestContextListener.contextInitialized(TestContextListener.java:21)
    <Apr 23, 2012 5:48:51 PM CST> <Notice> <LoggingService> <BEA-320400> <The log file /Users/sbutton/Java/wls-1211update-dev/domain/servers
    <Apr 23, 2012 5:48:52 PM CST> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to RUNNING.>
    <Apr 23, 2012 5:48:52 PM CST> <Notice> <WebLogicServer> <BEA-000360> <The server started in RUNNING mode.>
    >
    If you are using OEPE, then I wonder if you have auto-publishing set to true so that any changes you make to the application in OEPE are resulting in automatic republishing of the application, which will restart the web
    module to pick up the change and thus call this listener method each time?
    -steve-

  • How to schedule events using ServletContextListener??

    Hello all
    I have a servlet which contains a hashtable. I need to update it every hour with some new entries. I have read some of the other threads which suggest one to implement a ServletContextListener, and when the servletcontext is created or destroyed, certain methods would be called. So can I have my servlet implement ServletContextListener and write methods to do the same? When is the servletcontext created or destroyed?? Can I do it every hourly??
    Please help me with suggestions and any example code would be great.
    thanks a lot
    Mahesh :)

    in servlet specification 2.3 I found
    Servlet Context Events
    Lifecycle: The servlet context has just been created and is available to service its first request, or the servlet context is about to be shut down
    An Example of Listener Use:
    To illustrate a use of the event scheme, consider a simple web application containing
    a number of servlets that make use of a database. The developer has provided a
    servlet context listener class for management of the database connection.
    1. When the application starts up, the listener class is notified. The application
    logs on to the database, and stores the connection in the servlet context.
    2. Servlets in the application access the connection as needed during activity in
    the web application.
    3. When the web server is shut down, or the application is removed from the web
    server, the listener class is notified and the database connection is closed.
    ServletContext created when application deployed or server started
    ServletContext destroyed when for example server was shut down

  • ServletContextListener  Error

    Hi Everybody
    i'm trying to create an application with servletcontext but i got the following error
    thanks for ur help in advance
    the error is
    Apr 10, 2008 3:19:41 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Skipped installing application listeners due to previous error(s)
    Apr 10, 2008 3:19:43 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Error configuring application listener of class Mylistener
    java.lang.ClassNotFoundException: Mylistener
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
         at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
         at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3773)
         at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
         at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
         at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
         at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
         at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
         at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
         at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
         at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
         at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
         at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
         at org.apache.catalina.core.StandardService.start(StandardService.java:516)
         at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
         at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
         at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    Apr 10, 2008 3:19:43 PM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Skipped installing application listeners due to previous error(s)
    and my code is
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.ServletContext.*;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import java.io.*;
    public final class MyListener implements ServletContextListener
         Connection con;
         public void contextInitialized(ServletContextEvent sce)
    try
              ServletContext ctx=sce.getServletContext();
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String dburl=ctx.getInitParameter("dburl");
              String uname=ctx.getInitParameter("uname");
              String pwd=ctx.getInitParameter("pwd");
              con=DriverManager.getConnection(dburl, uname, pwd);
              ctx.setAttribute("Connection",con);
              System.out.println("The Connection is Established");
    catch ( Exception e )
    e.printStackTrace();
         public void contextDestroyed(ServletContextEvent sce)
         try
              ServletContext ctx=sce.getServletContext();
              con=(Connection)ctx.getAttribute("Connection");
              con.close();
    catch ( Exception e )
    e.printStackTrace();
    }

    Hi,
    Java is case sensitive u have mentioned in web.xml listener class name as Mylistener, so server looking for Mylistener class. But ur class name is MyListener. Change spell in web.xml.
    Regards,
    Ram.

  • ServletContextListener   getRemoteUser()

    Hello all
    All I want to do is get the remote user name so that i can query the database and set user
    permissions. I am using tomcat with basic authentication. What can I do. I thought I would
    be able to set up my userInfo in my ContextListener object which make sense to me
    because I only need on instance of the class.

    A ServletContextListener is invoked only when the application starts or stops. At that time, there's no request to handle, and hence, no "remote user".
    The getRemoteUser() method is defined on the request object, so you need to call it in the context of a request instead, e.g., in a servlet filter or a JSF backing bean (through the ExternalContext object).

  • Using DBControl in ServletContextListener

    Is it possible to use a DBControl in a ServletContextListener ?
    Right now i'm using WLS8.15 and testing the DBControl with a stateless webservice works fine, but using it in the ServletContextListener fails with a NullPointerException.
    Can someone show me the right way ? :-)

    You cannot change the datasource property dynamically. It is a design time property. You could change the pool behind the DS via API, but that is not want. You may need to create 1 control per DS and then change call the methods on different db controls in your own control.
    -Kai

  • Datasource null within ServletContextListener

    I'm using Tomcat 5.0.18 with jdk 1.4.1_05. I have a class in my webapp which is a ServletContextListener. The aim is to put a Datasource object in the application scope when the context is started/ended.
    Now, a datapool is defined in the <DefaultContext> section of the server.xml file as normal.
    I have an application-specific context in the server.xml file also which defines if my app is reloadable and the path to my codebase.
    Now, before I used to hit a servlet specially to cache the datasource in the application scope each time. So using this method it should cache the datasource upon context initialization automatically.
    What i get is a null Datasource and says something like "jdbc is not defined in this context" - something on those lines. I'm baffled as everything is defined in <defaultcontext> and so lookups in java:comp/env/jdbc/blah should work.
    Do you think because I add an application-specific context in the server.xml it ignores the <defaultcontext> ? This is only a temporary entry because i don't like to put app specific lines in the server.xml. I like to have a "global" datasource defined as I have in <defaultcontext>
    Is this a bug with Tomcat ?

    ..and yes, I have defined the listener in the web.xml
    (i use http://forum.java.sun.com/thread.jsp?thread=494937&forum=33&message=2335813 as a reference) but I think it's not helpful to me - because from the init() section of say a SimpleServlet i can "get access" to the jdbc source thru jndi naming without problem. I just can't get it from within a ServletContextListener. What's different ??

  • HSQLDB and Tomcat ServletContextListener

    Dear All,
    I'm using HSQLDB as embedded in-process mode for my web application. I used
    to schedule every 1 minutes to check on the HSQLDB database. I open the db
    when context initialized and close it when context destroyed. But when the
    context reloaded I always get Java.lang.NullPointerException when trying to
    execute SQL statement.
    What is wrong ?? It looks like everytime the context is destroyed... the
    hsqldb gets lock.
    The snippet code like below :
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextListener;
    import javax.servlet.ServletContextEvent;
    import java.nio.channels.ClosedByInterruptException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.util.Random;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class ContextStartUp implements ServletContextListener {
         private ServletContext context = null;
         MyThread objThread = null;
         ResultSet rs = null;
         Connection conn = null;
         public void openDB()
             try {
                 conn = DriverManager.getConnection("jdbc:hsqldb:file:" +
    context.getRealPath("/data/testdb") + ";ifexists=true;shutdown=true;", "sa",
    "phidmspassword");
             } catch (SQLException e) {
                 e.printStackTrace();
             catch(Exception e)
                 e.printStackTrace();
         public void closeDB()
             Statement stmt = null;
             try {
                 if(conn!=null)
                     stmt = conn.createStatement();
                     stmt.execute("SHUTDOWN COMPACT");
                     stmt.close();
                     conn.close();
                     stmt = null;
                     conn = null;
             } catch (SQLException e) {
                 e.printStackTrace
         public class MyThread implements Runnable {
             int nomor = 0;
             Thread currentthread = null;
             public MyThread() {
                 if (currentthread == null) {
                     currentthread = new Thread(this);
                     currentthread.setPriority(new Random().nextInt(5) + 1);
                     currentthread.start();
             public void run() {
                 Statement stmt = null;
                 String sqltodo = "";
                 Thread myThread = Thread.currentThread();
                 while (myThread == currentthread) {
                     try {
                         stmt = conn.createStatement();
                         if (stmt.execute("A select statement...... "))
                             rs = stmt.getResultSet();
                             if (rs.next()) {
                            sqltodo = Update queries ......;
                             stmt.executeUpdate(sqltodo);
                             stmt.execute("SHUTDOWN");
                             stmt.close();
                         else
                             stmt.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     } catch (Exception e) {
                         e.printStackTrace();
                     } finally {
                         stmt = null;
                     try {
                         Thread.sleep(100000);
                     } catch (InterruptedException e) {
         public void initThread() {
             openDB();
             objThread = new MyThread();
         public void stopThread() {
             objThread = null;
             closeDB();
         public void contextDestroyed(ServletContextEvent event) {
             context = null;
             stopThread();
         public void contextInitialized(ServletContextEvent event) {
             try {
                 Class.forName("org.hsqldb.jdbcDriver").newInstance();
             } catch (InstantiationException e) {
                 e.printStackTrace();
             } catch (IllegalAccessException e) {
                 e.printStackTrace();
             } catch (ClassNotFoundException e) {
                 e.printStackTrace();
             context = event.getServletContext();
             initThread();
    Regards,
    Feris
    PT. Putera Handal Indotama
    JL. KH. Moh. Mansyur No. 11 Blok B.8-12
    Telp. +62-21-631 6688 (Hunting)
    Fax. +62-21-6330211
    Jakarta (10140) - INDONESIA

    Oh, that's probably because, as usual, you're just jumping straight in and writing some code around a new technology you don't understand, without bothering to even glance at any documentation, or thinking about what you're doing, then posting the resultant stack trace here saying ":-( broken magic :-(". It'd be nice if you thanked people for their help now and again, too

Maybe you are looking for