J2EE Design Patterns: The Presentation Layer Patterns: Model-View-Controller - MVC: the Types
(Page 2 of 4 )
MVC can be implemented in two different ways which constitute the types of MVC. In technical terms the types are known as Models. Please do not confuse this Model with the Model (M) of MVC. Models of MVC represent the ways in which the MVC can be implemented whereas the Model represents data. On the basis of the different ways they are implemented, the two Models are MVC Model-I and MVC Model-II. The point of difference between them is where Controller is implemented.
MVC Model-I
This Model is also known as the Page Centric Model. In this type of implementation, the View and the Controller exist as one entity -- the View-Controller. In terms of implementation, in the Page Centric approach the Controller logic is implemented within the View i.e. with J2EE, it is JSP. All the tasks of the Controller, such as extracting HTTP request parameters, call the business logic (implemented in JavaBeans, if not directly in the JSP), and handling of the HTTP session is embedded within JSP using scriptlets and JSP action tags. For example, to redirect to another page in the case of an invalid session, the MVC Model-I approach would be the following snippet within the JSP page:
<%
if(session.getAttribute("USER_ID")==null)
{
%>
<jsp:forward page="/authenticator/login.jsp"/>
<%
//other logic
%>
Pictorially the MVC Model-I would be:

MVC Model-II
The problem with Model-I is its lack of maintainability. With Controller logic embedded within the JSP using scriptlets, the code can get out of hand very easily. So to overcome the problems of maintainability and reusability, the Controller logic can be moved into a servlet and the JSP can be used for what it is meant to be -- the View component. Hence, by embedding Controller logic within a servlet, the MVC Model-II Design Pattern can be implemented.
Thus the major difference between Model-I and Model-II is where the Controller logic is embedded, in JSP or in a servlet. To clarify Model-II a bit more, let's take the example used for Model-I and convert it to Model-II. Instead of embedding the code snippet in JSP, it would become a part of the servlet with necessary modifications as below:
if(session.getAttribute("USER_ID")==null) {
RequestDispatcher dispatcher=request.getRequestDispatcher
("/authenticator/login.jsp");
dispactcher.forward(request,response);
}
else {
//other logic
}
Pictorially the MVC Model-II would be:

That completes the second section of this discussion. In the next part I will be developing a mailing list application containing both Model-I and Model-II of MVC.
Next: MVC in the Real World >>
More Java Articles
More By A.P.Rajshekhar