Thursday, 21 April 2011

MVC with configurable controller


You must be wondering what went wrong with MVC. When application gets large you cannot stick to bare bone MVC. You have to extend it somehow to deal with these complexities. One mechanism of extending MVC that has found widespread adoption is based on a configurable controller Servlet. The MVC with configurable controller servlet.
 When the HTTP request arrives from the client, the Controller Servlet looks up in a properties file to decide on the right Handler class for the HTTP request.This Handler class is referred to as the Request Handler. The Request Handler  contains the presentation logic for that HTTP request including business logic invocation. In other words, the Request Handler does everything that is needed to handle the HTTP request. The only difference so far from the bare bone MVC is that the controller servlet looks up in a properties file to instantiate the Handler instead of calling it directly.

Model 2 Architecture - MVC


The Model 2 architecture for designing JSP pages is in reality, Model View Controller (MVC) applied to web applications. Hence the two terms can be used interchangeably in the web world. MVC originated in SmallTalk and has since made its way into Java community. Model 2 architecure and its derivatives are
the cornerstones for all serious and industrial strength web applications designed in the real world. Hence it is essential for you understand this paradigm thoroughly.


The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. 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. (This means the hyperlink in the JSP should point to the controller servlet).
2. The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes).
3. The Controller Servlet then by itself or through a controller helper communicates with the middle tier or directly to the database to fetch the required data.

4. The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application.
5. The controller then dispatches the request to the next view based on the request URL.
6. The View uses the resultant JavaBeans from Step 4 to display data.

Note that there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture is to display the data from the JavaBeans set in the request, session or application scopes.

Advantages of Model 2 Architecture

