Search code examples
javaweb-applicationsservletsstartup

How to invoke a Servlet (doGet) in a web application on startup?


I need to invoke a Servlet on application startup since it contains some application initialization logic.

I know I can set load-on-startup configuration, but this will only invoke Servlet’s init method. I need to invoke a doGet method and pass some Url parameters to it. Servlet doGet method expects ServletRequest and ServletResponse objects.

Also, since this is clustered application, I need to know exactly what node I am accessing (since one option is just to open a socket and invoke a Servlet).

What is the best option to perform this?

EDIT: As a clarification, Servlet already exist and can not be modified. Until now, someone would manually invoke the Servlet from the browser. I need to automatize this.


Solution

  • The best option is to refactor whatever logic you have in the doGet method into a separate method that can be invoked both from init and doGet.

    If you really can't refactor the logic (which really is the only good option), you can use some mock library. Google says Spring's mock objects are popular.

    Having a usable implementation of HttpServletRequest and HttpServletResponse, make a servlet loaded with load-on-startup, and from its init method, locate the relevant servlet from the current ServletContext, and invoke doGet with the appropriate request and response objects. (Yes, it's a pretty bad kludge, but you'll have to do something like this.)

    Edit: If you don't want to hack the WAR file, maybe you should check if your servlet container has the possibility to run some kind of hooks after you re/deploy a web app.