I have this code,
@WebServlet(value=\"/initializeResources\", loadOnStartup=1)
public class InitializeResources extends HttpServlet {
@Override
protecte
@WebServlet(name="InitializeResources", urlPatterns="/initializeResources", loadOnStartup=1)
urlPatterns to be ensure that the web conatainer finds the servlet path.
With you current code, you need to do a GET request for see the output HEREEEE
.
If you want to do something on the startup of the servlet (i.e. the element loadOnStartup with value greater or equal to zero, 0
), you need put the code in a init method or in the constructor of the servlet:
@Override
public void init() throws ServletException {
System.out.println("HEREEEE");
}
It may be more convenient to use a listener to start a resource in the application scope (in the ServletContext
).
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class InitializeListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("On start web app");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("On shutdown web app");
}
}
For an example, see my answer for the question Share variables between JAX-RS requests.
When loadOnStartup
is specified for a Servlet, the container would only load and pre-instantiate an instance of your Servlet ready to process any GET/POST requests that may come. This by itself wouldn't cause doGet()
or doPost()
to get fired because an actual client request hasn't come for processing yet. So, what's its use then?
Well, loadOnStartup
is typically used for Servlets that have heavy initialization code; say, they may make a JNDI call to get hold of a resource or a Database call to populate a local data structure with some backend values. In the absence of loadOnStartup
the very first client request could be painfully slow because of all this extra initialization stuff and hence pre-instantiating it makes sense.
Now, your custom initialization code (JNDI, JDBC) would go in an overriden GenericServlet#init()
method which is called by the servlet container to indicate to a servlet that it's being placed into service.