Since there is no presentation logic in JSP, there are no scriptlets. This means lesser nightmares. [Note that although Model 2 is directed towards elimination ofscriptlets, it does not architecturally prevent you from adding scriptlets. This has led to widespread misuse of Model 2 architecture.With MVC you can have as many controller servlets in your web application.

In fact you can have one Controller Servlet per module. However there are several advantages of having a single controller servlet for the entire web application. In a typical web application, there are several tasks that you want todo for every incoming request. For instance, you have to check if the user requesting an operation is authorized to do so. You also want to log the user’s entry and exit from the web application for every request. You might like to centralize the logic for dispatching requests to other views. The list goes on. If
you have several controller servlets, chances are that you have to duplicate the logic for all the above tasks in all those places. A single controller servlet for the web application lets you centralize all the tasks in a single place. Elegant code and easier to maintain.


Web applications based on Model 2 architecture are easier to maintain and extend since the views do not refer to each other and there is no presentation logic in the views. It also allows you to clearly define the roles and responsibilities in large projects thus allowing better coordination among team members.


Controller gone bad – Fat Controller

If MVC is all that great, why do we need Struts after all? The answer lies inthe difficulties associated in applying bare bone MVC to real world complexities.  In medium to large applications, centralized control and processing logic in the servlet – the greatest plus of MVC is also its weakness. Consider a mediocre application with 15 JSPs. Assume that each page has five hyperlinks (or five form submissions). The total number of user requests to be handled in the application is 75. Since we are using MVC framework, a centralized controller servlet handles every user request. For each type of incoming request there is “if”
block in the doGet method of the controller Servlet to process the request and dispatch to the next view. For this mediocre application of ours, the controller Servlet has 75 if blocks. Even if you assume that each if block delegates the request handling to helper classes it is still no good. You can only imagine how bad it gets for a complex enterprise web application. So, we have a problem at hand. The Controller Servlet that started out as the greatest thing next to sliced bread has gone bad. It has put on a lot of weight to become a Fat Controller.






Model 1 Architecture


Model 1 architecture is the easiest way of developing JSP based web applications. It cannot get any easier. In Model 1, the browser directly accesses JSP pages. In other words, user requests are handled directly by the JSP. Let us illustrate the operation of Model 1 architecture with an example. Consider a HTML page with a hyperlink to a JSP. When user clicks on the hyperlink, the JSP is directly invoked. The servlet container parses the JSP and executes the resulting Java servlet. The JSP contains embedded code and tags to access the Model JavaBeans. The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string. In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page. The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags.

Problems with Model 1 Architecture

Model 1 architecture is easy. There is some separation between content(Model JavaBeans) and presentation (JSP). This separation is good enough for  smaller applications. Larger applications have a lot of presentation logic. In Model 1 architecture, the presentation logic usually leads to a significant amount of Java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers. In large applications, JSPs are developed and maintained by page authors. The intermingled scriptlets and markup results in unclear definition of roles and is very problematic. 

Application control is decentralized in Model 1 architecture since the next page to be displayed is determined by the logic embedded in the current page. Decentralized navigation control can cause headaches. All this leads us to Model 2 architecture of designing JSP pages.


J2EE web application


Any web application that runs in the servlet container is called a J2EE web application. The servlet container implements the Servlet and JSP specification. It provides various entry points for handling the request  originating from a web browser. There are three entry points for the browser into the J2EE web application - Servlet, JSP and Filter. You can create your own Servlets by extending the javax.servlet.http.HttpServlet class and implementing the doGet() and doPost() method. You can create JSPs simply by creating a
text file containing JSP markup tags. You can create Filters by implementing the javax.servlet.Filter interface.
The servlet container becomes aware of Servlets and Filters when they are declared in a special file called web.xml 2. A J2EE web application has exactlyone web.xml file. The web  application is deployed into the servlet container by bundling it in zipped archive called Web ARchive – commonly referred to as WAR file.


A servlet is the most basic J2EE web component. It is managed by the servlet container. All servlets  implement the Servlet interface directly or indirectly. In general terms, a servlet is the endpoint for requests adhering to a protocol. However, the Servlet specification mandates implementation for servlets that handle HTTP requests only. But you should know that it is possible to implement the servlet and the container to handle other protocols such as FTP too. When writing Servlets for handling HTTP requests, you generally subclass HttpServlet class. HTTP has six methods of request submission – GET, POST, PUT, HEAD
and DELETE. Of these, GET and POST are the only forms of request submission relevant to application developers. Hence your subclass of HttpServlet should implement two methods – doGet() and doPost() to handle GET and POST respectively. Listing 1.1 shows a doGet() method from a typical Servlet. With this background, let us now dive straight into presentation tier strategies. This coverage of presentation tier strategies will kick start your thought process on how and where Struts fits in the big picture. 

J2EE Platform


As you might be already knowing, J2EE is a platform for executing server side Java applications. Before J2EE was born, server side Java applications were written using vendor specific APIs. Each vendor had unique APIs and architectures. This resulted in a huge learning curve for Java developers and architects to learn and program with each of these API sets and higher costs for the companies. Development community could not reuse the lessons learnt in the trenches. Consequently the entire Java developer community was fragmented, isolated and stunted thus making very difficult to build serious enterprise applications in Java.
Fortunately the introduction of J2EE and its adoption by the vendors has resulted in standardization of its APIs. This in turn reduced the learning curve for server side Java developers. J2EE specification defines a whole lot of interfaces and a few classes. Vendors (like BEA and IBM for instance) have provided
implementations for these interfaces adhering to the J2EE specifications. These implementations are called J2EE Application Servers.

The J2EE application servers provide the infrastructure services such as threading, pooling and transaction management out of the box. The application developers can thus concentrate on implementing business logic. Consider a J2EE stack from a developer perspective. At the bottom of the stack is Java 2 Standard Edition (J2SE). J2EE Application Servers run in the Java Virutal Machine (JVM) sandbox. They expose the standard J2EE interfaces to the application developers. Two types1 of applications can be developed and deployed on J2EE application servers – Web applications and EJB applications. These applications are deployed and executed in “container”s. J2EE specification defines containers for managing the lifecycle of server side  components. There are two types of containers - Servlet containers and EJB containers. Servlet
containers manage the lifecycle of web applications and EJB containers manage the lifecycle of EJBs. Only Servlet containers are relevant to our discussion as Struts, the theme of this book, is a web application framework.