Step 4: Add a Servlet Class
In this step we will add a servlet to manage guestbook web requests:
- Open the [Create Servlet] dialog box by right clicking the guest package node (in the [Package Explorer] window), selecting New > Other... > Web > Servlet and clicking Next.
- The Java package name should be guest.
- Enter GuestServlet as the class name - use exactly that case sensitive class name.
- 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 javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name="GuestServlet", urlPatterns={"/guest"}) public class GuestServlet extends HttpServlet { private static final long serialVersionUID = 1L; // Injected DAO EJB: @EJB GuestDao guestDao; @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Display the list of guests: request.setAttribute("guests", guestDao.getAllGuests()); request.getRequestDispatcher("/guest.jsp").forward(request, response); } @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle a new guest: String name = request.getParameter("name"); if (name != null) guestDao.persist(new Guest(name)); // Display the list of guests: doGet(request, response); } }
GuestServlet
performs the following operations on every http request:
- If a new guest has registered (using a JSP form that will be added 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.
Notice that operations on the database are carried on by the GuestDao
session bean, which is instantiated and injected by the application server into the guestDao
field automatically (since the field is marked with the @EJB
annotation).
The next step is adding a JSP page that will serve as the application view and will produce the guestbook output.