Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a web application in Apache Tomcat?

I was using WebSphere Application Server, and it gives a platform initialization listener which is invoked when an app gets started. Now, I am using Apache Tomcat, but have not found such stuff, and what I'm trying to do is do some initialization work before the application begins to serve requests.

How should I do it by Apache Tomcat?

like image 771
Bomin Avatar asked Jul 27 '26 12:07

Bomin


1 Answers

You create a Listener class what implement ServletContextListener like this:

package com.vy;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class StartStopListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet has been started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet has been stopped.");
    }

}

Add configuration information to WEB-INF\web.xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <listener>
        <listener-class>com.vy.StartStopListener</listener-class>
    </listener>

</web-app>

When run Tomcat, You will see result at console screen:

Servlet has been started.

Reference: http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContextListener.html

like image 88
Do Nhu Vy Avatar answered Jul 30 '26 01:07

Do Nhu Vy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!