Java code to be invoked when the server starts up

If you want to some java program to start by itself even you could not put in any type of start program or could not any utility. There is a smart way if you have one web server.

Creating a dynamic web project. Create a servlet out of your java program by extending it with HttpServlet.

On web.xml mention all servlet configuration like its name name, url pattern inside servlet mapping.

<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/ServletTest</url-pattern>
</servlet-mapping>
we need to tell Servlet container to load your Servlet at startup.There are several ways to do this.  For Tomcat, set the load-on-startup element to 1 in the web.xml file.Every HttpServlet class needs to have an init() method. Normally it return nothing & takes no argument but it give you facility to put some code in init() method which will called when any HttpServlet is loaded.


<display-name>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>
<display-name>ServletTest</display-name>
<servlet-name>ServletTest</servlet-name>
<servlet-class>com.test.javaclass.HelloWorld</servlet-class>
<init-param>
<param-name>sleep-time-in-seconds</param-name>
<param-value>10</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/Servlettest</url-pattern>
</servlet-mapping>

</web-app>

package com.test;
import javax.servlet.http.HttpServlet;
public class HelloWorld extends HttpServlet{
/**
* @param args
* @throws InterruptedException 
*/

public void init(){
System.out.println("I am inside init & invoked as soon as servlet loaded!");

}









Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java