Learn Java for Web Development

(Tina Meador) #1

86 CHAPTER 2: Building Web Applications Using Servlets and JSP


Figure 2-30 shows the output when user.jsp is accessed.


Figure 2-30. Usage of useBean, getProperty, and setProperty actions


The MVC Pattern


The motivation for the Model-View-Controller (MVC) pattern has been around since the conception
of object-oriented programming. Prior to MVC, the browser directly accessed JSP pages. In other
words, JSP pages handled user requests directly. This was called a Model-1 architecture, as
illustrated in Figure 2-31. A Model-1 architecture exhibited decentralized application control, which
led to a tightly coupled and brittle presentation tier.


Figure 2-31. Model-1 architecture


A Model-2 architecture for designing JSP pages is in actuality the MVC pattern applied to web
applications. MVC originated in Smalltalk and has since made its way to Java community.
Figure 2 -3 2 shows the Model-2 (in other words, MVC) architecture. In Model-2, a controller
handles the user request instead of another JSP page. The controller is implemented as a servlet.
The following steps are executed when the user submits the request:



  1. The controller servlet handles the user’s request.

  2. The controller servlet instantiates the appropriate JavaBeans based on the
    request.

  3. The controller servlet communicates with the middle tier or directly to the
    database to retrieve the required data.

  4. The controller sets the JavaBeans in one of the following contexts: request,
    session, or application.

  5. The controller dispatches the request to the next view based on the request URL.

  6. The view uses the JavaBeans from step 4 to display data.

Free download pdf