16.3. The Servlets

Servlets are modules of Java code that run in an application server for answering client requests. Servlets are not tied to a specific client-server protocol. However, they are most commonly used with HTTP, and the word "servlet" is often used as referring to an "HTTP servlet."

Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic servlet framework) and javax.servlet.http (extensions of the servlet framework for servlets that answer HTTP requests).

Typical uses for HTTP servlets include:

For more details refer to the Java Servlet Technology pages (http://java.sun.com/products/servlet/).

16.3.1. Example

The following example is a sample of a servlet that lists the content of a cart. This example is the servlet version of the previous JSP page example.

import java.util.Enumeration;
import java.util.Vector;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class GetCartServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
                         throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        out.println("<html><head><title>Your 
            cart</title></head>");
        out.println("<body>");
        out.println("<h1>Content of your cart</h1><br>");
        out.println("<table>");

        // The header of the table
        out.println("<tr>");
        out.println("<td><font 
            color="lightgreen">Product Reference</font></td>");
        out.println("<td><font 
            color="lightgreen">Product Name</font></td>");
        out.println("<td><font 
            color="lightgreen">Product Price</font></td>");
        out.println("</tr>");

        // Each iteration of the loop display a line of the table
        HttpSession session = req.getSession(true);
        Cart cart = (Cart) session.getAttribute("cart");
        Vector products = cart.getProducts();
        Enumeration enum = products.elements();
        while (enum.hasMoreElements()) {
            Product prod = (Product) enum.nextElement();
            int prodId = prod.getReference();
            String prodName = prod.getName();
            float prodPrice = prod.getPrice();
            out.println("<tr>");
            out.println("<td>" + prodId + </td>);
            out.println("<td>" + prodName + </td>);
            out.println("<td>" + prodPrice + </td>);
            out.println("</tr>");
            }

            out.println("</table>");
            out.println("</body>");
            out.println("</html>");
            out.close();
        }
}