be run simultaneously through several threads (there is no need for having a separate instance
of a servlet object for each request; only a thread is directly associated with a request).
A servlet is only removed from memory if it has not been requested over a longer period of time.
Prior to removal, the servlet's destroy() method is called to allow for clean up activities.
3.1.3 An Example Servlet
Java servlets always look very similar. A servlet class usually contains just a few methods, the
init(), a service(), and the destroy() method. If specific initialization or clean up activities are not
required, the init() and destroy() methods may even be omitted. An example for a simple, but
typical servlet class is shown below. This servlet reads a few parameters from the client
request, performs a task, and generates the HTML output.
package Rectangle;
// import the servlet packages
import javax.servlet.*;
import javax.servlet.http.*;
// import some other packages
import java.io.*;
import java.util.Arrays;
public class DrawRectangle extends HttpServlet {
// doGet method is an HTTP specific service() method
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// read two parameters from the request object
int width, height;
try {
width = Integer.parseInt(req.getParameter("width"));
height = Integer.parseInt(req.getParameter("height"));
}
catch (NumberFormatException e) { width = 10; height = 10; }
// perform action: generate a page & a rectangle with * characters
char line[] = new char[width];
Arrays.fill(line,'*');
StringBuffer str = new StringBuffer();
str.append("");
str.append("Rectangle Test");
str.append("");
for (int i=0; i
27