Tuesday, April 10, 2007

Why Is Model-View-Controller So Important?

The MVC architectural pattern is not directly related to web applications. In fact, it's quite common in Smalltalk applications, which generally have nothing to do with the Web.

As we saw in the previous section, the Model 2 approach is concerned with separating responsibilities in web applications. Allowing a JSP page to handle the responsibilities of receiving the request, executing some business logic, and then determining the next view to display can make for an unattractive JSP page, not to mention the maintenance and extensibility problems this entanglement causes. Application development and maintenance are much easier if the different components of a web application have clear and distinct responsibilities.

As an example, say you want to integrate security into your web site. Your first page, in this case, usually is a login screen that collects and validates the username and password. This page then directs the user to another screen that allows her to continue in a secure manner. However, as there is nothing to prevent the user from going directly to a page, each page (in a non-MVC world) needs to be aware of security. This can be accomplished by including a security check on every page, but that can be unwieldy, especially if there are some pages that need to be secure and some that do not. In the MVC world, the security is put inside the controller object. Because the interface to the customer is driven through the controller object, there is a single entry point and a single location for the security checks to be performed.

The MVC pattern is categorized as a design pattern in many software design books. Although there is much disagreement on the precise definition of the pattern, there are some fundamental ideas.

The MVC pattern has three key components:

Model

Responsible for the business domain state knowledge

View

Responsible for a presentation view of the business domain

Controller

Responsible for controlling the flow and state of the user input

With the MVC pattern, a form of event notification usually takes place to notify the view when some portion of the model changes. However, because a browser in a typical web application has a stateless connection, the notification from the model to the view cannot occur easily.[2] Of course, an application could perform some type of push mechanism to push notification or data all the way to a client, but this is overkill for most web applications. A user can close the browser at any time, and generally no notification is sent to the server. A great deal of overhead is necessary to manage remote clients from the server side. This type of behavior is not necessary for typical B2C and B2B web applications.

[2] Web applications are considered stateless because the browser doesn't maintain a constant open connection to the web server. However, a web application still may maintain session data for a user or even store data within the browser on behalf of the user.

With standard web applications, a client typically sends another request to the server to learn about any changes to the model. This is known as a "pull" approach. For example, if a user is viewing pricing information for an item and at the same time the administrator changes the price for that item, the user will not know it changed until he refreshes the page.

1.5.1 The MVC Model

Depending on the type of architecture your application uses, the model portion of the MVC pattern can take many different forms. In a two-tier application, where the web tier interacts directly with a data store such as a database, the model classes may be a set of regular Java objects. These objects may be populated manually from a ResultSet returned by a database query, or they may be instantiated and populated automatically by an object-to-relational mapping (ORM) framework such as TopLink or CocoBase.

In a more complex enterprise application (where the web tier communicates with an EJB server, for example), the model portion of the MVC pattern will be Enterprise JavaBeans. Although the EJB 2.0 specification made performance improvements through the use of local interfaces, there still can be a significant performance impact if the web tier attempts to use entity beans directly as the model portion of the application, due to the overhead of making remote calls. In many cases, JavaBeans are returned from session beans and used within the web tier. These JavaBeans, commonly referred to as data transfer objects or value objects, are used within the views to build the dynamic content.

1.5.2 The MVC View

The views within the web tier MVC pattern typically consist of HTML and JSP pages. HTML pages are used to serve static content, while JSP pages can be used to serve both static and dynamic content. Most dynamic content is generated in the web tier. However, some applications may require client-side JavaScript. This does not interfere with or infringe upon the MVC concept.

HTML and JSP are not the only choice for the view. You easily can support WML, for example, instead of HTML. Because the view is decoupled from the model, you can support multiple views, each for a different client type, using the same model components.

1.5.3 The MVC Controller

The controller portion of the web tier MVC design generally is a Java servlet. The controller in a web tier application performs the following duties:

1. Intercepts HTTP requests from a client

2. Translates each request into a specific business operation to perform

3. Either invokes the business operation itself or delegates it to a handler

4. Helps to select the next view to display to the client

5. Returns the view to the client

The Front Controller pattern, which is part of the Java 2 Platform, Enterprise Edition (J2EE) Design Patterns (found at http://java.sun.com/blueprints/patterns/index.html), describes how a web tier controller should be implemented. Because all client requests and responses go through the controller, there is a centralized point of control for the web application. This helps when adding new functionality. Code that would normally need to be put in every JSP page can be put in the controller servlet, which processes all the requests. The controller also helps to decouple the presentation components (views) from the business operations, further aiding development.

JavaServer Pages

The first thing to understand about JavaServer Pages is that it's a natural extension to the Java Servlet technology. In fact, after some preprocessing by a translator, JSP pages end up being nothing more than Java servlets. This is a point that many beginning developers have a hard time understanding. JSP pages are text documents that have a .jsp extension and contain a combination of static HTML and XML-like tags and scriptlets. The tags and scriptlets encapsulate the logic that generates the content for the pages. The .jsp files are preprocessed and turned into .java files. At this point, a Java compiler compiles the source and creates a .class file that can be executed by a servlet container.

The translator that turns the .jsp file into a .java file takes care of the tedious work of creating a Java servlet from the JSP page. Figure 1-2 illustrates how a JSP page is translated and compiled into a servlet.

Figure 1-2. A JSP page is translated and compiled into a Java servlet

figs/jstr_0102.gif

JSP technology has become an extremely popular solution for building web applications using the Java platform. JSP offers several advantages over its competitors:

· JSP is a specification, not a product. Developers are able to choose a "best of breed" approach.

· JSP pages are compiled, not interpreted, which can lead to better performance.

· JSP pages support both scripting and access to the full Java language and can be extended through the use of custom tags.

· JSP pages share the Write Once, Run Anywhere™ characteristics of Java technology.

As mentioned in the previous section, one of the limitations of using hardcoded HTML inside of servlets is the problem of separating page design and application logic programming responsibilities. This separation is easier with JSP pages, because the HTML designers are free to create web pages with whatever tools they choose (many of today's popular tools are capable of working with JSP and custom tags). When they are comfortable with the page layout, the JSP developers can insert JSP scriptlets and custom tags and save the files with a .jsp extension. That's pretty much all there is to it. When the time comes to change either the page layout or page logic, the developer modifies the JSP page as needed and allows it to be recompiled automatically.

Together, JSP pages and servlets are an attractive alternative to other types of dynamic web programming. Because both are based on the Java language, they offer platform-independence, extensibility into the enterprise, and, most importantly, ease of development.

JSP Scriptlets or Tag Libraries?

Many developers believe custom tags, rather than scriptlets or expressions, should be used in JSP pages. The rationale is:

· Scriptlets mix logic with presentation.

· Scriptlets break the separation of roles.

· Scriptlets make JSP pages difficult to read and maintain.

Custom tags, on the other hand, centralize code in one place and help maintain the separation of responsibilities. They also support the concept of reuse, as the same tag can be inserted into multiple pages while the implementation resides in a single location. There also is less redundancy and potential for copy-and-paste errors with custom tags.

What Are Java Servlets?

Java servlets have become the mainstay for extending and enhancing web applications using the Java platform. They provide a component-based, platform-independent method for building web applications. Servlets don't suffer from the same performance limitations that standard CGI applications incur. Servlets are more efficient than the standard CGI threading model because they create a single heavyweight process and allow each user request to use a much more lightweight thread, which is maintained by the Java Virtual Machine (JVM), to fulfill the request. Multiple user requests can be threaded through the same instance of a servlet. A servlet is mapped to one or more uniform resource locators (URLs), and when the server receives a request to one of the servlet URLs, the service method in the servlet is invoked and it responds. Because each user request is associated with a separate thread, multiple threads or users can invoke the service method at the same time. This multithreaded nature of servlets is one of the main reasons that they are more scalable than standard CGI applications. Also, because servlets are written in Java, they are not proprietary to a platform or OS.

Another significant advantage of being written in the Java language is that servlets are able to exploit the entire suite of Java application programming interfaces (APIs), including Java DataBase Connectivity™ (JDBC) and Enterprise JavaBeans (EJB). This was one of the factors in servlets becoming part of the mainstream so quickly; there already was a rich Java library in place for them to leverage.

Servlets are not executed directly by a web server. They require a servlet container, sometimes referred to as a servlet engine, to host the servlet. This servlet container is loosely coupled to a particular instance of a web server, and together they cooperate to service requests. Figure 1-1 illustrates how a web server and servlet container cooperate to service a request from a web browser.

Figure 1-1. Processing a client request

figs/jstr_0101.gif

Developers are free to choose from one of many servlet containers available to host their servlets; they are not locked into a particular vendor or platform. Servlets can be ported to any of these containers without recompiling the source code or making any changes. This leads to a "best of breed" solution for web applications—you get the best product or component for a specialized need, while at the same time avoiding the high risk normally associated with a single solution.

There are several popular servlet containers on the market. Some are standalone servlet containers that must be connected to an external web server to work, while others provide both the web server and servlet container in the same product. There are even a few that are integrated into application servers and provide much more functionality than just a servlet container. Table 1-1 lists some of the more popular servlet containers. Some of the products are commercial products and some have a small or insignificant cost to use.

Table 1-1. Popular servlet containers

Servlet container

URL

Bluestone

http://www.bluestone.com

Borland Enterprise Server

http://www.inprise.com

iPlanet Application Server

http://www.sun.com/software/iplanet/

Orbix E2A (formally iPAS)

http://www.iona.com

Jetty

http://www.mortbay.com

JRun

http://www.macromedia.com/software/jrun/

Orion Application Server

http://www.orionserver.com

Resin

http://www.caucho.com

SilverStream

http://www.silverstream.com

Apache Tomcat

http://jakarta.apache.org/tomcat/

Weblogic Application Server

http://www.bea.com

WebSphere

http://www-4.ibm.com/software/webservers/appserv/

EAServer

http://www.sybase.com

For a more complete listing of available servlet containers, visit Sun's servlet industry momentum web site at http://java.sun.com/products/servlet/industry.html.

Although servlets are great at what they do, it quickly became apparent that hardcoding HyperText Markup Language (HTML) output in a servlet as a response to a request had some serious limitations. First and foremost, it was hard to make changes to the HTML because for every change, a recompilation of the servlet had to take place.

Secondly, supporting different languages is difficult because the HTML is hardcoded. Determining the user's language, region, and optional variant and then displaying the output is not easily accomplished. Many web applications built with servlets avoid the entire issue of internationalization[1] by having different servlets, one for each supported locale.

[1] Internationalization is commonly referred to as "I18N" because the word begins with the letter I, ends with the letter N, and contains 18 characters in between.

Finally, because HTML was embedded within the servlet, there was a problem with responsibility. Web designers build HTML pages; they are not usually experienced with Java programming, let alone skilled at object-oriented design and programming. When you mix HTML and Java code within the servlet, it becomes hard to separate the page design and programming duties. Even when a developer has the necessary skills to perform both functions, modifications to the page layout require recompilation, which adds to development and testing time.

Servlet programming is such a broad topic that it can't be covered in great detail here. If you feel that you need more information on Java Servlet technology, a great source of material is Jason Hunter's Java Servlet Programming (O'Reilly). You can also find more information at the Sun Servlet web site (http://java.sun.com/products/servlet/index.html).

JavaServer Pages was the next step in the linear progression of developing web technologies based on the Java platform. The introduction of JSP pages, as they are commonly referred to, helped to alleviate the servlet limitations mentioned earlier and opened up many new doors for web developers.

First Look: Mozilla Thunderbird 2

New Thunderbird adds ability to tag multiple e-mail messages.

Erik Larkin, PC World

Monday, April 09, 2007 09:00 AM PDT

If you like Thunderbird 1.5, you'll love version 2, now available as a near-final release candidate. Like the new Firefox 2, Thunderbird 2 doesn't introduce any radical changes. But it does introduce inherently useful upgrades that will boost your productivity, particularly if your inbox overflows with e-mail.

The release candidate download is now available from Mozilla's site. I've been using version 2 every day since beta 2's release in January. Though the program is not yet final, I've found it stable and up to the task of handling my daily e-mail chores. Making the switch is easy: Thunderbird 2 maintains all your filters and account settings, and you shouldn't have any problem jumping right into it. Like previous versions, Thunderbird 2 has a clean and straightforward interface that makes good use of available screen space.

Click to view full-size image.

One of the first things I noticed: mail pop-up alerts, one of Thunderbird's new features, which list the subject and sender of newly received messages in the lower-right corner of your screen and automatically fade after a few seconds. Each pop-up provides enough information on the latest few unread messages for me to decide whether I need to interrupt what I'm doing to switch to Thunderbird and read the e-mail.

As convenient as the mail pop-ups are, the introduction of tags in Thunderbird 2 is an even bigger boon for organizing messages. Tags replace the previous versions' labels function, which allowed you to assign just one of a handful of premade labels, such as 'Personal' or 'ToDo', to each message. Now, you can create an unlimited number of tags, and you can give any e-mail multiple tags.

Click to view full-size image.

Creating on-the-fly tags for any new topic does wonders for managing an ever-growing inbox. For example, I track antivirus news and products, so I created a new tag called 'antivirus'. A right-click lets me assign the new tag to any e-mail, and I can then quickly view only those tagged messages. I found right-clicking faster and cleaner than the typical method of creating a new folder for all such messages and then manually adding those messages to the folder. The feature is also particularly useful when combined with saved-search folders that show all messages with a particular tag (but keep your e-mail in one inbox). In the release candidate, however, the new tags have a few rough edges. For example, I changed the name of the default 'Personal' tag to 'PCW', but a filter I migrated from Thunderbird 1.5 still assigns 'Personal' to many messages. Also, when I assign multiple tags, Thunderbird seems to randomly select which tag's color it will use for the message; it doesn't allow me to designate a dominant color.

Brand-new in this release candidate is a Gmail account preset that fills in almost everything (server name, etc.) automatically when you configure Thunderbird to read your Gmail messages. You need only provide your name (for display) and account. The default settings will leave the messages on Gmail's servers so you can read them through both Thunderbird and Gmail.

The release notes list the same functionality for a .Mac account, but (not surprisingly) I didn't see such an option in my Windows version; it may show up only in the Mac software.

Other notable tweaks to Thunderbird include better customization options for viewing folders, and find-as-you-type searches. See the release notes for a full list of changes.

Unfortunately, Mozilla doesn't seem to have significantly improved its junk-mail filters, and my inbox still has plenty of spam. Also, Thunderbird still lacks a built-in calendar; however, a terrific and easy-to-use add-on called ReminderFox adds some basic calendaring functions, such as reminders to revisit a particular e-mail by a certain time.

Though Thunderbird 2 is not yet a final release, I found that the release candidate's new features and overall stability more than warrant your making it your primary mail client.