How to use the servlet context listener to start a servlet as soon as the application loads?

3

I have the following servlet declared in web.xml and would like it to be initialized before any of the other servlets of the application:

<servlet>
    <servlet-name>ListarFilmesIndex</servlet-name>
    <servlet-class>br.com.corporacao.servlets.ListarFilmesIndex</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>ListarFilmesIndex</servlet-name>
    <url-pattern>/ListarFilmesIndex</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>
        br.com.corporacao.servlets.InicializacaoServletContextListener
    </listener-class>
</listener>

I tried to implement the class that uses ServletContextListener :

package br.com.corporacao.servlets;

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

public class InicializacaoServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent e) {

    }

    public void contextDestroyed(ServletContextEvent e) {

    } 
}

But I can not instantiate within the contextInitialized method the servlet ListarFilmesIndex that uses a DAO to load all the movies that are registered in the database.

When I try to instantiate the class ListarFilmesIndex I do not know what to do with the request and the response that are required for the servlet, and then when I run the application it is NullPointerException is released.

I have tried everything and searched but found nothing, just examples of filters and classes that are not servlets.

What should I do?

    
asked by anonymous 02.11.2015 / 10:41

1 answer

3

I think you're very close to the solution, but going the wrong way.

First, you were right to use the <load-on-startup> tag. This causes the Servlet to be initialized during application startup.

However, a context listener is not meant to instantiate servlets. It only allows you to perform some action right after the application starts and before you answer any request.

Anyway, to initialize values in servlets, you do not need a listener . Just override method init in the your servlet. Example :

public class CatalogServlet extends HttpServlet {
    private BookDBAO bookDB;
    public void init() throws ServletException {
        bookDB = (BookDBAO)getServletContext().
            getAttribute("bookDB");
        if (bookDB == null) throw new
            UnavailableException("Couldn’t get database.");
    }
}

Another detail is that you do need not ensure that this servlet is booted before others. This is because no servlet will execute before the application is fully initialized, which includes initializing and calling the init method of all servlets with the <load-on-startup> tag.

However, if the order really matters, just leave the other servlets without the initialization tag or put values greater than 1 .

    
03.11.2015 / 02:05