Learn Java for Web Development

(Tina Meador) #1

116 CHAPTER 3: Best Practices in Java EE Web Development


11.import com.apress.chapter03.model.Author;
12.import com.apress.chapter03.model.Book;
13.
14.public class BookController extends HttpServlet {
15.
16.protected void doGet(HttpServletRequest request,
17.HttpServletResponse response) throws ServletException, IOException {
18.Book book = new Book();
19.book.setBookTitle("Learning Java Web");
20.Author author = new Author();
21.author.setName("Vishal Layka");
22.book.setAuthor(author);
23.
24.request.setAttribute("bookAttrib", book);
25.
26.RequestDispatcher view = request.getRequestDispatcher("/book.jsp");
27.view.forward(request, response);
28.}
29.
30.}


Listing 3-11 is the controller part of the MVC pattern. As you learned in Listing 3-2, the separation
of the view concern from the business-logic concern depends on the attributes. Hence, you have
to save the model object into the attributes for the view (JSP) to be able to access the model via
attributes.


   Lines 19 to 22: In these lines you set the bookTitle and author properties of
Book. Note that the name property of Author is already set on line 21.
 Line 22: This sets the author property of book.
 Line 24: This sets the Book object as an attribute in the request.
 Lines 26 to 27: Line 26 should now be familiar to you. In this line, you dispatch
the request to book.jsp.

Listing 3-12 provides the deployment descriptor for this application.


Listing 3-12. web.xml


1.<?xml version="1.0" encoding="UTF-8"?>
2.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"



  1. xmlns="http://java.sun.com/xml/ns/javaee"

  2. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

  4. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    7.chapter03
    8.
    9.BookController
    10.com.apress.chapter03.controller.BookController
    11.

    12.
    13.BookController

Free download pdf