How to Initialize a Servlet
Servlets are the backbone of any Java web application. Even when developing strictly with JavaServer pages, behind the scenes each JSP is compiled into a servlet. Most often, however, a web application is developed using a combination of both servlets and JSPs. Though the majority of development work can ignore servlet initialization, sometimes it can be necessary to execute logic when the servlet is first loaded, such as connecting to a database or loading resources from a file.
Things You'll Need
- Java JDK (version 1.5 or higher)
- Java Integrated Development Environment such as Eclipse or NetBeans is strongly recommended (though not required)
- Java Servlet Container, such as Tomcat or JBoss
Instructions
-
-
1
Add initialization code to your servlet by overridding the init() method:
public class MyServlet extends HttpServlet {
@Override
public void init() {
System.out.println("MyServlet is Starting Up!");
}
}
-
2
Optionally, modify your web.xml file to indicate that the servlet should be initialized on startup. Otherwise, it'll be initialized the first time it's loaded through a request.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.examples.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-
-
3
Compile/build your project (if your development environment doesn't do so automatically) and redeploy your application to your application container. If you added the code from Step 2 into your web.xml file, you should notice your code will execute immediately when your container is finished deploying your site; otherwise, you'll need to add functionality to allow you to make a request from your site. When you execute the request, your servlet should initialize and execute the initialization code.
-
1
Tips & Warnings
The init method is an efficient place to load data that will be used throughout the life of your application, such as lookup tables and other data caches. Just ensure that the data loaded here isn't accessed by other areas of your code that may have executed first.