Java Platform, Enterprise Edition/Java EE Tutorial/First Servlet

Here we are going to create and deploy a simple servlet for an Apache Tomcat Server. The servlet will produce and send an html (with String "Hello World") to the client browser.

Creating the Servlet

 * Create the source file HelloWorld.java. The content of the source file HelloWorld.java is given below.

Note that  is an instance of   with which we are writing the HTML.


 * Create the folder with the application name (for example, SampleApplication) inside the folder "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps".


 * Create another folder namely "WEB-INF" inside the folder "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\SampleApplication"


 * Create another folder namely "classes" inside the folder "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\SampleApplication\WEB-INF"


 * Compile the servlet source file HelloWorld.java which produces HelloWorld.class


 * Store the servlet(HelloWorld.class) in the folder "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\SampleApplication\WEB-INF\classes". For simplicity, before compiling the source file you may move the source file to the above folder and compile it from there. The important thing is that the servlet should be in the "classes" folder.

You have created your first Servlet!

Setting CLASSPATH

 * For the servlet to be located by the JVM we have to set the CLASSPATH to "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\SampleApplication\WEB-INF\classes" or any of the folder above it. For setting the CLASSPATH, right click on 'My Computer'>Properties>Advanced>Environment Variables>System Variables>CLASSPATH>Edit. Add the above mentioned folder address (alongwith a semicolon) to the Variable value.

Note that the CLASSPATH should be set as system variable as the Tomcat Apache Server will be running as the "system" user.

Deployment Descriptor
There must be a deployment descriptor, which is actually an xml file namely web.xml, corresponding to each application inside the "WEB-INF" folder. So now we will create the web.xml file for our "SampleApplication" in the folder "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\SampleApplication\WEB-INF". The content of the file is shown below:

As you can assume "servlet" tag maps the name of the servlet to the servlet class and "servlet-mapping" tag maps the URL to the servlet.

Go to the URL
Make sure that the apache server is running. In the address bar of your browser type "http://localhost:8080/SampleApplication/servlet/HelloWorld" and press "Enter".

You will see a page with "Hello World" written on it.