Showing posts with label jsp java. Show all posts
Showing posts with label jsp java. Show all posts

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).

Thursday, July 1, 2010

A JSP limitation: You can't share JSP files between web applications

This one has been a real frustration of mine:  Say you have a couple of Java Servlet/JSP web applications.  Each of these applications shares common jsp files.  For example, a login.jsp page, header.jsp and footer.jsp, etc.  There is no "easy" way to package these common jsps into a jar and have each web application share these jsps.

There are a couple of workarounds:
  1. Manually convert the jsp into a servlet.  This one is a hard one, and it results into a lot of request.getWriter().print() statements into your servlet.
  2. Pre-compile the jsp into a servlet, and then package the servlet into a jar.  Then map the servlet into the web.xml file.
With method 1, it is easy to make changes.  With method 2, it is hard since the most jsp compilers produce difficult to manage code.