Java Web Programming with Eclipse contents
Last modified February 05, 2011 10:55 pm

back next

Item Management (continued)

List Page



In this section, we will implement the servlet and jsp to return the page that lists the news items in the system.

Modify the Deployment Descriptor

Modify the deployment descriptor, so that it uses the ListNewsItemsServlet to service requests that match the pattern /list-news-items. The following listing shows the servlet elements for the list-news-items servlet.


Create ListNewsItemsServlet

Create ListNewsItemsServlet in the publisher.web package with the implementation shown in the following listing.

package publisher.web;

import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


public class ListNewsItemsServlet extends HttpServlet
   private Logger logger = Logger.getLogger(this.getClass());
   private RequestDispatcher jsp;

   public void init(ServletConfig config) throws ServletException {
      ServletContext context = config.getServletContext();
      jsp = context.getRequestDispatcher("/WEB-INF/jsp/list-news-items.jsp");
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException
      List<NewsItem> newsItems = new NewsItemDAO().findAll();
      req.setAttribute("newsItems", newsItems);
      jsp.forward(req, resp);

Create JSP

Create list-news-items.jsp, and set its contents to the following list.

<%@ page import="java.util.Iterator" %>
<%@ page import="" %>
<jsp:useBean id="newsItems" scope="request" type="java.util.List" />
<%@ include file="" %>
   <a href="create-news-item">Create News Item</a>
<%@ include file="" %>
      Iterator it = newsItems.iterator();
      while (it.hasNext())
         NewsItem newsItem = (NewsItem);
         <a href="view-news-item?id=<%=newsItem.getId()%>"><%=newsItem.getTitle()%></a>
   <% } %>
<%@ include file="" %>


Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new servlet. Verify that the the new functionality works correctly by going to http://localhost:8080/publisher/home and following the link to the list items page. The following figure shows approximately how the list news items page should render.

List news items page

Note that the links on the list items page will not work yet. In the next section we implement the view item page, so that the links to the news items in the list will bring the user to the view item page.

back next

Copyright 2007-2009 David Turner and Jinseok Chae. All rights reserved.