646 words

Step 4: Add a Servlet Class

In this step we will add a servlet to manage guestbook web requests:

  • Open the [New Servlet] dialog box by right clicking the guest package node
    (in the [Projects] window) and selecting New > Servlet...
  • Enter GuestServlet as the class name - use exactly that case sensitive class name.
  • The Java package name should be guest.
  • Click Finish to create the new servlet class.

Now replace the content of the new source file with the following code:

package guest;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.persistence.*;
public class GuestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(
        HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Obtain a database connection:
        EntityManagerFactory emf =
        EntityManager em = emf.createEntityManager();
        try {
            // Handle a new guest (if any):
            String name = request.getParameter("name");
            if (name != null) {
                em.persist(new Guest(name));
            // Display the list of guests:
            List<Guest> guestList = em.createQuery(
                "SELECT g FROM Guest g", Guest.class).getResultList();
            request.setAttribute("guests", guestList);
                .forward(request, response);
        } finally {
            // Close the database connection:
            if (em.getTransaction().isActive())
    protected void doPost(
        HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);

GuestServlet performs the following operations on every http request:

  • The EntityManagerFactory is retrieved from the application scope attribute, and then an EntityManager (representing a database connection) is constructed.
  • If a new guest has registered (using a JSP form that is shown in the next tutorial step) - a new Guest entity object is constructed and stored in the database.
  • All the Guest entity objects are retrieved from the database and stored in the request's "guest" attribute. Then the processing is forwarded to the JSP page (which is presented in the next tutorial step). The JSP uses the "guest" attribute to generate the page output.
  • Finally, the database connection (including the transaction if still active) is closed.

The next step is adding a JSP page that will produce the guestbook page output.