Back to main index

Servlet Examples with Code

This is a collection of examples which demonstrate some of the more frequently used parts of the Servlet API. Familiarity with the Java(tm) Programming Language is assumed.

These examples will only work when viewed via an http URL. They will not work if you are viewing these pages via a "file://..." URL. Please refer to the README file provide with this Tomcat release regarding how to configure and start the provided web server.

Wherever you see a form, enter some data and see how the servlet reacts. When playing with the Cookie and Session Examples, jump back to the Headers Example to see exactly what your browser is sending the server.

To navigate your way through the examples, the following icons will help:
 
Execute the example
Look at the source code for the example
Return to this screen

Tip: To see the cookie interactions with your browser, try turning on the "notify when setting a cookie" option in your browser preferences. This will let you see when a session is created and give some feedback when looking at the cookie demo.
 
Hello World Execute Source
Request Info Execute Source
Request Headers Execute Source
Request Parameters Execute Source
Cookies Execute Source
Naming Execute Source
Sessions Execute Source
MySQL Query Execute Source
File Upload Execute Source

Note: The source code for these examples does not contain all of the source code that is actually in the example, only the important sections of code. Code not important to understand the example has been removed for clarity.


Building your own servlets

There are some advatages of using Servlets over JSP. Tomcat is restarted every morning at 4AM EST or every 4 hours if there has been a configuration change. After a restart, JSP pages may require a recompile which can take several seconds depending on the size of the jsp page. With Servlets, there is no recompile time because the java code has already been compiled.

Using our MysqlExample for an example, you would recompile this using the command:
From your home directory (/pub/users/xxxx/www) :

cd java-server/WEB-INF/classes
javac -classpath /usr/local/etc/tomcat/common/lib/servlet.jar MysqlExample.java
This will produce a file named MysqlExample.class.

From the web, you can then access this using the url:

http://www.yourdomain.com/java-server/servlet/MysqlExample
The /servlet in the URL uses Tomcat's built-in Invoker servlet to launch the class file from the WEB-INF/classes/ directory.