Java Web Programming with Eclipse contents
Last modified March 09, 2011 04:22 pm

back next

Item Management (continued)


Create Page


In this section, we will add functionality to enable the user to create additional news items. The logic needed for this task is similar to that used for the edit news item page.

Modify the news item DAO

Add the following create method to the news item DAO.

   public void create(NewsItem newsItem)
      Long id = getUniqueId();
      PreparedStatement statement = null;
      Connection connection = null;
         connection = getConnection();
         String sql = "insert into news_item " + "(id, title, url) "
               + "values (?, ?, ?)";
         statement = connection.prepareStatement(sql);
         statement.setLong(1, id.longValue());
         statement.setString(2, newsItem.getTitle());
         statement.setString(3, newsItem.getUrl());
      } catch (SQLException e)
         throw new RuntimeException(e);
      } finally
         close(statement, connection);

The create method takes an instance of the NewsItem class and inserts a row in the news_item table to represent this instance. The create method generates a unique id to serve as a primary key for the newly inserted news item. It sets the id field of the NewsItem object passed into it, so that the calling code has access to this newly generated value. It is possible to have MySQL generate a unique id as part of the insert command. This is done by declaring the id column with auto_increment during table creation. However, this feature is not part of standard SQL and is not implemented in all relational database servers. To keep the code portable to these other servers, we choose to generate our own primary keys.

Modify the Deployment Descriptor

Add configuration to web.xml so that CreateNewsItemServlet is invoked for requests matching /create-news-item as shown in the following listing.


Create CreateNewsItemServlet

Create CreateNewsItemServlet with the contents of the following listing.

package publisher.web;

import java.util.Map;

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 CreateNewsItemServlet 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/edit-news-item.jsp");
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
      jsp.forward(req, resp);

   protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException
      // Check if cancel button was pressed.
      String cancelButton = req.getParameter("cancel-button");
      if (cancelButton != null)
         logger.debug("cancel button pressed");
      Map<String, String> errors = EditNewsItemServlet.validate(req);
      if (!errors.isEmpty())
         logger.debug("validation errors");
         jsp.forward(req, resp);

      NewsItem newsItem = (NewsItem) req.getAttribute("newsItem");
      new NewsItemDAO().create(newsItem);
      resp.sendRedirect("view-news-item?id=" + newsItem.getId());

The jsp needed for the create news item servlet is identical to the edit news item servlet. For this reason, the doGet method of the create news item servlet forwards to the edit news item jsp.

In the doPost method, the first thing we do is check for the cancel button. If pressed, we send the user to the list-news-items page.

If the cancel button was not pressed, we validate and bind form data to an instance of NewsItem. If there are validation errors, we pass the newsItem and errors objects to the jsp to display the user input and the validation error messages.

Validation and binding for object creation and object editing are identical. For this reason, we invoke validate in EditNewsItemServlet, rather than replicate the code in CreateNewsItem. For this to work, we declared the validateAndBind method of EditNewsItemServlet as static.

If there are no validation errors, we invoke the create method of the NewsItemDAO class. Unlike EditNewsItemServlet, we don't need to worry about NotFoundException.

After creating the news item in the database, we return the user to the view-news-item page, so that he can verify that the news item was created. (Alternatively, we could have redirected the user to the list-news-items page.) The create method of NewsItemDAO has the side effect of setting the id attribute of the NewsItem object passed into it. For this reason, we are able to redirect the user to the view news item page with the id of the newly created news item.


Stop and start the publisher application with the Tomcat manager application, so that Tomcat reloads the web.xml file and the new class files. Verify that the new functionality works correctly by going to http://localhost:8080/publisher/home and creating an additional news item. You should try entering in an empty title and an empty url to check that validation works correctly. The following figure shows approximately how the create news item page should render.

Create news item page

back next

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