For the most part, building a servlet on Eclipse is done the same way as you would build any other Java class. Simply create a project for your class then add a class to your project. Place the servlet code into your class. As an example, add a class to your project called FirstServlet. Then copy the following code into your class.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">n";
out.println(docType +
"< HTML>n" +
"< HEAD>< TITLE>Hello Servlet< /TITLE>< /HEAD>n" +
"< BODY BGCOLOR="#FDF5E6">n" +
"< H1>Hello from your first servlet!< /H1>n" +
"< /BODY>< /HTML>n");
}
} //end class
In order to build your servlet, you need to import a special Java library file which contains all the class definitions which support the servlet API. This library is part of the Java Enterprise Edition, and is not included with the Java Standard Edition. However, Apache Tomcat does include the needed Java library file. To add the servlet-api.jar file to your project, start by right clicking on your project and selecting Properties from the pop-up menu. You should see a display as shown below. See image.
Select the Java Build Path on the left side of the display, and then select the Libraries tab. Click on the Add External JARs button. The following display should appear. Navigate to the following directory:
C:Program FilesApache Software FoundationTomcat 5.5commonlib
Then select the servlet-api.jar file and click the Open button in the Jar Selection display. Finally, click the OK button in the Properties display shown above. Your project is now ready to successfully build your servlet project.