|
What is MVC?
Some call it a design pattern, others call it a best
practice. I’m pretty content to
describe it as a darned good philosophy for putting together your applications.
The basic idea behind MVC, Model View Controller, is that when
you develop your applications, you should split the application development
project into three distinct segments:
Fa
Model
Fa
View
Fa
Controller
So, what is a View?
A view is probably best described as a window into your
application. The view can display data
to the user, request input from user, and provides the overall look of the
application.
In our web based application, the view is usually the web page we
can see in our Internet browser; the view is the markup language that gets
displayed in the web browser, the screen of an internet enabled cell phone, or
the face of our personal data assistant (PDA).
What is the model?
The model is our business logic.
Enterprise applications have to do innumerable crazy things such as
interacting with back end databases, plopping messages on message queues,
interacting with CICS server and all sorts of other things that are needed to
successfully respond to a clients request.
This requires some real razzle-dazzle code, and all of this Java voodoo
is best kept away from your view and your controller, and factored out into
separate Java components know as your model.
How do we interact with a database? How do we add a message to a message queue? How do we efficiently
pass data across network from one EJB to another? All of these problems should
be addressed by reusable Java components, which make up the model of an
application.
So the view is responsible for generating a handsome look for our
application, and we have all of these great business components in our model
that implements our business logic. The
last piece of the puzzle is the controller.
What is the controller?
The controller is designed to handle the initial client
request, extract input from the user
and kick off the execution of business logic required to process the
request.
Input Validation
The controller might validate user input. Making sure that a user has filled in all of
the required text fields and supplied a properly formatted email address is the
job of the controller.
Request Validation
The controller will also make sure that a users request is a
valid request. For example, a user
might have book marked a page that displays the value of their stock portfolio.
Of course, if the user logs out and then comes back to that page later, we need
the user to log in so we can display the portfolio of that particular
user. A controller will make sure a
user has logged in and visited the appropriate pages the lead up the current
request being made on the server.
Delegation to Business Components (Model)
The controller will also be responsible for figuring out which
model components need to be used to implement the current request. If a user needs to read data from a
database, the controller will call upon business components that do JDBC. If a user needs to read from a message
queue, the Servlet will call on model components that have been designed to
implement messaging.
Flow Control
And depending upon whether the client request is valid, and
whether all of the business objects that have been invoked execute
successfully, the Servlet will figure out which view component to display to
the user.
The MVC Home Heating System
A great example of a MVC application is your home heating
system. Just think about it.
The Thermostat Controller
The thermostat, that little thing on the wall that you twist or
turn to indicate what you want the temperature in your home to be is the
controller. You control the temperature
in your home by using the thermostat.
Furthermore, the thermostat does input validation as well. After all, you can’t lower the temperature
to absolute zero, and you can’t set the thermostat so high that it will boil
the air around you. The controller only
allows you to put in certain values from about 55 to 80.
The Furnace as the Model
And does the thermostat warm up your house? Not a chance. The thermostat delegates that work to the model, or should I say,
the furnace. The furnace burns and
burns until finally the controller tells it has burned long enough. The controller is responsible for validating
user input, and subsequently delegates work to model components.
Supporting Multiple Views
So, what is the view?
Well, the view could be many things. Remember how we said that one of
the benefits of MVC is the multiplicity of views?
We said that we could create an application that supported HTML
clients, but quite easily add support for WML, HDML or cHTML clients if we
properly designed our applications around the tenets of good MVC. The home heating system is no different when
it comes to the MVC benefit of supporting multiple views.
You may have a thermometer attached to your thermostat. That could be the view. You could have one of those Newtonian
thermometers that float glass bulbs depending on how hot or cold it is. Heck, the number of sweaters your sister
Sally is wearing could be an indication of how hot or cold the house is, so that could be considered a potential view
as well.
The home heating system is a perfect example of a MVC
architecture. Furthermore, it
demonstrates some of the most important benefits of MVC as well.
Problem Isolation
I know that it’s not something one likes to think about, but say
your furnace happens to breaks down. Are you going to replace your
thermostat? Of course not - you fix the
furnace.
In fact, maybe you just want to switch from oil to gas, or you
want to add an air conditioner for those hot and muggy summer days. All of these additions and upgrades to your
model can occur independently from your view and your controller.
A good MVC architecture isolates problems, makes debugging
easier, and makes it possible to plug components in and out of one layer
without effecting components in other layers.
So a good MVC home heating system allows me to fix, upgrade or replace
my furnace while leaving my thermostat and thermometers alone.
Pluggability
In my house, my crazy Dad always turns the temperature down at
around eleven at night, and then gets
up at around five in the morning and turns the heat up so the house is nice and
warm when my Mom and I get up at around noon.
Of course, if I was a generous son, I could buy one of those new
digital thermostats that automatically change the temperature depending upon
the time of the day. May Dad could stay
in bed, and my Mom and I wouldn’t get woken up at five in the morning every
time my Dad goes down to fiddle with the thermostat. Again, MVC affords us pluggability. I can swap out one controller, throw another controller in, and
it doesn’t effect any of the other components.
Division of Labor: Parallel Development
Division of labor is also a great benefit of MVC. If I need a home heating system, I can have
people developing the thermostat, knitting sweaters for my sister, and building
a furnace concurrently. Parallel development is what we call that, and it helps
your applications get to market faster.
Furthermore, we can apply appropriate skills to appropriate
tasks. I don’t want grandma building a
furnace, and I don’t want that furnace guy knitting a sweater for my sister.
People can concentrate on what they do best, and the best cohesive product will
be developed in the end.
Support for Multiple Views
Even the fact that I can tell how hot or cold it is in various
different ways demonstrates a massive benefit of MVC design.
Think about your applications.
You may have one database that stores information. There are probably a common set of steps
users have to go through to get access to that information. These steps, or
flow, can easily be managed by the controller. But users might want this data
in many different forms.
Clients might want to view data in a web page that displays HTML,
they may need to see that data using WAP on a palm pilot, or they may even want
it as an image or a pdf file. If we’re using good MVC, our applications will be
able to easily adapt to the changing needs of our end users.
How does J2EE support MVC?
The nice thing about J2EE is that it fits perfectly into a model-view-controller
framework.
Servlets act as our controller.
Servlets are intended to handle incoming requests, make sure the request
is valid, and delegate to various model components to do work.
As far as model components go, those are our JavaBeans and EJBs. Those are the components that do the tough
work for us and implement the business logic required to fulfill a client
request.
Finally, when a Servlet is finished calling on various JavaBeans
and EJBs, it calls on a Java Server Page (JSP) to generate some markup for the client, also known as a view.
In a J2EE environment, we can have our best web page and graphic
designers creating the JSP pages, the database and transactionally aware Java
Gurus creating our EJBs, and our senior Java developers gluing everything
together with an effective use of Servlets and the occasional JavaBean.
A clear separation of roles, parallel development, and a modular
application where components can easily be plugged in and pulled without
negatively effecting other layers of our program are just some of the benefits
we garner from developing good model view controller applications..
How do frameworks like struts fit into this MVC framework?
One of the most difficult parts of developing an enterprise
application is developing the controller.
Developing the controller means not only controlling how a user
transitions from one page to another, but it must also make sure any data a
user is sending to the server is valid. If a user is sending garbage to the
server, a good controller will provide useful, internationalized error messages
where appropriate.
Struts has always been a controller centric framework
The Struts framework provides a built in mechanism for form
validation and error handling, removing the burden of developing an error
identification and error notification system from the developer. Struts helps
facilitate the development of good, robust controllers.
Struts is a fantastic, open source framework, that is incredibly
pervasive, and it will make many of the routine tasks you really hate doing a
little bit easier, but don’t be fooled:
it won't revolutionize the way you program.
So, what does Struts do for us?
Struts solves very common development problems. It doesn't solve every problem, but it does
address a few problems that arise over and over again in our J2EE applications.
First of all, Struts provides a great mechanism for handling user
input. Struts makes it very easy to
validate any data a user might have typed into a form and submitted to the
server. Form handling and input
validation is always a stabbing pain in the neck. The Struts framework provides a fantastic form validation
mechanism that reduces this stabbing pain to a much more tolerable throbbing
sensation.
Struts solves very common problems
Secondly, Struts provides a relatively simple mechanism for
providing feedback to a user. Not only does Struts help weed out bad input
data, it also provides a mechanism for telling the user what it is they did
wrong, so they can resubmit their form with something different filled out
wrong.
Furthermore, if your user's preferred language is German, it
would be nice to send error messages back to your user in German. Actually, always sending error messages back
to users in German isn't a bad idea in itself.
Instructions always seem so much more authoritative when relayed in
Deutch. But the point is, Struts
provides some great facilities for internationalizing your applications as well
- not just error messages, but every single text string in your application.
Now don't get overly excited by this whole internationalization
thing. Struts will do
internationalization, but it does not do translation. Struts is not a translation server. If you have written your application in English, you will still
have to hire a French linguist to translate the whole site so it can be
understood by les Quebecois. You'll
also have to have it all translated into Spanish so it can be read by
Americans. Struts doesn't do
translations, but it will recognize the preferred language of the client, and
send appropriately translated text back to the client.
“Struts does internationalization, not translation”
Struts also forces the developer to use good MVC, or as it’s
affectionately know, Model View Controller.
We’ll get into MVC later, but suffice to say, MVC is simply a darned
good best practice, and Struts makes sure your developers stick to it.
Struts even provides a few neat custom tags that help the
developer generate HTML to send to the client.
The Struts custom tags become especially handy when generating HTML
pages that include internationalized error messages. Other logic custom tags exist as well, although in my personally
opinion, the Struts logic custom tags can be as aggravating as the scripted
Java code they are intended to replace.
The latest incarnation of the Struts framework, version 1.1,
introduces a fantastic new element called Tiles. While much of the Struts framework deals with controlling the
flow of your application, Tiles provides some fantastic features for assembling
complex web pages from much smaller html and JSP snippets. The Tiles portion of the Struts framework
provides a sweet mechanism for assembling web pages that quite simply was
lacking in earlier versions.
Struts also provides features for handling database connection
pools. This facility was quite helpful
back in the dinosaur ages when application servers didn't provide robust
connection pooling services, but if you're deploying to WebSphere or any other
J2EE compliant application server, using the Struts connection pooling services
will only cause you problems. Stay away
from them.
So, here's what Struts does for you:
F-helps
with input validation
F-helps
provide user feedback
F-helps
internationalize our applications
F-enforces
a good MVC design pattern
F-provides
a collection of semi-useful custom tags
F-facilitates
html development through Tiles
F-provides
a common framework
So, that's it. Struts
doesn't write any code for you. It
doesn't solve your performance problems.
Struts isn't a rapid development environment. But Struts does address five or six very specific areas of
application development that are often neglected, done poorly and implemented
inconsistently across the enterprise.
By addressing issues such as form validation, error feedback and
internationalization, Struts allows developers to concentrate on the more
pressing aspects of application development
What is cocoon?
Cocoon is the most powerful, most amazing, most awesome open
source framework on the market, although I may be a little biased
Cocoon adds a new letter to MVC. Cocoon adds a D.
The D in MVCD stands for data, and that’s exactly what cocoon is,
a data centric framework.
Cocoon figures that when a client comes to you website, they’re
interested in data. Instead of using JSPs to generate HTML, Cocoon uses XSPs to
generate data marked up in an XML document.
An XSL transition then converts that XML into any markup language your
client want.
Cocoon adds a ‘D’ to MVC
Get a Cocoon application that serves up HTML pages, and in about
five minutes you can have that same application coughing up PDFs, WML, HTML,
even gifs of what the html would look like.
The Cocoon framework is awesome, and every time I use it, I’m
amazed at how mature and robust it is.
The biggest drawback for Cocoon is the fact that it uses XLS
transitions extensively, and XSL transitions can be slow. Cocoon is fairly
resource intensive. Still, if you have
the hardware, think about adopting it as a framework – it is powerful.
|