Architecture & DesignApplying MVC to Web-Based Applications with Generic Views

Applying MVC to Web-Based Applications with Generic Views

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The business world is heavily investing into the evolution of their services and product lines; both presentation and customer interaction are becoming Internet centric. Corporations are establishing a Web presence to attract new customers, diversify, and simplify its interaction with its existing customer base, ease business-to-business communications, or to simply put a new face on an old service. Today, practically every bank offers online banking; every financial institution, brokerage house, and hedge fund is rewriting their trading systems to allow global access and trading from any internet-enabled location. Airline, defense, pharmaceutical, document management, and other industries are all adding Web interfaces to their business models.

This rapid emergence of Web-based services and applications caused a tremendous growth in the Web application development area. Existing programming methodologies, design patterns, and code libraries have been reapplied (or rewritten) to make them pertinent to Web-based applications. Even entire frameworks have been created to decrease development time, ease maintenance cycles, and simplify coding of online applications. Because the Model-View-Controller (MVC) design paradigm’s main purpose is to separate business logic from presentation and because it’s flexible enough to be incorporated into any type of application, it was a prime candidate for adaptation in Web-based applications and services. Apache‘s software foundation project Struts is actually a framework implementation of MVC in Java, and the FuseBox project is another implementation of MVC in multiple Web technologies: ColdFusion, PHP, Java, ASP, and Lasso.

In my last article (Creating Dynamic Swing Views with Reflection by Extending MVC), I described how to apply MVC to a Java Swing application to dynamically generate JTabbedPane views by using Reflection and briefly described the history of the Model-View-Controller; in this article, I’ll show how to use MVC in a Web-based project. My controller will rely on Reflection API to dynamically call action methods, redirect to proper views, and coordinate data flow between presentation and model layers.

Because it will be a Web-based project, I will use Servlets for server-side processing and controller implementation, Java Beans for the model layer, and JSPs as a presentation layer. If you are not familiar at all with Servlets, JSPs, and J2EE component development, please first read the referenced tutorials at the end of this article.

In order to test my project or if you want to use it as a backbone for a larger program, you will need to configure the J2EE compliant application server. I use the freely available Tomcat, but in an enterprise environment you will probably use IBM WebSphere or BEA WebLogic as commercial J2EE application servers with EJB and JSP containers. The setup of application server is beyond the scope of this article, but project’s source is packaged as a J2EE—compliant application WAR (Web archive) file with all necessary XML deployment descriptor files; so, to run it on a configured server, all you’ll need to do is drop it in an appropriate place. Also, if you feel like investing a bit more time and not writing your own Controller layer, you may want to look at the Apache Struts framework, which also comes with a huge JSP tag library for all sorts of functionalities you may need.

Project

To show how to use MVC in a Web-based application, I’ve created a simple project consisting of several JSP Views—viewable in any web browser—several helper bean and action classes, and a Servlet controller class. The business objective will be to display weather information based on the user’s ZIP code or city name. The project’s structure is generic enough to make it easily modifiable for any type of larger online application. Enterprise-level applications usually have a database in the back end, to fetch dynamic data for the views, comprising a so-called three-tier architecture—client application, server processes, and enterprise data services; in my case, hoverer, all data info will be stored in a HashMap object.

Architecture Overview

Code Listings

Listing 1

public void

 doPost(HttpServletRequest req,HttpServletResponse res)
  

throws

 ServletException, IOException{
    res.setContentType(

“text/html”

);
    String action = (String) req.getParameter(

“ACTIONKEY”

);
    String redirect = (String) req.getParameter(

“REDIRECTKEY”

);
    ActionInterface actionInterface = null;
    HttpSession session = req.getSession();

try

 {
  String classNameStr = action.substring(0, action.indexOf("."));
  String methodName = action.substring(action.indexOf(".") + 1);
  // if action exists - get it, 
  actionInterface = (ActionInterface) actions.get(classNameStr);
  // if null - instantiate it
  

if (actionInterface == null) { className = Class.forName(“actions.” + classNameStr); actionInterface = (ActionInterface) className.newInstance(); actions.put(classNameStr, actionInterface); } method = actionInterface.getClass().getMethod(methodName, new Class[] { o.getClass(), o.getClass()}); method.invoke(actionInterface, new Object[] { req, res }); } catch (Exception e) { session.setAttribute( “msg”, “Problem in MainController Servlet doPostn” + e); System.out.println( “Problem in MainController Servlet doPostn” + e); } finally { this .getServletContext() .getRequestDispatcher(“/jsp/” + redirect + “.jsp”) .include(req, res); } }

Listing 2

public synchronized void

 viewByZip(Object reqO, Object resO) {

  HttpServletRequest req = (HttpServletRequest) reqO;
  HttpServletResponse res = (HttpServletResponse) resO;
  String zip = (String) req.getParameter("ZIP");
  String data = (String) WeatherData.getData(zip);

  

if

 (data == 

null

)
  data = "Sorry; no weather data is available for zip:" + zip;
  // fill new bean
  WeatherBean wb = 

new

 WeatherBean();
  wb.setZip(zip);
  wb.setData(data);
  // put bean in to request user's object
  req.setAttribute("weather", wb);
  }

Listing 3

<BODY>
<% beans.WeatherBean wb =
  (beans.WeatherBean)request.getAttribute("weather"); %>
<P>Weather information for <%=wb.getZip() %></P>
  <%=wb.getData() %>
<P>
<% if (session.getAttribute("msg") == null)
      { session.setAttribute("msg", "& "); } %>
<%=session.getAttribute("msg") %>
<% session.setAttribute("msg", "& "); %>
</P>
  <backTags:BackLink text="<- Back" />
</BODY>

Download source code here.

About the Author

Vlad Kofman is a System Architect currently working on projects under government defense contracts. He also has been involved with enterprise-level projects for major Wall Street firms and the U.S. government. His main interests are object-oriented programming methodologies and design patterns.

References

Java Servlet Technology by Stephanie Bodoff
http://java.sun.com/webservices/docs/1.0/tutorial/doc/Servlets.html

Sun Reflection API by Dale Green

http://java.sun.com/docs/books/tutorial/reflect/

WebSphere Studio Application Developer Version 5 Programming Guide
By Ueli Wahli, Ian Brown, Fabio Ferraz, Maik Schumacher, and Henrik Sjostrand
IBM Redbook SG24-6957-00, May 9, 2003
http://www.redbooks.ibm.com/

Core Java 2, Volume II: Advanced Features (5th Edition)
by Cay Horstmann, Gary Cornell
Publisher: Prentice Hall; 5th edition (December 10, 2001)

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories