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:
- The controller servlet handles the user’s request.
- The controller servlet instantiates the appropriate JavaBeans based on the
request. - The controller servlet communicates with the middle tier or directly to the
database to retrieve the required data. - The controller sets the JavaBeans in one of the following contexts: request,
session, or application. - The controller dispatches the request to the next view based on the request URL.
- The view uses the JavaBeans from step 4 to display data.