Post on 30-May-2019
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
1/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
BILLDIGMAN Search
JAVALOBBY Join thought leaders, community members and developers at GraphConnect 2012!
Article Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 Model 2 CRUD hasbeen created.
The post has been submitted for moderation and won't be listed publicly until it has been approved.
View Edit
Tutorial covering Java EE: JSP2.2 and Servlets 3.0 withOpenSource Resin ServletContainer: Part 2 Model 2CRUD11.01.2012 | views | TweetTweet 0 0
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
Bill DigmanBio
Like 0 ShareShare
Publish an ArticlePublish an Article Share a Tip Share a Tip
FollowFollow 17.5K followers
DZone, Inc. on Follow
CONNECT WITH DZONE
Getting Started with Drupal 7Written by: Cindy McCourt
Featured Refcardz: Top Refcardz:1. Jenkins on PaaS2. VisualVM3. Android4. Scala5. Drupal 7
1. Drupal 72. Scala3. Java4. Java Concurrency5. VisualVM
150+ Refcardz Available · Get them all
The Absolute Top 34Features of WindowsPhone 8
SOA Service DesignCheat Sheet
Weekly Poll: Windows8... When?
Domain Modeling withOWL - Part 2
POPULAR AT DZONE
Like 5k
Spotlight Features
HOM E REFCARDZ M ICROZONES ZONES LIBRARY SNIPPET S T UT ORIALS
Online Visitors: 253
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
2/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./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 ofbooks 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 sothat they can edit the details of book. Also we want an add link so that the end user can add a newbook 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:
To this by adding an edit book link to book-list.jsp listing
The EL expression ${pageContext.request.contextPath} refers to the URI you have the war filemapped to in the Servlet container. The default URI for a webapp is its war file name so our war filename is bookstore so a rendered URL will look like this:
The link /bookstore/book/ (with slash) loads the book listing. The link /bookstore/book?id=1 loads theform 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 bookAdding an add book link to book-list.jsp listing
Before the table add this HTML code to add a new book:
1.2.3.4.5.
...<c:forEach var="book" items="${books}">
<tr><td>${book.title}</td>
...
1.2.3.4.
5.
...<c:forEach var="book" items="${books}">
<tr><td><a href="${pageContext.request.contextPath}/book?
id=${book.id}">${book.title}</a></td>...
1.2.3.4.5.6.7.
...<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>
...
1.2.3.
...<a href="${pageContext.request.contextPath}/book">Add Book</a>...
See more popular at DZone
Subscribe to the RSS feed
Check if String is valid Date in Java
Discovering the future of Java
Data Grid, JBoss Data Grid
Top of Apache Commons Libraries forJava Development
Java's Future... Lays in Lienzo
Downloads of Scala plugin for IntelliJrocket upwards
Read / Write CSV file in Java
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
3/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
Now we have to links going to the URI /book, we need a Servlet that handles the links. TheBookEditorServlet handles both add and the edit book functions.
Servlet doGet to load a Book formBookEditorServlet.java doGet
Notice we use @WebServlet("/book") to map BookEditorServlet to the URI /book. It is common to loada form from a doGet method, and to handle the form submission via doPost. Following REST andHTTP principles GET operations reads data, and POST data modifies data. The doGet method usesthe id being empty or not to determine if this is a load "Add Employee Form" or load "UpdateEmployee Form" operation. The doGet method also converts the date into a format that is easy for theend user to modify and it also maps the book into request scope as follows:
BookEditorServlet.java doGet() delegate to book-form.jsp page
01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.
21.22.23.24.25.
26.27.28.29.30.31.32.33.34.
35.36.37.38.39.40.41.
42.43.44.45.46.47.48.
package com.bookstore.web; ... @WebServlet("/book")public class BookEditorServlet extends HttpServlet {
@Injectprivate 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);
}}
1.2.3.
Book book = bookRepo.lookupBookById(id);request.setAttribute("book", book);request.setAttribute("bookPubDate", dateFormat.format(book.getPubDate()));
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
4/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
In the model 2 architecture, the Servlet tier prepares the form data before a form loads to be renderedand 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
Rendering the book form HTML
The book-form.jsp has the HTML code to render a form as follows:
book-form.jsp Renders form to update or add a Book
1.2.
3.
/* Redirect to book-‐form. */getServletContext().getRequestDispatcher("/WEB-‐INF/pages/book-‐
form.jsp").forward(request, response);
001.002.003.004.005.006.007.008.009.010.011.012.013.014.015.016.017.018.019.020.021.022.023.024.025.026.027.028.029.030.031.032.033.034.035.036.037.038.039.040.041.042.043.044.045.
046.047.048.049.050.051.052.053.054.
<%@ page language="java" contentType="text/html; charset=UTF-‐8"pageEncoding="UTF-‐8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML><html><head><title>Book Form</title></head> <body>
<h1>Book Form</h1>
<form method="post"action="${pageContext.request.contextPath}/book"><fieldset>
<legend><c:choose>
<c:when test="${not empty book.id }">Updating Book
</c:when><c:otherwise>
Adding Book</c:otherwise>
</c:choose></legend>
<div><label for="title">Title</label> <input type="text"
name="title"id="title" value="${book.title}" />
</div>
<div><label for="description">Description</label><textarea name="description" id="description" rows="2"
cols="60">${book.description}</textarea>
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
5/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
The book-form.jsp uses JSTL c:choose, c:otherwise to display whether we are adding a new book orupdating a book as follows:
book-form.jsp using JSTL c:choose to display update or add status
055.056.057.058.059.060.061.
062.063.064.065.066.067.068.069.070.071.072.073.074.075.076.077.078.079.080.081.082.083.084.085.086.087.088.089.090.091.
092.093.094.095.096.097.098.099.
cols="60">${book.description}</textarea></div>
<div><label for="price">Price $</label> <input name="price"
id="price" value="${book.price}" />
</div>
<div><label for="pubDate">Publication Date</label> <input name="pubDate" id="pubDate"
value="${bookPubDate}" /><label class="after">(MM/DD/YYYY)</label>
</div>
<c:if test="${not empty book.id}"><input type="hidden" name="id" value="${book.id}" />
</c:if>
</fieldset>
<div class="button-‐row"><a href="${pageContext.request.contextPath}/book/">Cancel</a> or
<input type="submit" value="Submit" /></div>
</form> </body></html>
01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.
...<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>...
<legend><c:choose>
<c:when test="${not empty book.id }">Updating Book
</c:when><c:otherwise>
Adding Book</c:otherwise>
</c:choose></legend>
...
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
6/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
If the book.id property is present the test "Updating Book" is rendered.
Also, the form renders a hidden id property if it is doing an edit/update operation as follows:
book-form.jsp using JSTL c:if to hidden id field for edit/update operation
The doPost method of BookEditorServlet handles the form submission as follows:
Creating a doPost method to handle the form
submissionBookEditorServlet.java doPost
1.2.3.
<c:if test="${not empty book.id}"><input type="hidden" name="id" value="${book.id}" />
</c:if>
01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.
28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.
package com.bookstore.web; ... @WebServlet("/book")public class BookEditorServlet extends HttpServlet {
@Injectprivate BookRepository bookRepo;
.../*** Handles posting an HTML book form. If the id is null then it is an* "add book", if the id is set then it is an "update book"*/protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
String title = request.getParameter("title");String description = request.getParameter("description");String price = request.getParameter("price");String pubDate = request.getParameter("pubDate");
String id = request.getParameter("id");if (id == null || id.isEmpty()) {
bookRepo.addBook(title, description, price, pubDate);} else {
bookRepo.updateBook(id, title, description, price, pubDate);}
response.sendRedirect(request.getContextPath() + "/book/");}...
}
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
7/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
Notice that if the id is null then BookEditorServlet.doPost calls bookRepo.addBook, otherwise it callsbookRepo.updateBook. Once the form handling is done, doPost redirects to /book/. A redirect meansan extra hit to the server, since we are basically telling the browser to load another link. The astutereader may wonder why we don't just do a forward like we did in the doGet. The answer isbookmarking. The URL /book/ (ending in slash) represents a collection of books, while /book (noslash) represents a single book (using REST style URL). If we did a forward, then after the formsubmission the browser would show the listing, but under the URI /book instead of /book/. If the enderuser linked to /book, it would not take them back to the listing but back to a form, which not correct.This is why we do a sendRedirect instead of a forward.
Now we have an add/edit/update/read/ and listing. It is everything you could want from a CRUD listing.
At this point, we don't do much validation. We will add this in a later lesson.
Quick review of what we have so far
We have created the following files for this bookstore example:
./WebContent/WEB-INF/pages/book-form.jsp full listing
01.02.03.04.05.
06.
07.
08.
09.
10.
$ find .../WebContent/WEB-‐INF/pages/book-‐form.jsp Book Form./WebContent/WEB-‐INF/pages/book-‐list.jsp Book Listing./src/META-‐INF/beans.xml Needed for
Java EE dependency injection (CDI)./src/com/bookstore/Book.java Domain/model
object./src/com/bookstore/BookRepositoryImpl.java Repository
implementation using Java collections (just for testing)./src/com/bookstore/BookRepository.java Interface to Book
Repository so we can swap it out with JDBC, JPA, JCache and MongoDBversion later
./src/com/bookstore/web/BookEditorServlet.java Servlet that loads Book(doGet) form and handles Book form submissions (doPost).
./src/com/bookstore/web/BookListServlet.java Servlet that looks upa list of books and displays the listing
001.002.003.004.005.006.007.008.009.010.011.012.013.014.015.016.017.018.019.020.021.022.023.024.025.026.027.028.029.030.031.032.033.034.
<%@ page language="java" contentType="text/html; charset=UTF-‐8"pageEncoding="UTF-‐8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML><html><head><title>Book Form</title></head> <body>
<h1>Book Form</h1>
<form method="post"action="${pageContext.request.contextPath}/book"><fieldset>
<legend><c:choose>
<c:when test="${not empty book.id }">Updating Book
</c:when>
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
8/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./WebContent/WEB-INF/pages/book-list.jsp full listing
034.035.036.037.038.039.040.041.042.043.044.045.
046.047.048.049.050.051.052.053.054.
055.056.057.058.059.060.061.
062.063.064.065.066.067.068.069.070.071.072.073.074.075.076.077.078.079.080.081.082.083.084.085.086.087.088.089.090.091.
092.093.094.095.096.097.098.099.
</c:when><c:otherwise>
Adding Book</c:otherwise>
</c:choose></legend>
<div><label for="title">Title</label> <input type="text"
name="title"id="title" value="${book.title}" />
</div>
<div><label for="description">Description</label><textarea name="description" id="description" rows="2"
cols="60">${book.description}</textarea></div>
<div><label for="price">Price $</label> <input name="price"
id="price" value="${book.price}" />
</div>
<div><label for="pubDate">Publication Date</label> <input name="pubDate" id="pubDate"
value="${bookPubDate}" /><label class="after">(MM/DD/YYYY)</label>
</div>
<c:if test="${not empty book.id}"><input type="hidden" name="id" value="${book.id}" />
</c:if>
</fieldset>
<div class="button-‐row"><a href="${pageContext.request.contextPath}/book/">Cancel</a> or
<input type="submit" value="Submit" /></div>
</form> </body></html>
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
9/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./src/META-INF/beans.xml full listing
./src/com/bookstore/Book.java
01.
02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.
33.34.35.36.37.38.39.40.41.42.43.44.
<%@ page language="java" contentType="text/html; charset=UTF-‐8"pageEncoding="UTF-‐8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c" %><!DOCTYPE HTML> <html><head><title>Book listing</title></head><body> <a href="${pageContext.request.contextPath}/book">Add Book</a> <table>
<tr><th>Title</th><th>Description</th><th>Price</th><th>Publication Date</th>
</tr> <c:forEach var="book" items="${books}">
<tr><td><a href="${pageContext.request.contextPath}/book?
id=${book.id}">${book.title}</a></td><td>${book.description}</td><td>${book.price}</td><td>${book.pubDate}</td>
</tr></c:forEach>
</table> </body></html>
1.2.3.4.
5.
<?xml version="1.0" encoding="UTF-‐8"?><beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-‐instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"></beans>
001.002.003.004.005.006.007.008.009.010.011.012.013.014.015.016.017.
package com.bookstore; import java.math.BigDecimal;import java.util.Date; public class Book implements Cloneable {
private String title;
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
10/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
018.019.020.021.022.023.
024.025.026.027.028.029.030.031.032.033.034.035.036.037.038.039.040.041.042.043.044.045.046.047.048.049.050.051.052.053.054.055.056.057.058.059.060.061.062.063.064.065.066.067.068.069.070.071.072.073.074.075.076.077.078.079.080.081.082.083.084.085.086.087.088.089.090.091.
private String description;private BigDecimal price;private Date pubDate;private String id; public Book(String id, String title, String description, BigDecimal
price, Date pubDate) {this.id = id;this.title = title;this.description = description;this.price = price;this.pubDate = pubDate;
} public Book () {
}
public String getTitle() {return title;
}
public void setTitle(String title) {this.title = title;
}
public String getDescription() {return description;
}
public void setDescription(String description) {this.description = description;
}
public BigDecimal getPrice() {return price;
}
public void setPrice(BigDecimal price) {this.price = price;
}
public Date getPubDate() {return pubDate;
}
public void setPubDate(Date pubDate) {this.pubDate = pubDate;
}
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
11/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./src/com/bookstore/BookRepositoryImpl.java full listing (testing only)
091.092.093.094.095.096.097.098.099.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.
public String getId() {return id;
}
public void setId(String id) {this.id = id;
} public Book cloneMe() {
try {return (Book) super.clone();
} catch (CloneNotSupportedException e) {return null;
}} @Overridepublic String toString() {
return "Book [title=" + title + ", description=" + description+ ", price=" + price + ", pubDate=" + pubDate + ", id=" + id+ "]";
} }
001.002.003.004.005.006.007.008.009.010.011.012.013.014.015.016.017.018.019.020.021.022.023.024.025.026.027.028.029.030.
031.032.033.034.035.036.037.038.039.
package com.bookstore; import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.math.BigDecimal; import javax.enterprise.context.ApplicationScoped; @ApplicationScopedpublic class BookRepositoryImpl implements BookRepository {
private SimpleDateFormat dateFormat = newSimpleDateFormat("MM/dd/yyyy");
private int count;private Map<String, Book> idToBookMap = new HashMap<String, Book>();
public BookRepositoryImpl() {synchronized (this) {
books(book("War and Peace", "blah blah blah", "5.50",
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
12/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
039.
040.
041.042.043.044.045.046.047.048.049.050.
051.052.053.054.055.056.057.058.059.060.061.062.063.064.065.066.067.068.069.070.071.072.073.074.075.076.077.078.079.080.081.082.083.084.085.086.087.088.089.090.091.092.093.094.095.096.097.098.099.100.101.102.103.104.105.106.107.108.109.110.111.
books(book("War and Peace", "blah blah blah", "5.50","5/29/1970"),
book("Pride and Prejudice", "blah blah blah", "5.50","5/29/1960"),
book("book1", "blah blah blah", "5.50", "5/29/1960"),book("book2", "blah blah blah", "5.50", "5/29/1960"),book("book3", "blah blah blah", "5.50", "5/29/1960"),book("book4", "blah blah blah", "5.50", "5/29/1960"),book("book5", "blah blah blah", "5.50", "5/29/1960"),book("book6", "blah blah blah", "5.50", "5/29/1960"),book("book7", "blah blah blah", "5.50", "5/29/1960"),book("book8", "blah blah blah", "5.50", "5/29/1960"),book("book9", "blah blah blah", "5.50", "5/29/1960"),book("Java for dummies", "blah blah blah", "1.99",
"5/29/1960"));}
}
private Book book(String title, String description, String aPrice,String aPubDate) {
Date pubDate = null;BigDecimal price = null; try {
price = new BigDecimal(aPrice);}catch (Exception ex) {} try {
pubDate = dateFormat.parse(aPubDate);}catch (Exception ex) {} return new Book("" + (count++), title, description, price, pubDate);
}
private void books(Book... books) {for (Book book : books) {
doAddBook(book);}
}
private void doAddBook(Book book) {synchronized (this) {
this.idToBookMap.put(book.getId(), book);}
}
@Overridepublic Book lookupBookById(String id) {
synchronized (this) {return this.idToBookMap.get(id).cloneMe();
}}
@Override
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
13/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./src/com/bookstore/BookRepository.java full listing
111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.154.155.156.157.158.159.160.161.162.163.164.165.166.167.168.169.170.171.172.173.174.175.176.
@Overridepublic void addBook(String title, String description, String price,
String pubDate) {doAddBook(book(title, description, price, pubDate));
}
@Overridepublic void updateBook(String id, String title, String description,
String price, String pubDate) {Book book = book(title, description, price, pubDate);synchronized (this) {
book.setId(id);this.idToBookMap.put(id, book);
}}
private List<Book> doListBooks() {List<Book> books;synchronized (this) {
books = new ArrayList<Book>(this.idToBookMap.size());for (Book book : this.idToBookMap.values()) {
books.add(book.cloneMe());}
}return books;
} public List<Book> listBooks() {
List<Book> books = doListBooks();
Collections.sort(books, new Comparator<Book>() {public int compare(Book bookA, Book bookB) {
return bookA.getId().compareTo(bookB.getId());}
});return books;
}
@Overridepublic void removeBook(String id) {
synchronized(this) {this.idToBookMap.remove(id);
}}
}
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
14/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./src/com/bookstore/web/BookEditorServlet.java
01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.
package com.bookstore; import java.util.List; public interface BookRepository {
Book lookupBookById(String id);
void addBook(String title, String description,String price, String pubDate);
void updateBook(String id, String title,String description, String price, String pubDate);
void removeBook(String id);
List<Book> listBooks(); }
001.002.003.004.005.006.007.008.009.010.011.012.013.014.015.016.017.018.019.020.021.022.023.024.025.026.027.028.029.030.031.032.
package com.bookstore.web; import java.io.IOException;import java.text.SimpleDateFormat; import javax.inject.Inject;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.bookstore.Book;import com.bookstore.BookRepository; /*** Servlet implementation class BookEditorServlet*/@WebServlet("/book")public class BookEditorServlet extends HttpServlet {
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
15/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
./src/com/bookstore/web/BookListServlet.java
033.034.035.036.037.038.039.040.
041.042.043.044.
045.046.047.048.049.050.051.052.053.
054.055.056.057.058.059.060.
061.062.063.064.065.066.067.068.069.070.071.072.073.
074.075.076.077.078.079.080.081.082.083.084.085.086.087.088.089.090.091.092.093.094.095.096.097.098.099.
@Injectprivate 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);
} /*** Handles posting an HTML book form. If the id is null then it is an* "add book", if the id is set then it is an "update book"*/protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
String title = request.getParameter("title");String description = request.getParameter("description");String price = request.getParameter("price");String pubDate = request.getParameter("pubDate");
String id = request.getParameter("id");if (id == null || id.isEmpty()) {
bookRepo.addBook(title, description, price, pubDate);} else {
bookRepo.updateBook(id, title, description, price, pubDate);}
response.sendRedirect(request.getContextPath() + "/book/");}
}
11/1/12 Tutorial covering Java EE: JSP 2.2 and Servlets 3.0 with OpenSource Resin Servlet Container: Part 2 …
16/18java.dzone.com/articles/tutorial-‐‑covering-‐‑java-‐‑ee-‐‑jsp
Technical debt
We have accumulated some technical debt. Our UI is just plain HTML, it has no styling. This isprobably and oversight. There is no footer, or header. There probably should be some sort of headerarea that has a link to the home page, and a footer with a copyright notice or something. The booklisting does not format the price of the date, it should.
We will address these issues and others in the coming lessons.
Bill Digman is a Java EE / Servlet enthusiast and Open Source enthusiast who loves working withCaucho's Resin Servlet Container, a Java EE Web Profile Servlet Container.
Caucho's Resin OpenSource Servlet Container
Java EE Web Profile Servlet Container
JavaLobby Article: Java EE Tutorial Covering JSP and Servlets Part One
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.)
Tags: CDI java java ee JSP/Servlet Tutorial Model 2 CRUD Resin
01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.
36.37.
38.39.40.41.42.43.
package com.bookstore.web; import java.io.IOException; import javax.inject.Inject;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.bookstore.BookRepository; @WebServlet("/book/")public class BookListServlet extends HttpServlet {
@Inject private BookRepository bookRepo;
protected void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {request.setAttribute("books", bookRepo.listBooks());getServletContext().getRequestDispatcher("/WEB-‐INF/pages/book-‐
list.jsp").forward(request, response);}
}