Bill Digman is a Java EE / Servlet enthusiast and Open Source enthusiast who loves working with Caucho's Resin Servlet Container, a Java EE Web Profile Servlet Container. Bill has posted 12 posts at DZone. You can read more from them at their website. View Full User Profile

Java EE: JSP 2.2 and Servlets 3.0 tutorial with Resin Servlet Container Part Two

11.01.2012
| 5968 views |
  • submit to reddit

Java EE Servlet tutorial : Adding create, update and delete to the bookstore listing.  

This tutorial is part of Java EE Tutorial covering JSP_2.2, and Servlets 3.0

Contents

  • Java EE Servlet Tutorial: Implementing a basic CRUD listing
  • Adding a link to the book listing to edit a book
    • Adding an edit book link to book-list.jsp listing
  • Adding a link to the book listing to add a book
    • Adding an add book link to book-list.jsp listing
  • Servlet doGet to load a Book form
    • BookEditorServlet.java doGet
    • BookEditorServlet.java doGet() delegate to book-form.jsp page
    • BookEditorServlet.java doGet() delegate to book-form.jsp page
  • Rendering the book form HTML
    • book-form.jsp Renders form to update or add a Book
    • book-form.jsp using JSTL c:choose to display update or add status
    • book-form.jsp using JSTL c:if to hidden id field for edit/update operation
  • Creating a doPost method to handle the form submission
    • BookEditorServlet.java doPost
  • Quick review of what we have so far
    • ./WebContent/WEB-INF/pages/book-form.jsp full listing
    • ./WebContent/WEB-INF/pages/book-list.jsp full listing
    • ./src/META-INF/beans.xml full listing
    • ./src/com/bookstore/Book.java
    • ./src/com/bookstore/BookRepositoryImpl.java full listing (testing only)
    • ./src/com/bookstore/BookRepository.java full listing
    • ./src/com/bookstore/web/BookEditorServlet.java
    • ./src/com/bookstore/web/BookListServlet.java
  • Technical debt

Java EE Servlet Tutorial: Implementing a basic CRUD listing

We left off with a basic listing. BookListServlet used a BookRepository  object (DAO) to load a list of books and then delegated to book-list.jsp to render  the book listing.

In this step, we want to add a link to the book listing so when the user clicks it a form gets rendered so that they can edit the details of book. Also we want an add link so that the end user can add a new book to the listing.

Adding a link to the book listing to edit a book

Change the code that looks like this in book-list.jsp:

...
	<c:forEach var="book" items="${books}">
		<tr>
			<td>${book.title}</td>
...

To this by adding an edit book link to book-list.jsp listing

...
	<c:forEach var="book" items="${books}">
	     <tr>
			<td><a href="${pageContext.request.contextPath}/book?id=${book.id}">${book.title}</a></td>
...			

The EL expression ${pageContext.request.contextPath} refers to the URI you have the war file mapped to in the Servlet container. The default URI for a webapp is its war file name so our war file name is bookstore so a rendered URL will look like this:

	...
		<tr>
			<td><a href="/bookstore/book?id=0">War and Peace</a></td>
	...
		<tr>
			<td><a href="/bookstore/book?id=1">Pride and Prejudice</a></td>
	...

The link /bookstore/book/ (with slash) loads the book listing. The link /bookstore/book?id=1 loads the form page to edit an existing book. To add a new book, we will use the link /bookstore/book.

Adding a link to the book listing to add a book

Adding an add book link to book-list.jsp listing

Before the table add this HTML code to add a new book:

...
<a href="${pageContext.request.contextPath}/book">Add Book</a>
...			

Now we have to links going to the URI /book, we need a Servlet that handles the links. The BookEditorServlet handles both add and the edit book functions.

Servlet doGet to load a Book form

BookEditorServlet.java doGet
package com.bookstore.web;




...




@WebServlet("/book")
public class BookEditorServlet extends HttpServlet {




	@Inject
	private BookRepository bookRepo;
		
	private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
	
    ...
	/** Prepare the book form before we display it. */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");




		if (id != null && !id.isEmpty()) {
			Book book = bookRepo.lookupBookById(id);
			request.setAttribute("book", book);
			request.setAttribute("bookPubDate", dateFormat.format(book.getPubDate()));
		}




		/* Redirect to book-form. */
		getServletContext().getRequestDispatcher("/WEB-INF/pages/book-form.jsp").forward(
				request, response);




	}
}

Notice we use @WebServlet("/book") to map BookEditorServlet to the URI /book. It is common to load a form from a doGet method, and to handle the form submission via doPost. Following REST and HTTP principles GET operations reads data, and POST data modifies data. The doGet method uses the id being empty or not to determine if this is a load  "Add Employee Form" or load "Update Employee Form" operation. The doGet method also converts  the date into a format that is easy for the end user to modify and it also maps the book into request scope as follows:

BookEditorServlet.java doGet() delegate to book-form.jsp page
			Book book = bookRepo.lookupBookById(id);
			request.setAttribute("book", book);
			request.setAttribute("bookPubDate", dateFormat.format(book.getPubDate()));




In the model 2 architecture, the Servlet tier prepares the form data before a form loads to be rendered and edited correctly.

To render the HTML form, the servlet delegates to book-form.jsp as follows:

BookEditorServlet.java doGet() delegate to book-form.jsp page
		/* Redirect to book-form. */
		getServletContext().getRequestDispatcher("/WEB-INF/pages/book-form.jsp").forward(
				request, response);




 

Bill Digman is a Java EE / Servlet enthusiast and Open Source enthusiast who loves working with Caucho's Resin Servlet Container, a Java EE Web Profile Servlet Container.

Caucho's Resin OpenSource Servlet ContainerJava EE Web Profile Servlet ContainerJavaLobby Article: Java EE Tutorial Covering JSP and Servlets Part OneCaucho Wiki Java EE Servlet Tutorial: Using JSPs to create header, footer area, formatting, and basic css for bookstore <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> ${param.title} ${param.title}
AttachmentSize
Java EE Tutorial covering JSP and Servlets PDF.pdf671.11 KB
Published at DZone with permission of its author, Bill Digman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)