[RESOLVIDO][Tomcat] Servlet executar sempre

7 respostas
J

Olá amigos,

alguêm já passou por isso?, preciso executar algumas linhas no banco via JDBC toda vez que o Tomcat for startado/reiniciado.

Ou seja… preciso chamar um determinado Servlet pelo tomcat.

Grato por qualquer ajuda.

7 Respostas

M

Opa!
Acho que você pode fazer um listener dessa forma:

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

public class ClasseListener implements ServletContextListener
{
	public void contextInitialized(ServletContextEvent event) {
//insira o código aqui
	}
}
Para executar o listener na inicialização do TomCat, é só adicionar as seguintes linhas no web.xml:
<listener>
		<listener-class>
			<!-- o nome da sua classe aqui, tipo br.com.SuaClasse -->
		</listener-class>
	</listener>

Flw!!!

fmeyer

é porco, mas vc pode por na funcao init do servlet uma chamada para essa sua funcao e declarar o servlet pra iniciar quando o servidor iniciar…

&lt;servlet&gt;
		&lt;description&gt;&lt;/description&gt;
		&lt;servlet-name&gt;AutenticationServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;com.fmeyer.business.AutenticationServlet&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
public class AutenticationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private static final long serialVersionUID = 3988194379125537822L;

           // Caching the DataSource - It is obtained in the Servlet.init() method
            private javax.sql.DataSource ds = null;

            // This Happens Once and is Reused
            public void init(ServletConfig config) throws ServletException
            {
                       super.init(config);
                       Context ctx = null;
                       try
                       {
                                 java.util.Hashtable env = new java.util.Hashtable();
                                 env.put(Contex.INITIAL_CONTEXT_FACTORY,
                                  "com.ibm.ejs.ns.jndi.CNInitialContextFactory");

                                 ctx = new InitialContext(env);
                                 ds = (javax.sql.DataSource)ctx.lookup("jdbc/SAMPLE");
                                 ctx.close();
                       }
                       catch(Exception es)
                       {
                                es.printStackTrace();
                       }
            }
J

fmeyer,

Nunca mexi com esse objeto "Context" vc poderia me explicar melhor as linhas referente a esse objeto, pelo que vi seria uma melhor forma de implementar tal necessidade minha.

Abraço e obrigado a todos ate o momento

fmeyer:
é porco, mas vc pode por na funcao init do servlet uma chamada para essa sua funcao e declarar o servlet pra iniciar quando o servidor iniciar...
&lt;servlet&gt;
		&lt;description&gt;&lt;/description&gt;
		&lt;servlet-name&gt;AutenticationServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;com.fmeyer.business.AutenticationServlet&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
public class AutenticationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private static final long serialVersionUID = 3988194379125537822L;

           // Caching the DataSource - It is obtained in the Servlet.init() method
            private javax.sql.DataSource ds = null;

            // This Happens Once and is Reused
            public void init(ServletConfig config) throws ServletException
            {
                       super.init(config);
                       Context ctx = null;
                       try
                       {
                                 java.util.Hashtable env = new java.util.Hashtable();
                                 env.put(Contex.INITIAL_CONTEXT_FACTORY,
                                  "com.ibm.ejs.ns.jndi.CNInitialContextFactory");

                                 ctx = new InitialContext(env);
                                 ds = (javax.sql.DataSource)ctx.lookup("jdbc/SAMPLE");
                                 ctx.close();
                       }
                       catch(Exception es)
                       {
                                es.printStackTrace();
                       }
            }
fmeyer

Ignora oq ta dentro do metodo init() e coloca o que voce precisar la … ali é apenas um exemplo de conexao com DataSource e JNDI …

J

fmeyer:
Ignora oq ta dentro do metodo init() e coloca o que voce precisar la … ali é apenas um exemplo de conexao com DataSource e JNDI …

Eae velhão to fazendo oque vc pediu mais ele não da sinal de vida… o máximo que ele xiou quando tinha saido do padrão da DTD. de resto ele não me da uma Exception e nao consigo printar nada no console. Segue:

&lt;servlet&gt;
 		&lt;servlet-name&gt;LimpaTabelasTemporarias&lt;/servlet-name&gt;
 		&lt;servlet-class&gt;xxxxx.service.LimpaTabelasTemporarias&lt;/servlet-class&gt;
 		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
 	&lt;/servlet&gt;
package xxxxx.service;

public class AutenticationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

             public void init(javax.servlet.ServletConfig config) throws javax.servlet.ServletException
             {
                        super.init(config);
                        
                        try{
                          System.out.println("@@@@@@@@@@@@@@@@@@@@@@@");
                        }
                        catch(Exception es)
                        {
                                 es.printStackTrace();
                        }
             }
}

oque pode ser amigon???

J

fmeyer resolvido!

fmeyer:
é porco, mas vc pode por na funcao init do servlet uma chamada para essa sua funcao e declarar o servlet pra iniciar quando o servidor iniciar...
&lt;servlet&gt;
		&lt;description&gt;&lt;/description&gt;
		&lt;servlet-name&gt;AutenticationServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;com.fmeyer.business.AutenticationServlet&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
public class AutenticationServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private static final long serialVersionUID = 3988194379125537822L;

           // Caching the DataSource - It is obtained in the Servlet.init() method
            private javax.sql.DataSource ds = null;

            // This Happens Once and is Reused
            public void init(ServletConfig config) throws ServletException
            {
                       super.init(config);
                       Context ctx = null;
                       try
                       {
                                 java.util.Hashtable env = new java.util.Hashtable();
                                 env.put(Contex.INITIAL_CONTEXT_FACTORY,
                                  "com.ibm.ejs.ns.jndi.CNInitialContextFactory");

                                 ctx = new InitialContext(env);
                                 ds = (javax.sql.DataSource)ctx.lookup("jdbc/SAMPLE");
                                 ctx.close();
                       }
                       catch(Exception es)
                       {
                                es.printStackTrace();
                       }
            }
J

Obrigado maddonde funcionou sua solução... obrigado

maddonde:
Opa! Acho que você pode fazer um listener dessa forma:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ClasseListener implements ServletContextListener
{
	public void contextInitialized(ServletContextEvent event) {
//insira o código aqui
	}
}
Para executar o listener na inicialização do TomCat, é só adicionar as seguintes linhas no web.xml:
<listener>
		<listener-class>
			<!-- o nome da sua classe aqui, tipo br.com.SuaClasse -->
		</listener-class>
	</listener>

Flw!!!

Criado 16 de agosto de 2006
Ultima resposta 16 de ago. de 2006
Respostas 7
Participantes 3