udakarajd
udakarajd

Reputation: 114

do some stuff before getting the request from a client, tomcat war

I am creating a Vaadin web application (Deployable war file) to be hosted by tomcat.

Is there a way to do something (let's say creating an object) at the deployment of war file, before initialization or before getting a request from a client?

Could it be done by overriding

void init()

method? I don't have a clear idea. I'm new to this.

Upvotes: 1

Views: 228

Answers (3)

Abbas
Abbas

Reputation: 3258

The above answers both work, but if you want another alternative, you can override the init method in your default Vaadin servlet.

public class MyServlet extends com.vaadin.server.VaadinServlet {
   @Override
    public void init(javax.servlet.ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        // do extra work here!
    }
}

Please note that you need to configure your web.xml or your annotated UI class to initialize your vaadin app with the new servet, e.g. change your `web.xml to

<servlet>
    <servlet-name>YourAppName</servlet-name>
    <servlet-class>path.to.MyServlet</servlet-class>
</servlet>

Upvotes: 2

Priyanshu
Priyanshu

Reputation: 128

When the server is started or more precisely when the servlet container starts up, it deploys all the web applications, loads them and then it creates an application context for each application and store in its memory. I mentioned the above things so that you can have a better understanding of the solution to your question.

Now coming to your question, what you can do is create a class and name it anything and then implement ServletContextListener interface. It has basically two methods with the following signature.

  • public void contextInitialized(ServletContextEvent event)
  • public void contextDestroyed(ServletContextEvent event)

Now in the contextInitialized method, you can do whatever you want, like creating an object or something because this is the method which is invoked when your ServletContext is initialized.

In your web.xml place the mapping as follows

<listener>
   <listener-class>
       your fully qualified class name that which will implement the ServletContextListener
     </listener-class>   
</listener>

I hope it answers your question. Happy to help.

Upvotes: 3

chenchuk
chenchuk

Reputation: 5742

You can add another class to be loaded automatically by specifying in web.xml load-on-startup=1 :

example :

<web-app>
   <servlet>
      <servlet-name>MyLoader</servlet-name>
      <servlet-class>com.xxx.MyLoader</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>MyLoader</servlet-name>
      <url-pattern>/load</url-pattern>
   </servlet-mapping>
</web-app>

Upvotes: 2

Related Questions