Rumble in the jungle: J2EE versus .Net, Part 1 +2
How do J2EE and Microsoft's .Net compare in enterprise environments?
By Humphrey Sheil and Michael Monteiro
Heard a lot about .Net versus J2EE (Java 2 Platform, Enterprise Edition)? Wondering what that conflict means for you? Well, we wondered the same thing. So, drawing on our combined experiences from both sides of the fence, we put together an unbiased explanation as to how J2EE and .Net match up. Make no mistake, finding unbiased opinions is difficult—both camps' marketing hype has kicked into overdrive. This two-part series will help you better understand how the two technologies differ and how they are alike, all in the context of building a Web application from design right through to deployment. (4,500 words; June 21, 2002)
ith the advent of .Net, Microsoft introduced an enterprise computing platform able to compete toe-to-toe with Sun Microsystems' J2EE (Java 2 Platform, Enterprise Edition). Microsoft's move leaves J2EE developers with two options: ignore .Net or analyze it. In this article, we choose the latter, analyzing and comparing the two technologies.
Both platforms feature innovative ideas—ideas that should cross pollinate, not stagnate on one specific platform. Furthermore, we all want technologies that add the best business value and are cutting edge, not bleeding edge! So, which language works better—.Net's C# or Java? Is .Net poised to sweep all before it or is Microsoft's mighty marketing machine simply desperate to make you think so? Well, in this two-part series we'll dive into the technologies to find out.
Read the whole "Rumble in the Jungle: J2EE Versus .Net" series:
In this article, we first examine J2EE and .Net in turn, then line the technologies up to understand how each approaches common enterprise problems. To actualize the terms and concepts introduced here, we briefly introduce our sample application: the Ice Cold Beer Boutique. In Part 2 we will focus exclusively on its background code and architecture of both J2EE and .Net implementations.
What is J2EE?
When thinking of the Java 2 Platform, Enterprise Edition, the key word is platform. Java represents more than just a programming language, as it encompasses the VM technology that lets compiled Java programs run unaltered on various machine architectures; tools to compile, analyze, debug, and deploy Java programs; and other components, such as browser plug-ins, rich media, and more. Talk about feature creep!
The three faces of Java
About two years ago, Sun reorganized the Java platform into three profiles:
Although it's something of a simplification, you can think of J2ME as a subset of J2SE and J2EE as a superset of J2SE.
- The Java 2 Platform, Micro Edition (J2ME), for handheld and other lower-end devices
- The Java 2 Platform, Standard Edition (J2SE), targeted at desktop machines
- The Java 2 Platform, Enterprise Edition (J2EE), installed on servers and responsible for the heavy lifting in the Java world.
Our J2EE definition
Definition: J2EE is a Java-based technology stack, built on top of J2SE, that provides developers with the development tools and runtime capabilities necessary to build enterprise applications meeting rigorous uptime, security, scalability, and maintainability requirements.
The latest version of J2EE is 1.3. Sun uses the J2EE platform to synchronize the constituent technology specifications for specific releases. Here's a partial J2EE components list:
Although the following components are technically part of J2SE, they prove important for J2EE applications as well:
- JavaServer Pages (JSPs): Generate dynamic content for Web browsers and mobile devices. JSPs resemble HTML, especially when developers use custom tag libraries to remove Java code from the JSPs themselves, making them easier to maintain.
- Servlets: Build control and navigation logic into J2EE applications, typically following a Model-View-Controller design pattern in conjunction with JSPs.
- Enterprise JavaBeans (EJBs): The mainstay of the J2EE platform. There are two main types of EJB: session beans that model business logic and entity beans that model persistent data. When coded correctly, EJBs provide transparent scaling, a security framework, a transaction model, and a container-managed life cycle.
- Java Connectivity Architecture (JCA): Lets Java enterprise applications interface with existing non-Java enterprise applications like SAP. Specifically, transactions and security roles can propagate, allowing you to fully utilize legacy applications in a J2EE architecture.
- Java Message Service (JMS): Provides asynchronous messaging capabilities to the J2EE platform. Established message-oriented middleware (MOM) vendors like IBM (MQ Series) and Tibco (Rendezvous) provide JMS faces to their products.
- Java Management Extensions (JMX): Manages J2EE servers and applications.
- Java Naming and Directory Interface (JNDI): A required part of the J2EE platform, JNDI provides component location transparency in a clustered J2EE environment.
Figure 1 depicts these components as a J2EE technology stack.
- Java Database Connectivity (JDBC): The real bread and butter of any enterprise application! JDBC handles all database input/output via SQL.
- The HotSpot Virtual Machine: Can run in server mode to better profile long-running applications with stringent requirements for thread and memory management. The HotSpot VM has addressed most of the initial concerns about J2EE's performance.
Figure 1. High-level overview of the J2EE technology stack. Click on thumbnail to view full-size image.
The Java community: Spirit and ethos
In addition to these technologies, the Java platform boasts another important feature: the Java developer community.
With Java, you'll find free, open source tools, such as Ant (a build tool), JUnit (a testing framework), JBoss (an application server), and NetBeans (an integrated development environment, or IDE). More exist—SourceForge lists hundreds of Java-related initiatives.
Moreover, look at the curriculum for any third-level teaching institution. In many such schools, students learn programming by studying Java. The same phenomenon pushed Unix from a 1970s research curiosity to the operating system that it is today. What's my point? The students of today are the programmers of tomorrow, and they are learning in Java and Unix.
What is .Net?
So what exactly is .Net? Unlike J2EE's specification set, .Net is a suite of shipping products (although some parts of .Net have been ratified as international standards by the European Computer Manufacturers Association (ECMA)).
According to Microsoft, ".Net is a set of Microsoft software technologies for connecting your world of information, people, systems, and devices."
Well, that clears things up! The truth is, .Net evades easy definition because it covers so many topics. Some define it as a development platform for building XML Web services, while others think it's a set of enterprise servers. Both lines of thinking prove correct, although neither tells the whole story. To get a clearer picture, let's peek at .Net's basic elements:
Figure 2 below illustrates the pieces of the .Net Framework.
- Smart client software: Software for running a variety of smart clients, from personal computers (Windows XP), to small-footprint devices like PDAs (Windows CE .Net), to set-top devices (Windows XP Embedded).
- XML Web services: Let applications share data and consume services provided by other applications without regard to how those applications were built, what platform they run on, or what devices access them. .Net includes implementations of the latest accepted Web service standards, such as the XML Schema standard. In addition, Microsoft plans to provide many commercially available foundation services, called My Services, to serve as application building blocks. As a recent example, the MapPoint.Net Web service integrates maps and driving directions into applications. (That effort, however, has recently lost some momentum because partners have been slow to jump on board.)
- Enterprise servers: Products that support enterprise applications by addressing different parts of the overall solution. Among the offerings in the mix are Application Center for deploying and managing Web applications, BizTalk Server for coordinating XML-based business processes across applications and organizations, and the SQL Server database application.
- Development tools and the runtime environment: Includes Visual Studio .Net, a single integrated development environment for building .Net applications, along with the .Net Framework, which in turn includes the Common Language Runtime (CLR), ASP.Net (a new Web development environment for building Web applications and XML Web services), and an extensive set of framework class libraries.
Figure 2. The .Net Framework. Click on thumbnail to view full-size image.
As you can see, .Net covers a lot of ground.
Note: From here on out, when we talk about .Net, we're specifically referring to .Net Framework.
Line them up
In this section, we show how J2EE and .Net solve common issues developers face when architecting a system. To help frame the discussion, we present each issue within the context of the layer where it is most relevant. The four layers we'll cover are presentation, business, data, and runtime. Additionally, Figures 3 and 4 depict the logical architecture of Part 2's sample application for J2EE and .Net, respectively.
Figure 3. Illustration of the sample application architecture under J2EE. Click on thumbnail to view full-size image.
Figure 4. Illustration of the sample application architecture under .Net. Click on thumbnail to view full-size image.
Presentation layer: HTML generation
How do the two competitors handle HTML generation?
- J2EE: JSPs and servlets generate HTML for J2EE applications. The servlet containers include such features as session state, a security framework, and configuration. Tag libraries allow the developer to cleanly separate presentation code from control and business logic and also make the JSPs readable to HTML coders. A new initiative called JavaServer Faces aims to extend JSPs to allow developers to specify UI (user interface) components, event handling for HTML widgets, data validation, and navigation. Currently, you can handle such tasks with presentation frameworks such as Struts, Webwork, or wingS.
- .Net: ASP.Net builds and hosts Web applications under Microsoft's Internet Information Server (IIS). ASP.Net includes the usual stuff: fault-tolerant session state, authentication and authorization, and HTML generation. With ASP.Net, developers build ASPX pages that include HTML and custom tags that map to server-side Web controls. Web controls encapsulate reusable user interface logic and provide many advanced features to ease Web programming. For example, input controls (e.g., textboxes) automatically maintain their state from one round trip to the next, so developers can access form data on the server via control properties (e.g., textbox.Text).
Now let's see how the competing platforms handle the most commonly encountered tasks in enterprise computing: transactions, distributing remote objects, and XML Web services support.
Developers code transactions to provide systems with the so-called ACID properties: atomicity, consistency, isolation, and durability. Simply put, these properties keep your system's data coherent when things go wrong. An often used example is the ATM machine that gives you $200 in cash while simultaneously deducting the same amount from your current account. All parts of that transaction must either commit (are applied) or roll back (are not applied), and whatever happens, the system is left in a consistent state. Let's see how each platform handles transactions:
So which do you choose, manual or active transactions? It depends: Automatic transactions prove easier to program, but they are much more expensive in performance terms than manual transactions. Developers generally only use automatic transactions, therefore, to manage distributed transactions.
- J2EE: Developers can either explicitly code transaction management (user defined or manual) or specify the required behavior and hand off the management to the container (automatic mode). In most cases, developers try to delegate transaction handling to the EJB container. Manually managing transactions can introduce subtle bugs into the application; in addition, the container should prove better at transaction management than you, the developer!
- .Net: The CLR supports both manual and automatic transactions. With manual transactions, developers begin the transaction, enlist others in the transaction, commit or abort the transaction, and end the transaction. With automatic transactions, developers define an object's transactional behavior by setting a transaction attribute value on an ASP.Net page, an XML Web service method, or a class. Once an object is marked to participate in a transaction, it will automatically execute within the transaction's scope.
Calling remote objects
With .Net and J2EE, business logic can be encapsulated into components that may exist locally (in memory) or out of process on a remote machine. Nevertheless, both architectures follow different guidelines on how to achieve distribution:
XML Web services
- J2EE: Location transparency is a core J2EE feature. JNDI finds server-side components such as EJBs or JMS Queues, which, if running in a clustered environment, may or may not reside in the same VM. More generally, all access to an EJB must go through interfaces, which allows the application server to implement its own load balancing across multiple nodes to optimize throughput and response time. In practical terms, most application servers attempt to keep communicating EJBs in the same VM to minimize network traffic and the associated marshaling overhead. The developer can enforce in-VM execution with local interfaces.
- .Net: With .Net remoting, developers can call remote objects distributed across application domains, processes, and machine boundaries. As you'd expect from any remoting framework, .Net remoting hides the nasty remote call details, and it formats messages and provides the underlying transport mechanisms.
What's more interesting, however, is how you decide whether or not to use remoting. In .Net you can't automatically decide to distribute your objects as you can in J2EE, because you pay a price in network latency when you do so. You must therefore understand what you will receive in return. In the .Net world, developers employ remoting to increase security and ease maintenance, but not to improve scalability; that task is generally achieved by adding Web servers.
XML Web services make sense for some business problems. Let's see how both platforms support the latest technology wave in enterprise computing:
- J2EE: By downloading and installing the Java Web Services Developer Pack from java.sun.com, you can begin creating Web services today. In the future, J2EE 1.4 will provide best-in-class Web services support. With 1.4, all EJB Web services can be consumers, and a stateless session bean can provide a Web service. Additionally, specifications such as JSRs (Java Specification Request) 67, 93, 101, and 109 enhance the Web services support in the Java platform, providing service naming, lookup, invocation, and usage functionality, respectively.
- .Net: Microsoft placed XML Web services at .Net's core and it shows. .Net contains the latest accepted XML Web service standards (such as the XML Schema standard). Moreover, Microsoft, which groups Web services-related standards as Global XML Web Services, actively promotes other needed Web services standards.
Enterprises revolve around their data, often stored in multiple, heterogeneous data stores. Both technologies provide data access and persistence strategies, so let's dig a little deeper:
- J2EE: Persistent data is typically modeled as entity beans. There are two main types: container-managed and bean-managed persistence (CMP and BMP, respectively). Both let developers tap into container-provided services such as transaction management, a persistence framework with intelligent database updates and caching, and a security framework, as well as leveraging the container's innate characteristics such as scalability and fault tolerance. More generally, there is a Java package to access almost any corporate data source you care to mention.
- .Net: Developers can access a variety of data sources, including XML, through .Net's ADO.Net classes. Although ADO.Net gets its name from its predecessor, ADO (ActiveX Data Objects), ADO.Net is a rewrite rather than an upgrade. As you'd expect, ADO.Net includes data providers that let you connect to a database and execute commands. Developers can also transport data over the Web using XML Web services or across process boundaries using .Net remoting.
Next, we examine both platforms to identify their common and divergent areas.
How do J2EE's and .Net's execution engines—the runtime architecture that compiles and executes code—compare?
- J2EE: Java source code compiles into machine-independent byte code, which the JVM interprets at runtime. With that in mind, the particular installed JVM proves crucial to performance and scalability. Sun supplies its HotSpot VM with Java, and other JVM implementations exist, such as IBM's JVM or BEA Systems' JRockit.
As its name suggests, HotSpot looks for repeatedly executed code sections, then intensively optimizes them. HotSpot doesn't just have great scalability and performance; it also supplies the standard configurable security model for code loading and execution.
As a final feature, Java's JVMs leverage their host machines' strengths. For example, JVMs optimized for Solaris will take advantage of that operating system's special features, such as thread management. In this way, Java applications running on Solaris machines can scale up to more than 100 CPUs, 10,000 threads, and 100 GB of RAM per virtual machine (on the right hardware).
- .Net: The CLR environment executes .Net's Microsoft Intermediate Language (MSIL, or just IL) code. Like the JVM, the CLR also offers support services, such as code verification, memory management via garbage collection, and code security. When you throw in an extensive set of Framework Class Libraries (FCL), you have the .Net Framework.
The JVM and the CLR may look like identical twins, but they're more like cousins. First, Microsoft designed the CLR to support multiple languages, whereas the JVM supports only one—Java. Microsoft currently provides CLR-compliant versions of Visual Basic, C#, C++, JScript, and even Java. Other vendors are also working to support additional languages, such as COBOL, FORTRAN, and Perl.
Second, in .Net, managed code always translates into native machine code rather than interpreted. The CLR, unlike the JVM, supports compilation from the start. Although all JVMs provide just-in-time (JIT) compilers or HotSpot today, the JVM was originally designed as an interpreter.
Third, consider .Net's support for application domains. Application domains resemble processes; they provide the same isolation level without the overhead that comes from making cross-process calls or switching between processes, because they can run within a single process space. That ability to run multiple applications within a single process dramatically increases server scalability, something not supported by JVMs.
Next we examine platform portability, an area where J2EE and .Net differ.
- J2EE: J2EE offers complete cross-platform portability. If a JDK exists for your target platform, then J2EE can run on it. The ability to support Windows and mainframes and everything in between represents a big J2EE attraction.
- .Net: The CLR includes a JIT compiler that translates IL into machine code running on target platforms. Currently, .Net only supports the Windows platform, but in theory, other platforms could have their own JIT compilers. For proof, consider the Mono project, an effort lead by a Linux company called Ximian to build an open source .Net implementation. (Note, however, that at this time Mono is not currently a commercially viable option.)
Again, language support is another major differentiator between the platforms:
- J2EE: Tied to Java. If you want to use another language, you'll have to do it via an interface technology like the Java Native Interface (JNI) or via Web services.
- .Net: .Net is language independent and can use any language once a mapping exists from that language to IL. At the time of this writing, several third-party vendors have produced language compilers that target the CLR; examples include NetCOBOL from Fujitsu, and Visual Perl and Visual Python from ActiveState, with others on the way. Because all .Net languages share a common type system, developers can safely pass types written in one language to code written in another. They can also use the unified Framework Class Libraries in any .Net language, saving them from having to learn how to work with many different implementations.
This does not mean that every developer on a team should use a different language. It does mean that companies have more options, allowing them to choose the best language for the job based their developers' skills.
Since both J2EE and .Net target the enterprise, we need to look carefully at how each platform supports the technology standards that underpin the world of e-commerce:
- J2EE: Anyone can propose a JSR for a new platform extension, and the Java Community Process (JCP) does a great job keeping Java technology open with input from IBM, HP, BEA Systems, and many other participants. Adding to the language itself, however, proves nearly impossible. Sun is conservative about introducing changes to the Java language—a good idea, in my opinion, as it keeps the platform stable.
- .Net: Microsoft has long been criticized for tightly controlling its technologies. However, the company took a huge step forward when it submitted C# and the CLI to ECMA for ratification. On December 13, 2001, the ECMA General Assembly ratified the C# and CLI specifications into international standards, allowing others to participate in their evolution.
Tools support is important because it affects developer productivity:
- J2EE: Java features a plethora of tools, which is both good and bad: the developer has a great deal of choice, but might have difficulty choosing the right tool for a given job. For example, while you can choose from numerous IDEs, which works best? It depends on the project! More generally, debugging support is good via the Java Platform Debugging Architecture (JPDA), and the arrival of Ant and JUnit has given the Java community a standard build tool and unit testing framework, respectively.
- .Net: Microsoft's long and successful development tools history continues with Visual Studio .Net, the single IDE for building .Net applications, whether you're building Windows applications, Web applications, or XML Web services. With Visual Studio .Net, you can choose any .Net language. From the developer's viewpoint, applications are built using a single IDE. Visual Studio .Net boasts too many features to address here, but it's worth mentioning the new Server Explorer feature. With the Server Explorer, developers can access server resources (message queues, performance counters, data sources, and so on) without ever leaving Visual Studio .Net.
Again, like platform support, vendor support means different things in the .Net and J2EE worlds:
- J2EE: Vendor support represents a linchpin of the J2EE world. IBM, BEA Systems, Sun Microsystems, Oracle, JBoss.org, and many others offer a wide variety of J2EE products. At present, however, open source vendors cannot become J2EE-certified—a contradiction that Sun should resolve to allow open source J2EE offerings to grow.
- .Net: At the moment (and for the foreseeable future), .Net is a Microsoft platform. That could be either good or bad, depending on your viewpoint. On the plus side, developers need not worry about a dizzying array of choices, about inconsistencies in various vendor implementations, or about standards compliance. On the other hand, .Net locks you into Microsoft. For example, .Net runs only on Wintel machines. Depending on your organization, that lock-in may or may not be an issue.
Having walked through the main points that any enterprise technology must address and evaluated J2EE and .Net for each one, what do we think about our respective causes?
Sheil on .Net versus J2EE
.Net represents a real challenge to J2EE, and, with Microsoft's integrated tools support and ASP.Net, it seems very developer friendly. However, with initiatives like the NetBeans IDE, innovative features like hot deployment of server-side components, and free tools like Ant, XDoclet, and JUnit, developers can be productive with J2EE right now.
With .Net the same age-old concerns remain: I don't want to be tied to Windows as an operating system, and I fear the associated risks in doing so. Microsoft has a poor track record in security, uptime, and stability when compared to Unix. In comparison, Java's seven years in existence, combined with Unix's decades-long evolution, make the Java/Unix combination potent where it counts: mission-critical production sites. Furthermore, I remain skeptical of Microsoft's new apparent openness toward technology standards. Has the leopard changed its spots? I don't believe it has.
Monteiro on .Net versus J2EE
So which is better? .Net or J2EE? While it's an obvious question to ask, in my view it's the wrong question. The more relevant question is: What problems are better solved with .Net? For starters, .Net shines in its strong XML Web services support.
Furthermore, Microsoft will likely continue as one of the first vendors to implement the latest Web service standards, given its leadership role in these standards' development. .Net also shines in productivity. ASP.Net's familiar event-driven programming model makes programming the Web dramatically easier than anything I've seen before.
What about security and stability? Sheil is right: Microsoft's track record in these areas is suspect, but much has changed. Last October, Microsoft announced a massive security initiative to protect customer systems from Internet-based threats. We'll see whether Microsoft's efforts suffice, but based on my conversations with Microsoft people, Microsoft appears more serious about security than ever. In the area of stability, Microsoft efforts have paid off, reaching 99.999-percent reliability with Windows 2000.
So then, should a development shop already committed to either J2EE or Microsoft-based technologies switch? And if so, what would that involve?
We say that neither side should switch! .Net represents a strong effort by Microsoft to put together a cohesive server-side platform for its clients. J2EE is already there. Who will reskill an entire development organization to switch? Do compelling reasons exist to switch from .Net to J2EE or J2EE to .Net? Absolutely not! If your development organization already excels at Java development on multiple platforms, then .Net is not for you. Likewise, if your organization has invested heavily in ASP, COM/DCOM, and Windows, then moving to J2EE makes no sense either.
In Part 2, we'll dive into the code behind a B2B business—the Ice Cold Beer Boutique (ICBB). Your homework before Part 2 is to read Sheil's "To EJB, or Not to EJB?" (JavaWorld, December 2001), in which he introduced the ICBB.
Web application overview
For the Ice Cold Beer Boutique application, which Sheil introduced in "To EJB, or Not to EJB?" (JavaWorld, December 2001), we chose a problem interesting enough to be nontrivial, yet simple enough to ensure that we can clearly show each technologies' features and deficits. With that in mind, what should the ICBB application accomplish?
The Ice Cold Beer Boutique
ICBB, a business-to-business (B2B) company that sells premium beverages to resellers in Europe and the US, wants to reduce costs and order turnaround time by allowing resellers to create orders on a secure Website. The IT strategy calls for incrementally building up the site as demand increases.
The application's first release must:
The second release, building on that functionality, will allow resellers to create orders and schedule them for shipment. Eventually, ICBB will integrate its Web store with its enterprise resource planning (ERP) system Sales order Processing module so sales invoices can be raised automatically and stock information updated.
- Be secure by allowing only authorized visitors access the ICBB Website
- Be easy to use; ICBB's CEO intends to test this feature himself
- Allow resellers to view all currently stocked beverage types and prices
- Allow an ICBB system administrator to update the details for a beverage type
- Allow an ICBB system administrator to delete a beverage product
Our goal: Produce an application using a technology and design that meets these immediate requirements and admits constant enhancements as the system expands.
We implement a thin slice of the overall application, so you can see how the application layers communicate together. Figure 1 shows the distinct HTML pages planned for the system and how they hang together. All pages apart from the Welcome and Login pages are secure; only authenticated users can access them.
Figure 1. The system HTML pages in relation to each other, for both J2EE and .Net implementations. Click on thumbnail to view full-size image.
Let's see how to design the ICBB application as a J2EE application, then look at the reasons behind the important J2EE-based implementation decisions. Figure 2 illustrates how the ICBB sample application looks when implemented with J2EE.
Figure 2. The ICBB schematic as implemented with J2EE. Click on thumbnail to view full-size image.
The presentation tier
Unlike .Net, with J2EE you can employ a number of free frameworks to help build an application. That's both good and bad: While I have freedom of choice, I may choose the wrong tool. For example, with Web frameworks, I can choose to build my own or choose between Struts, WebWork, Velocity, Turbine—jeez! Which one is the right one? It depends on the task at hand!
For our ICBB example, I chose the Jakarta Project's Struts Web framework as it is arguably the most deployed Web framework in the J2EE world. Such wide deployment means that more developers know Struts than any other framework, Struts boasts a large and stable developer community, all the major application servers support Struts, and documentation/support is easy to come by. In short, you can expect Struts to be a long-lived Web application framework.
When using Struts, the system JSPs (JavaServer Pages) handle only data formatting and presentation. The pages themselves remain as simple as possible by using Jakarta Project standard tag libraries. These tag libraries require JSP 1.2 specification support, contained in all J2EE 1.3-compliant servers.
With tag libraries, Java code exists away from the JSPs, making the pages much easier to read and maintain. In addition, with tag libraries you can more easily change the JSPs' look and feel.
Business and data tiers
I implement the business and data tiers as one unit using stateless session beans called the ProductManager and CategoryManager. These session beans retrieve requested products and categories from the database, delete products, and apply changes made to products by an ICBB system administrator. They also update the database using straight SQL executed as Java Database Connectivity (JDBC) code. SQL statements execute as PreparedStatement objects to allow JDBC drivers to optimize them as cacheable statements in the database wherever possible.
In a more complex system, I would split the ProductManager between session beans for business functionality and entity beans for persistence, but the business case for ICBB simply doesn't warrant that approach—yet. Looking forward, I could easily extend the ProductManager session bean to delegate persistence to a separate persistence object(s).
Further, container managed transactions provide the system with transactional capability. Each business method invoked on the ProductManager class executes with a Required transaction attribute, and the Enterprise JavaBean (EJB) container manages the in-depth transaction management details.
Any serious enterprise computing platform must do the simple things well. In this section, we examine the most common bread and butter tasks in enterprise application development and how the J2EE-based ICBB sample application meets the following needs:
- Exception handling: ICBBException indicates when an unexpected error occurs. ICBBExceptions are logged at the source to aid finding and fixing the underlying cause.
In the presentation tier, JSPs provide specific error-handling support through the <%@ page isErrorPage="true" %> attribute in the page directive. JSPs with that tag act as error handlers for other JSPs for use in application-wide error reporting and handling. See ExceptionHandler.jsp for a concrete example.
- Logging: The code base uses the log4j logging library in conjunction with the Logger wrapper class to provide a library-independent logging system view. Log4j supports multiple destinations for logging information, including flat file, XML output, console and socket output, and even the Windows Event logger. In contrast to .Net, no explicit distinction exists between logging and trace output in J2EE, although your chosen server vendor may employ nonstandard features to provide trace information. Like .Net, the logging level can vary dynamically to aid debugging production systems while minimizing the overall impact on performance.
- Configuration: Server-side components such as servlets and EJBs can also store configuration information outside code via the web.xml and ejb-jar.xml files. The ServletConfig for servlets and the "java:comp/env" JNDI (Java Naming and Directory Interface) naming context for EJBs enable access to that configuration information.
- Authentication: The servlet container's built-in capabilities handle user authentication based on users' established roles. By simply setting up protected resources in a declarative fashion, we can hand off the authorization and authentication responsibilities to the servlet container. See the etc/web.xml file for more details on this functionality (specifically the <security-role>, <login-config>, and <security-constraint> tags).
- Authorization: The J2EE specification strongly supports both declarative and programmatic security through APIs and XML configuration files. The ICBB application includes two roles: reseller and admin. J2EE's declarative security features prevent nonadmin users from editing products, while its programmatic features control what a user sees on a particular JSP based on his or her current role.
- Session management: The servlet/JSP specifications' session management support lets developers create sessions and track users either through cookies or URL rewriting, while both JSPs and servlets can access the HttpSession object. The servlet container can invalidate these HTTP sessions automatically after a specified time-out period or programmatically (by calling the session.invalidate() method).
As with application servers, J2EE developers can choose among a wide range of free and commercial tools to enhance their productivity. My favorites include:
(For more information on the most popular Java-based development tools at present, read Jennifer Orr's "Java's Top Guns," (JavaWorld, March 2002) which honors the leading Java technologies in the JavaWorld 2002 Editors' Choice Awards.)
- Ant (free): The standard build tool for compiling, packaging, and deploying Java-based software.
- JUnit (free): A simple, easy-to-use unit testing framework for Java.
- xdoclet (free): Use custom Javadoc tags to generate code, XML, and so on from Java source code. I used xdoclet to generate some of the code and deployment descriptors for ICBB J2EE solution.
- Eclipse (free): A good Java IDE (integrated development environment). Achieves native code performance in Java! Supports debugging via the Java Platform Debugging Architecture (JPDA), including debugging server-side components, plus productivity features such as smart coding help, Ant and JUnit integration, some source-code management integration, refactoring, and more.
- IntelliJ (commercial): Another good Java IDE. Also provides debugging support through the JPDA, plus useful productivity features such as smart coding help, Ant and JUnit integration, source-code management integration, and refactoring.
Build and test the application
For detailed instructions on how to set up the J2EE-based ICBB application, read the INSTALL.txt file included with the download pack.
Application server selection and portability
I chose IronFlare's Orion application server to run the J2EE-based ICBB application. Orion boasts a small download size, supports the standard J2EE specifications, and is easy to set up and develop on. Orion also supports application hot deployment and is 100% Pure Java, so it runs on any platform with a JDK.
You can choose from numerous alternatives, such as JBoss, BEA WebLogic, or IBM WebSphere. For me, Orion's ease of use, size, and speed make it a good choice for this project. If you want to deploy the application on other application servers, feel free. I used xdoclet to generate the server-specific pieces, such as the deployment descriptors, easing the porting process. In addition, I used no proprietary Orion features to build the sample application.
Since the J2EE-based ICBB implementation uses Struts, I can hand off most of the data validation work to Strut's behind-the-scenes code. For each HTML form from which I want to update the system, I define a class that extends ActionForm, such as EditForm. Then I implement the validate method to handle whatever necessary validation before the associated Struts Action fires. Note that the data validation is server-side; to enforce client-side validation of particular fields, I would have used the Jakarta Project's Validate tag.
For Web applications, caching refers to the storing and reuse of previously constructed HTML fragments or retrieved objects to reduce the overall response time to users. The resulting performance gain can mean the difference between a successful application and a slow application that frustrates its user base. So, then, how do we handle caching in the J2EE-based ICBB application?
- Page caching: Unlike .Net, in J2EE caching generated HTML does not typically fall under the J2EE developer/administrator's control. Rather, the JSP/servlet container controls page caching under the covers as it sees fit. That lets JSP developers focus on constructing the JSP without worrying about explicitly managing caching policies or enforcing them.
However, in the spirit of flexibility, an open source JSP tag library from OpenSymphony lets JSP developers control JSP caching. In addition, vendors such as BEA also support JSP caching, albeit in a proprietary fashion.
- Data caching: J2EE's data-caching strategy depends on the data access strategy in use. EJB 2.0-compliant containers provide advanced caching strategies. Vendors, moreover, compete on the strength of their implementation/interpretation of the baseline EJB 2.0 specification. With more mature J2EE offerings, developers can use transactions directly against a cache, safe in the knowledge that the cache provider ensures the database remains consistent.
Now that Sheil has explained how he proposes to implement the ICBB application with J2EE, let's see how Monteiro will build the same application with .Net.
Figure 3 illustrates how the ICBB sample application looks when implemented on .Net.
Figure 3. The ICBB schematic when implemented with .Net. Click on thumbnail to view full-size image.
The ICBB presentation tier contains numerous Webpages, each comprising an ASPX page and code-behind. The ASPX page represents the UI (user interface); it contains HTML and custom tags that correspond to ASP.Net Web controls. The code-behind represents the behavior behind the UI; it contains the page class's definition.
Create the UI by dragging ASP.Net Web controls onto ASPX pages using the Visual Studio.Net designer. After that, you code event handlers contained in the ASPX page's code-behind. That physical separation disentangles the UI from the behavior associated with the UI, similar to how J2EE allows developers to use tag libraries to simplify JSPs.
For example, the Login page code-behind contains an event handler to handle the Login button's click event. When the user clicks the Login button, ASP.Net calls the appropriate event handler defined in the ASPX page's code-behind. Using such an event-driven programming model improves productivity because most developers can readily understand it.
Web controls also improve productivity by providing advanced features not found in standard HTML controls. For example, each control can automatically maintain its state from one roundtrip to another. When pages change, you don't need to repopulate the category ListBox between requests because the ListBox Web control can maintain its state. That simplifies Web programming and improves performance by eliminating the need to reretrieve the product categories from the database.
Another important feature: You can access form data in an object-oriented way. Instead of getting form data from a key/value collection, developers access type-safe properties on Web controls declared in the ASPX page's code-behind. For example, you can access the selected category from the ListBox control on the Product List page via ListBox.SelectedItem.Value.
Business and data tiers
As with the J2EE version, the .Net-based ICBB application relies on a single business/data tier because no significant business functionality exists beyond data access. The single tier, again like the J2EE version, contains a stateless ProductManager class responsible for retrieving, deleting, and updating products.
To retrieve products, the ProductManager's GetProducts() method calls a stored procedure using ADO.Net classes. While GetProducts() could call inline SQL, I've designed it to call a stored procedure to improve performance and security.
To update a product, the ProductManager's SaveProduct() method also calls a stored procedure to save the product updates to the database.
For transactions, recall from Part 1 that the Common Language Runtime (CLR) supports both manual and automatic transactions. Automatic transactions are easier to program, but they don't perform as well as manual transactions.
Since the ICBB application need not support distributed transactions, I selected manual transactions. (Refer to the ProductManger.SaveProduct() method in the source code.)
Next, let's revisit a number of bread-and-butter tasks needed in enterprise application development to see how .Net supports them:
- Exception handling: In Web-based applications, users will appreciate being redirected to a user-friendly error page when they encounter an unexpected error. To accomplish that goal in the ICBB .Net application, I configured ASP.Net to redirect to a specific error page (Error.aspx, for example) when an unhandled exception throws. See the <customErrors> in the web.config file to see how this is done.
- Logging: In .Net, .Net Framework classes Trace and Debug handle logging. With the Debug class, you can print debugging information and check program logic with assertions without affecting the shipping product's performance or size because no executable code generates for Debug methods when doing a release-build.
To instrument release-builds, use the Trace class. Unlike the Debug class, code generates for Trace methods for debug and release-builds. In addition, you can generate trace information related to the HTTP request by adding Trace="true" to the @Page directive (see ProductList.aspx). To view the trace output, developers use a special HTTP handler provided by ASP.Net (http://localhost/ICBB/trace.axd).
- Configuration: ASP.Net reads configuration information from the web.config XML file. If any settings within this file change, ASP.Net automatically reloads the configuration information in memory without restarting the Web server. In addition to the ASP.Net settings, you can add your own application-specific application settings in the form of key/value pairs, such as a database connection string. You can then access the configuration information using a standard API in the .Net Framework.
In the ICBB application, the ConfigurationSettings.AppSettings class reads the application's database connection string from the web.config file.
- Authentication: ASP.Net supports several authentication schemes, including Windows-, Passport-, and Forms-based, to control access to Webpages. For ICBB, I chose Forms-based authentication to avoid creating separate Windows accounts for each user and relying on Microsoft's Passport service.
With Forms-based authentication, ASP.Net automatically redirects unauthenticated users to a custom login page. The user then provides credentials as a username and password. If the user's credentials prove valid, ASP.Net issues an authentication cookie that allows the user to access parts of the site that require authentication. Note that ASP.Net entirely handles the redirection and cookie management. The developer merely validates the user's credentials.
Check out the web.config file's <authentication> tag to see how I configured authentication.
- Authorization: Once a user has been authenticated, you next determine what he or she is allowed to do. For example, in the ICBB application, only administrators should see the Product List page's Edit and Delete buttons. For everyone else, those buttons should be hidden. In addition, only administrators can save products; therefore, you should restrict nonadministrators from calling the ProductManager.SaveProduct() method.
To solve the first problem, hide the Edit and Delete buttons via programmatic security checks contained in the Product List code-behind. These checks call the current principle object's IsInRole() method. In the ICBB application, the principal represents the authenticated user logged in to the system. Solve the second problem via CLR-enforced declarative security checks. In the ICBB application, a PrincipalPermissionAttribute ensures only administrators call the ProductManager.SaveProduct() method.
For the ICBB application, because the username appears on several pages throughout the application, session state holds the authenticated user's name.
You can build a .Net application using your favorite text editor and the appropriate .Net-language compiler. I advise against that choice, however, except for the simplest applications. You'd give up many productivity-enhancing features provided by Visual Studio.Net. For example, when you drag an ASP.Net control onto a Web form, Visual Studio.Net adds the appropriate tags to the ASPX page and generates code in the corresponding code-behind for that control. When you double-click the control within the designer, Visual Studio.Net generates an event handler in the code-behind class to handle the default event (for example, the clicked event for a button). The idea is to let Visual Studio.Net take care of the plumbing while the developer focuses on the business problems.
In addition to Visual Studio.Net, a number of tools address other parts of the software development problem. Here's a partial list:
Build the application
- NAnt: A free .Net build tool for compiling, packaging, and deploying .Net applications
- NUnit: A free framework for writing repeatable tests in any .Net language
- NDoc: A free documentation-generation tool for C# developers
For detailed instructions on how to set up the .Net-based ICBB application, read the INSTALL.txt in the integrated download.
Application server selection and portability
When talking about application servers, you cannot easily draw a parallel between J2EE and .Net because the lines between Web servers, application servers, and operating systems are becoming increasingly blurry. In the .Net world, no product called an application server exists. Instead, many of the enterprise services an application server provides, such as distributed transaction management and object pooling, are embedded within Windows 2000 Server.
Enter ASP.Net with its array of validation controls including required field, range, compare, and regular expression controls (developers can even write custom validation controls if one of the prebuilt controls does not suit their needs). Instead of writing client- and server-side validation logic for each input control, you tie one or more validation control to each input control using design-time properties. When a user submits a page, each validation control checks to see if the data its responsible for passes muster. If not, an error message displays on the Webpage. The validation controls and detects the requesting browser's capabilities, letting you focus on the business problem rather than worry about technical details.
In the .Net-based ICBB application, validation controls validate user input on the Edit Product page (EditProduct.aspx).
Recall that for Web applications, caching stores previously constructed HTML fragments or retrieved objects to reduce the overall response time to users. With that in mind, let's examine .Net's built-in caching support:
And the winner is ...
- Page caching: Rather than recreating dynamic pages with each request, ASP.Net can cache entire pages or parts of a page, thereby increasing scalability by reducing the server load. Microsoft calls this kind of caching dynamic output caching.
Output caching works well for pages whose underlying content rarely changes or for those pages not requiring up-to-the-minute data synchronization, but what about pages whose content varies from one request to the next? For example, a search page shows a different result set based on the search criteria selected. ASP.Net solves the problem by varying the cached output by a set of parameters such as the query string. If the parameter value changes, ASP.Net caches a new copy of the output.
In the ICBB application, output caching has been enabled on the Welcome page via an @OutputCache directive included in the ASPX page. To see the output cache in action, try refreshing the Welcome page. Notice how often the timestamp on the page updates.
- Data caching: In classic ASP, developers often used the Application object to cache frequently requested but infrequently changing data. That works great until the underlying data changes. The .Net Framework solves the problem by providing a Cache object that behaves much like the Application object with a few added benefits, such as the ability to remove items from the cache when some dependency changes (for example, a file on disk).
In the ICBB application, the ProductManager.GetCategories() method caches the product categories in the Cache with a timestamp dependency. The Cache object then evicts the data when the data expires. You can also evict cached data based on an update to the database.
Well, there you have it. Our two-part series has culminated in the building of the same Web-based application with both J2EE and .Net technologies.
Well, the rumble didn't turn out to be much of a rumble at all! .Net and J2EE are both here to stay. .Net will capture all current Microsoft developers, but will not receive waves of converts from the Java/J2EE community as reported elsewhere. Why not?
Because the two technology stacks serve different masters. .Net is Microsoft's solution for the Microsoft OS and Intel platform combination and will flourish there. .Net cannot run on non-Microsoft platforms. In contrast, J2EE's two lynchpins are open standards and cross-platform portability, enabled through the Java programming language and platform.
At any point in time, either camp can and will claim to have a better toolset, lower total ownership costs, better performance, and even better-looking developers! But those temporary circumstances will last for no more than three to six months on either side. In general, if you are investing in either J2EE or .Net right now, it's a safe bet. Disappointing conclusion? Well write us and disagree—we value reasoned debate!
About the author
Humphrey Sheil, a Sun-certified Java architect with Cedar Enterprise Solutions, has worked on more than 25 enterprise Java projects in Europe and the US, from initial scoping right through to going live. He also researches the parallelization of neural network algorithms for compute clusters at University College in Dublin, Ireland.
Michael Monteiro is a technical specialist at Sapient, a leading business and technology consultancy that helps Global 2000 clients achieve measurable business results through the rapid application and support of advanced technology. He has more than eight years of experience delivering mission-critical applications, many of which use Microsoft technologies. As a .Net early adopter, he has spent the last year working closely with .Net and with Microsoft. In his current role, he is part of a team providing .Net architectural guidance to Sapient.