I have web application in Java code, which uses servlets
. My question is how to initialize some java class, which is not servlet
. I understand that if the client connects - the servlet
then prints the output. But only "if client connects".
Is it possible to run some threads before any connections are made?
EDIT:
Thanks to answers, right now I'm trying to do it this way:
the class:
package com.xsistema.filemanager.application;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
*
* @author Ernestas Gruodis
*/
public class ServerInit implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Initialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Destroyed");
}
}
And the glassfish-web.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
<context-root>/file-manager</context-root>
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class' java code.</description>
</property>
</jsp-config>
<listener>
<listener-class>
com.xsistema.filemanager.application.ServerInit
</listener-class>
</listener>
</glassfish-web-app>
And I getting this error while deploying the application:
Warning: Unsupported deployment descriptors element listener-class value com.xsistema.filemanager.application.ServerInit.
What's wrong here?
EDIT2:
Can not delete this question, appeared to be duplicate (it has the answers already). But I found the solution:
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.servlet.ServletContextEvent;
@Startup
@Singleton
public class Config {
@PostConstruct
public void init() {
// Do stuff during webapp's startup.
}
@PreDestroy
public void destroy() {
// Do stuff during webapp's shutdown.
}
}
Very nice and easy, and working :)