background image

Generating HTML Markup

<< Constructing Responses | Filtering Requests and Responses >>
<< Constructing Responses | Filtering Requests and Responses >>

Generating HTML Markup

book from the bookstore database. Finally, the servlet generates HTML markup that describes
the book information and then commits the response to the client by calling the close method
on the PrintWriter.
public class BookDetailsServlet extends HttpServlet {
...
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
...
// set headers before accessing the Writer
response.setContentType(
"text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();
// then write the response
out.println(
"<html>" +
"<head><title>+
messages.getString(
"TitleBookDescription")
+</title></head>
");
// Get the dispatcher; it gets the banner to the user
RequestDispatcher dispatcher =
getServletContext().
getRequestDispatcher(
"/banner");
if (dispatcher != null)
dispatcher.include(request, response);
// Get the identifier of the book to display
String bookId = request.getParameter(
"bookId");
if (bookId != null) {
// and the information about the book
try {
Book bd =
bookDB.getBook(bookId);
...
// Print the information obtained
out.println(
"<h2>" + bd.getTitle() + "</h2>" +
...
} catch (BookNotFoundException ex) {
response.resetBuffer();
throw new ServletException(ex);
}
}
out.println(
"</body></html>");
out.close();
}
}
Writing Service Methods
Chapter 4 · Java Servlet Technology
113