11.4. Creating a Servlet

Problem

You want to use Eclipse to develop servlets.

Solution

Develop the servlet’s Java code using Eclipse, and add servlet.jar or servlet-api.jar (depending on your version of Tomcat) as external .jar files. After compiling the servlet, copy it over to your Tomcat installation.

Discussion

JSP files such as that developed in the previous recipe were introduced to make online Java programming easier. JSPs actually are compiled into servlet code, which is pure Java code, with no HTML mixed in. Developing servlets in Eclipse is like developing other Java code: Eclipse can detect problems even before you compile.

You can see the Java code for a servlet in Example 11-2. Servlet code such as this extends the HttpServlet class, and you have to include a .jar file in the build path to get that support. In Tomcat 4.x, that .jar file is servlet.jar; in Tomcat 5.x, it’s servlet-api.jar.

Example 11-2. A sample servlet

package org.cookbook.ch11; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletClass extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter( ); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Servlet Sample"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>"); out.println("Servlet Sample"); ...

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.