How to use the Servlet context Listener to start a Servlet so when the application is loaded?

Asked

Viewed 1,544 times

4

I have the following declared Servlet on web.xml and would like it to be initialized before any of the other application Serrvlets:

<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 you use 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’t instantiate within the method contextInitialized the Servlet ListarFilmesIndex that uses a DAO to upload all movies that are registered in the database.

When I try to instantiate the class ListarFilmesIndex I don’t know what to do with the request and the sponse which are required for Servlet, and then when I run the application a NullPointerException.

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

What should I do?

1 answer

3

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

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

However, a context Listener does not serve to instantiate Rvlets. It only allows you to perform some action exactly after the application starts and before you fulfill any request.

Anyway, to initialize values in Servlets, you do not need a Listener. Just overwrite the method init in your Rvlet. 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 nay You need to make sure that this Servlet is booted before the others. This is because no Servlet will run before full startup of the application, which includes initializing and calling the method init of all Rvlets tagged <load-on-startup>.

However, if the order really matters, just leave the other Rvlets without the boot tag or put higher values than 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.