Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Model View Controller: Free Enterprise Patterns Framework

In this article we will expand our knowledge about MVC. We will discuss about MVC patterns and its implementation.

Introduction

Before I start, I should clarify something. There are two design patterns that are generally known as “Model-View-Controller”. They are closely related, but are not the same. The elder of the two is the one described in the book Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (commonly referred to as “Gang of Four” or “GoF”). In this pattern, View objects monitor a Model using the Observer pattern so that they are notified when the Controller objects introduce changes to it. This is not the pattern I am discussing. The Model-View-Controller architecture used by many web application frameworks has a slightly different structure. In order to adapt the pattern for the stateless nature of web applications, the relationship between the components has changed slightly:

The Model is still the same as it ever was, a representation of the basic data that makes up the system being interacted with. It no longer needs to support the Observer pattern, however, as we will not be using it like that anymore.

The Controllers adopt an extra responsibility: as well as performing any updates that are required to the Model, they must also select an appropriate View to present to the user, extract any Model data that is required by the View and pass control to the View.

The View no longer actively monitors the Model, so like the Model no longer needs to implement Observer, but is instead purely reactive to being invoked by the Controller.

This article expands our knowledge about MVC. It also uses the Spring framework with a method that I described in Servlet dependency injection with Spring.

Refactoring to the Model-View-Controller pattern

At its heart, implementing the MVC pattern for web applications is extremely simple. Taking an example servlet from the previous article, the changes required are quite simple:

  • We are already using Model objects, which we load via Data Access Objects.
  • The servlet class is performing the roles of Controller and View already. We simply need to separate these, and take advantage of the separation to rewrite them using more appropriate techniques for their two functions.

Because we separate all interaction with the model from the presentation of the results to the user, the View object is free to be changed from standard Java code to something more focussed on data presentation. We could, in fact, use any suitable templating or HTML rendering library for the view. For this article, I have decided to use JSP as the view rendering system. This is because it is simple, demonstrates effectively the techniques required, and I suspect most of my readers will already be familiar with its operation. You could however easily substitute Velocity, FreeMarker, or any other Java templating system you prefer.

Having decided how we’re going to render the view, the next thing is to work out what information it is going to need. This is often very simple: for example, the controller for the “customer list” action needs to provide a list of all customers to the view – this is readily available from a single method call to the Customer Data Access Object. The data needs to be transferred from the controller to the view, and forunately the Servlet API provides an ideal mechanism for doing this: request attributes. I can create any objects I want and then insert them into the request by calling HttpServletRequest.setAttribute(“attributeName”, value), and the results are easily accessible to the view (e.g. using JSP Expression Language, I can just use ${attributeName} to get the value object).

This just leaves the final item in the Controller’s responsibility, which is to say performing any necessary changes in the model. This is also quite simple. I tend to use a pattern where any controller that makes changes to the model does not actually render a view, but rather redirects the request to another controller that does render a view. This is done using an HTTP-level redirect, because by doing so I can cause the browser to forget the data it sent to the controller via a POST request, thus avoiding those annoying messages you get on some sites when you use the back button saying you have to resubmit the request to see the page.

So now we’ve worked out everything we need to know, let’s look at some code. Here’s a simple Controller for making a change to the model (creating a new Customer):

Listing 1: The NewCustomer controller

 
publicclassNewCustomerextendsHttpServlet
{
	privateCustomerDAOcustomerDAO;
	publicvoidsetCustomerDAO (CustomerDAOcustomerDAO)
{
	this.customerDAO = customerDAO;
}
	
	@Override
	protectedvoiddoPost (HttpServletRequestreq, HttpServletResponseresp) 
throwsServletException, IOException
	{
		Customer c = newCustomer();
		c.setName (req.getParameter ("name"));
		try
		{
			customerDAO.create (c);
	}
catch (SQLException e)
{
thrownewServletException (e);
}
		resp.sendRedirect ("customers");
	}
}

Notice that in this case (because we are not using a View directly) the code is no different to a straightforward Servlet implementation.

Controllers that present a View are no more difficult. Here’s the CustomerList controller:

Listing 2: Listing customers

 
publicclassCustomerListextendsHttpServlet
{
	privateCustomerDAOcustomerDAO;

	publicvoidsetCustomerDAO(CustomerDAOcustomerDAO)
	{
		this.customerDAO = customerDAO;
	}

	@Override
	protectedvoiddoGet(HttpServletRequestreq, HttpServletResponseresp)
			throwsServletException, IOException
	{
		try
		{
			req.setAttribute("customers", customerDAO.getAll());
			req.getRequestDispatcher("/templates/customers.jsp")
.forward(req, resp);
		} 
catch (SQLException e)
		{
			thrownewServletException(e);
		}
	}

}

This just leaves the View implementation, which is in the /templates/customers.jsp file referred to in the call to getRequestDispatcher above. This is just a simple JSP page that renders the customer list as HTML. The relevant section looks like this:

Listing 3: The View for the customer list

<table>
<tr><th>Id</th><th>Name</th><th>Action</th></tr>
<c:forEachvar="customer"items="${customers}">
<tr><td>${customer.id}</td><td><c:outvalue="${customer.name}"/></td>
<td><a href="customerDetails?customer=${customer.id}">Details</a></td></tr>
</c:forEach>
</table>

To use a framework or not?

As you can see, implementing MVC without a framework is very easy. You might therefore query whether or not you need the framework. But many frameworks do provide significant advantages:

  • Easy-to-customise URL mapping schemes
  • Integrated transaction support (although see my article Spring transaction handling - transaction-per-request with AOP for an easy way to add this yourself using facilities provided by the Spring dependency injection framework that I used to set up these servlets)
  • Integrated authorization support (although this is not hard to do with the same facilities of Spring that I used for the transaction handling in the above article)
  • Other facilities like data binding, automatic code generation from the database, and so on can also make the process of building a site much faster.

To gain these things, you sacrifice a little clarity in how your application works and little bit of flexibility. Is it worth it? I’ve worked on significant projects both ways, and in the end it doesn’t seem to make a lot of difference. I spend about the same amount of time either fighting the frameworks to make them work the way I want or implementing basic functionality that a framework might provide for me. But maybe that’s just me, and you might find a framework much easier because it fits well with how you structure your applications. The only thing I can suggest is experimenting and finding the way that is best for you.

This is all for this article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login