Wednesday, June 15, 2011

An MVC Checklist (Java)

Model-View-Controller (MVC2) and Model-View-Controller 2 (MVC2) are the de-facto patterns to use when developing Java and .NET web applications.

Here is a checklist to follow in order to apply the MVC pattern in Java:
  1. Each of your JSP page (the View) has a corresponding servlet (the Controller).
  2. Your database objects are mapped to "Model Objects", usually POJOs that mirror the database structure to Java Objects. (the Model).
  3. From your web application pages, you have no direct html links to your JSP pages. Instead, your links point to the corresponding servlet of each JSP page.
  4. Each JSP page posts back to its Controller servlet. In other words, the <form&ht; tag on your JSP page has the action attribute set to the Controller servlet url.
    Example: <form method="POST" action="/myServlet">
  5. Each Controller Servlet handles/checks for "actions" and after processing, forwards or redirects to the JSP View Page. Here are some standard Controller Servlet actions:
    • "edit": where the Controller Servlet calls the Model which loads a record from a database based on same criteria, and then forwards to the JSP View page. The record is shown to the user available for editing.
    • "save": where the Controller Servlet loads data from the Http Request to the correspondind Model Object, calls a save routine and then forwards to a JSP View page.
    • "create": where the Controller Servlet calls the correspondind Model Object's create method, and then forwards to a JSP View page. This is where our uses can create new records.
    • "delete": where the Controller Servlet calls the corresponding Model Object's delete method, and then forwards to a JSP View page. This is where our uses delete records.
Here is the MVC diagram: (source: Wikimedia Commons)
The solid line represents a direct association, the dashed an indirect association (via an observer for example).

No comments:

Post a Comment