First, let me explain what servlets really are. Most people associate servlets with Web servers; in fact, Sun's own definition of a servlet is a way of "extending the functionality of Web Servers." While this is true, it is also a little misleading and puts servlets in a smaller box than I like, but more on that later. So for my definition of a servlet, I'm going to go with this: "A servlet is the implementation of a specific Java interface called GenericServlet that has an associated input (or request) object and an output (or response) object." GenericServlet is part of the javax.servlet package that is part of Sun's Java 2 Enterprise Edition (J2EE), but it can also be used as an extension to Sun's Java 2 Standard Edition (J2SE) without having all the other extensions--such as Enterprise Java Beans (EJBs)--that come along with the full-blown J2EE package. Or more simply put, a servlet is something you make a request of and then receive a response from. Since the javax.servlet package already has a concrete implementation of the GenericServlet interface for handling HTTP requests, I will use it for my example, but keep in mind that this is only one of any number of possible concrete implementations of GenericServlet. It just happens to be the easiest and most compelling one to provide examples for.
HttpServlets allow you to make HTTP requests--such as GETs and POSTs--that return dynamic, Java-generated HTML responses. In other words, HttpServlets allow you to embed HTML in Java source code. HttpServlets, like all servlets that implement GenericServlet, live in Web containers that are simply the wrapper around the servlet that allows them to accept requests from and send responses to a Web server. Any J2EE-compliant application server functions as a Web container for servlets, but for the purposes of this discussion, I will look at another implementation of servlet Web containers called Tomcat. Tomcat is one of several projects hosted by Jakarta at Apache. Tomcat provides Web containers for both servlets and JavaServer Pages (JSPs). Although it is part of the Sun J2EE reference implementation, it does not provide containers for EJBs and thus is not a J2EE platform on its own. I chose Tomcat for my examples because it is very stable and mature as well as seamlessly integrated with Apache's Web server, but the best reason of all is that it's free.
What You Will Need
To try the example I'm going to present here, you will need two pieces of software: Tomcat and a current Java Developer Kit (JDK) from Sun. Any version 1.2 or higher of the JDK should work, although I used 1.4 when developing my example. You can get the JDK 1.4 here. Just accept all the defaults on the installers. You can get a copy of Apache's servlet/JSP container called Tomcat 4.0.4 from here. Install it and accept all the defaults. The Tomcat installer will put convenience shortcuts on your Start menu under Apache Tomcat for starting and stopping the server. Start the Tomcat server, which by default will be listening on port 8080. You can test that Tomcat is installed correctly by pointing your Web browser to http://localhost:8080/, which should take you to a page congratulating you on your successful installation of Tomcat. There are some example servlets that you can link to off of this page, but I always find I learn the most by creating one of my own.
Before you can write your servlet, you need to set up a new CLASSPATH entry and let Tomcat know where you are going to store your servlet. For this example, you will need several classes from the servlet.jar library that is included as part of Tomcat. If you accepted all the defaults on your Tomcat installation, you will add C:Program FilesApache Tomcat 4.0commonlibservlet.jar to your CLASSPATH. Next, set up a home for your servlet in the Tomcat tree by adding a folder called servletExample under Apache Tomcat 4.0webapps. Then, create a folder called WEB-INF and put it inside your new servletExample folder. Now, make one last folder called classes and put it in WEB-INF. This will be the folder in which you store the .class file for your servlet. Just one last step: You need to let Tomcat know where to look for your servlet when it gets a request. So look for the server.xml file in Apache Tomcat 4.0conf and add the following entry somewhere near the other context declarations:
docBase="C:Program FilesApache Tomcat 4.0webappsservletExample">
The Good Stuff
Take a look at the code. It begins with the obligatory set of imports. Note that I did not use .* imports--this way, you can tell which package each class is in. The java.io classes are part of J2SE, but all the javax.servlet classes are from Tomcat. Next, I declared the new servlet class, which extends HttpServlet, and overrode the doGet() method that it inherits. For this example, I ignored the request object that is passed in and provisioned the response class with a contentType and an outputStream with some simplistic HTML. That's all there is to it; Tomcat handles all the details.
Now, compile the example and move the resulting ServletJJ.class file to the servletExample WEB-INFclasses directory that you created earlier. If Tomcat is currently running, stop it and restart it using the shortcuts on the Start menu. Then, start up your Web browser and enter http://localhost:8080/test/servlet/ServletJJ. You should get back a Web page containing the message from the source code. Note that this URL may not look very intuitive. The localhost:8080 is of course port 8080 on your local machine. The /test directory is from the server.xml docBase that you set earlier. The /servlet was preconfigured in Tomcat's default .xml to point to the WEB-INF/classes directory under a doc base. As a general rule, servlet containers such as Tomcat hide what is in their WEB-INF directories from direct access. So if you were to try to go to http://localhost:8080/test/WEB-INF/classes/ServletJJ, you would get a 404 error. This feature helps keep your servlets secure.
This example shows the entry point for http GETs. There is also a corollary entry point for POSTs called doPost(), which takes the same arguments as the doGet(). So next, try implementing something dynamic--like returning a timestamp--or go all out and connect to your favorite database and grab some data. Just send all your output to the PrintWriter, and it will show up on the Web page.
So Why Use Servlets?
Servlets are generally used as a replacement for traditional CGI programming. Although servlets have a number of advantages over CGIs, the most important to me are that they are easy to extend, secure, easy to debug, and portable. Servlets are easy to extend because they have the power of all the Java APIs behind them. So whether you need to retrieve data from the database, use a library of HTML tags or send email, chances are that there is already a Java API written and waiting for you. Since servlets execute within a Web container such as Tomcat, which restricts direct access to your servlets .class files, your first line of security is already provided for you. Many IDEs have built-in debuggers that allow you to step right into your servlet code, something I've never been able to do when trying to debug a CGI. The final advantage, which is more or less synonymous with Java, is portability. This is especially important when developing servlets because you can develop and test your servlet on your laptop and not have to worry about whether it will run differently on your production enterprise servers.
So Why Not Use Servlets?
Although servlets do provide a lot of great features, most people use HttpServlets to provide dynamic Web pages by embedding HTML in their Java code, as in the example. For small projects and prototyping, servlets are great, but because the Web pages are rendered at runtime, you cannot leverage high-end HTML editors and you often wind up with HTML in many places in your code where it doesn't belong. Also, making style changes to your site can be painful because the HTML may be spread over any number of source files. So Sun came up with two competing technologies: JavaServer Pages (JSPs) and Java Web Services. By invoking Java methods from within HTML, JSPs allow us to reverse the embedding so that we can take full advantage of Web authoring tools. Java Web Services are the future of servlets; they allow servlets to work together as an integrated, yet loosely coupled, system. I will take a look at both JSPs and Java Web Services in upcoming Java Journals.
Servlets are the easiest way to get yourself some experience doing Web programming, and you don't need a full-blown, expensive J2EE application server to get started. Tomcat is a good tool to practice writing servlets with and is easy to configure. Although servlets may not be the best solution for generating dynamic Web pages, they are a fundamental piece of Java Web Services and a good place to start getting your feet wet.