Overview
In this article we will learn about Java Servlets. We will develop and deploy a simple Java Servlet in the Tomcat Servlet Container. We will also learn about the web.xml (Web Deployment Descriptor) file. After reading this article you'll be able to develop and deploy Java Servlets.
I'll assume here that you know a bit of Java and can understand it's syntax.
What are Java Servlets?
Servlets are snippets of Java programs which run inside a Servlet Container. A Servlet Container is much like a Web Server which handles user requests and generates responses. Servlet Container is different from a Web Server because it can not only serve requests for static content like HTML page, GIF images, etc., it can also contain Java Servlets and JSP pages to generate dynamic response. Servlet Container is responsible for loading and maintaining the lifecycle of the a Java Servlet. Servlet Container can be used standalone or more often used in conjunction
with a Web server. Example of a Servlet Container is Tomcat and that of Web Server is Apache.
Servlets are actually simple Java classes which must implement the javax.servlet.Servlet interface. This interface contains a total of five methods. Most of the time you don't need to implement this interface. Why? Because javax.servlet package already provides two classes which implement this interface i.e. GenericServlet and HttpServlet. So all you need to do is to extend one of these classes and override the method(s) you need for your Servlet. GenericServlet is a very simple class which only implements the javax.servlet.Servlet interface and provides only basic functionality. On the other hand, HttpServlet is a more useful class which provides methods to work with the HTTP protocol. So if your Servlet works with HTTP protocol (in most cases this will be the case) then you should extend javax.servlet.http.HttpServlet class to build Servlets and this is what we are going to do in this article.
Servlets once initialized are kept in memory. So every request which the Servlet Container receives, is delegated to the in-memory Java Servlet which then generates the response. This 'kept in memory' feature makes Java Servlets, a fast and efficient method of building Web Applications.
We will be using Tomcat 6.0.14 for this tutorial. Tomcat 6.0 supports latest Servlet specification 2.5. The installation, configuration and deployment of Tomcat 6.0 has alread been discussed in detail in this tutorial: Installing Tomcat 6.0 on Windows, and Developing & Running your first JSP page. Before moving any further, make sure that you have a working copy of Tomcat 6.0 running on your computer, and that you were able to develop and run your first JSP page.
Following is a list of topics we'll cover in this article :
Your first Java Servlet
Create a new text file and save it as 'TestServlet.java' in the "C:\apache-tomcat-6.0.14\webapps\star\WEB-INF\classes\com\stardeveloper\servlets" folder. "C:\apache-tomcat-6.0.14\webapps" is the folder where web applications (not individual files) that we create should be kept, in order for Tomcat to find them. "\star" is the name of our sample web application that we created it in an earlier tutorial (Installing Tomcat 6.0 on Windows, and Developing & Running your first JSP page). "\WEB-INF\classes" is the folder to keep Servlet class files. "\com\stardeveloper\servlets' is the package path to the Servlet class that we will create.
Now, copy and paste the following text into the 'TestServlet.java' file we created earlier:
package com.stardeveloper.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
/* Display some response to the user */
out.println("<html><head>");
out.println("<title>TestServlet</title>");
out.println("\t<style>body { font-family: 'Lucida Grande', " +
"'Lucida Sans Unicode';font-size: 13px; }</style>");
out.println("</head>");
out.println("<body>");
out.println("<p>Current Date/Time: " +
new Date().toString() + "</p>");
out.println("</body></html>");
out.close();
}
}
Explanation
Our TestServlet is extremely simple. It displays the current date and time on the server to the user.
We overrode just one method of HttpServlet class. doGet() is called when a HTTP GET request is received by the Servlet Container. In this method we set the content type of our response to 'text/html' (informing the client browser that it is an HTML document). Then we get hold of PrintWriter object and using its println() method, we send our own HTML content to the client browser. Once we are finished, we call its close() method.