ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


What Is Struts

by Chuck Cavaness, author of Programming Jakarta Struts, 2nd Edition
11/02/2005
Struts
Apache Struts is an open source Java framework used for building web applications based on the servlet and JavaServer Pages (JSP) technologies. It was created in 2000 by Craig R. McClanahan and has become the de facto standard framework for web applications in Java.

In This Article:

  1. The Web Development Landscape: Six Years Ago
  2. Along Comes Jakarta Struts
  3. Benefits of the Struts Framework
  4. Overview of the Struts Framework
  5. Choosing a Model Layer for Struts
  6. The Struts Presentation Layer
  7. Struts' Other Great Features
  8. More Information on Struts

Is it conceivable that anyone in the business of building software hasn't heard of the Struts framework? From developers that are just starting out in the business to those long in the tooth, the name "Struts" surely must ring a bell. But if you haven't spent your development time in the Java world or haven't had the need to build web applications, Struts might only be a buzzword that you've added to your resume. For the next five to ten minutes, you're going to be taken on a whirlwind tour of the Struts framework. Get a drink (non-alcoholic, of course), sit back, and put your feet up, and learn a little about one of the most popular free frameworks to ever grace the open source community.

The Web Development Landscape: Six Years Ago

This is going to sound like a grandfather preaching to his grandkids about how tough it was in his day, but prior to 2000, the landscape for developing Java web applications was much different. Java servlets had been out for just a short time (relatively speaking) and Sun had recently released JavaServer Pages (JSP) to counter Microsoft's Active Server Pages (ASP) technology. JSPs caught on like wildfire and before long, many web applications were being built using JSPs.

Unfortunately, in an effort to get applications quickly out the door and due to a lack of any best practices in the industry at the time, many JSP applications became a tangled web of pages as developers crammed as much of the application functionality into the JSP. This approach to building JSP applications would eventually be called the JSP "Model 1" architecture and is shown in Figure 1.

Figure 1
Figure 1. The JSP Model 1 architecture

The Model 1 architecture used the JSPs to handle the HTTP requests, communicate with the data layer (via JavaBeans), and to render the next page back to the client. For small applications, this approach isn't so terrible. But for non-trivial applications where there are many pages or when the functionality is more traditionally application-like, the Model 1 architecture presents many maintenance and upgradeability challenges.

Developers soon realized that the use of JSPs in conjunction with a single controller servlet could improve this design greatly. The separation of the presentation layer from the business logic not only serves to keep the JSPs cleaner, but it allows development teams to utilize each team member's specialized skill.

This new approach to building JSP applications became known as the JSP "Model 2" architecture. It was patterned after the Model-View-Controller (MVC) design, which originated from Smalltalk, where it was used to separate the GUI from the business layer. (When MVC is done on the Web, it is often referred as Web MVC.) The JSP Model 2 architecture is shown in Figure 2.

Figure 2
Figure 2. The JSP Model 2 architecture

The Model 2 architecture uses a Java servlet to receive the HTTP requests from the browser and to communicate with the model layer. The JSPs are used only for presentation. The same controller that receives the request is responsible for determining which view gets returned back to the client.

Programming Jakarta Struts

Related Reading

Programming Jakarta Struts
By Chuck Cavaness

Along Comes Jakarta Struts

Three things started to happen around 2000 that helped catapult Struts into the forefront of web development frameworks. First, the open source community was starting to gain momentum and popularity. Open source projects like Tomcat, Ant, and Log4J were gaining mindshare with the development community, and managers were just starting accept that free software had a place in the business world.

The second thing that was happening around the same time was a huge number of new startup companies (affectionately called dot coms) were trying out their various business models on the populace. Most of these business models involved some form of web presence and therefore required a web framework. (In retrospect, for those of us who lived through it, these times were very stressful and exciting at the same time.)

It was also during this time that Craig McClanahan created the open source web development framework called Struts, which was based on the Model 2 architecture and which was added to the list of Jakarta projects. Little did he probably know that the planets were lining up behind his newly created web framework.

Benefits of the Struts Framework

There are literally hundreds of web development frameworks available, each sharing some similarities while providing their own twist on what a web framework should be. Many of these frameworks have been around several years and have positives and negatives associated with them. While the Struts framework is not completely unique, it provides some key benefits:

When Struts first arrived on scene, I put together a list of reasons that would help developers and their managers decide if Struts was right for their team. I created a separate list for developers and one list for their managers, because often that the two are focused on different issues. Those lists are still relevant today.

Is Struts right for your project? (Manager version)

Is Struts right for your team? (Developer version)

Whether you're a manager being pushed by your development team to allow Struts into your organization or a developer wondering if all of the hype is true, these two lists should tell you that Struts is a serious framework. After all, do you think a company the size of BEA would choose Struts for their commercially released administrative console if they didn't have confidence in the open source framework?

Overview of the Struts Framework

The Struts framework is composed of approximately 300 classes and interfaces organized in about 12 top-level packages. Besides the utility and helper classes, much of the framework consists of classes and interfaces for working with either the controller functionality or the presentation through custom tag libraries. The choice of a model layer is a decision that's left up to you. Some argue that this is a deficiency in the framework, while seasoned Struts developers would say that this freedom is warranted and welcomed. A high-level view of the Struts architecture is shown in Figure 3.

Figure 3
Figure 3. The Struts architecture

In 2002, I put together a presentation for the Atlanta Java Users Group (AJUG) on Struts. In that presentation, I came up with a facetious business model called Beer4All that included an e-commerce web site called beer4all.com. (Back then, I actually owned the domain name. Now it's been taken over by cretins who want to make money by selling the domain name.) You can find the original presentation that included the Beer4All example at www.ajug.org/meetings/download/struts.pdf. I'm going to refer to the Beer4All here for a few of the examples.

The Struts Controller Components

When a request is sent to a Struts application, it's handled by the Struts ActionServlet. The Struts framework includes a concrete ActionServlet that for many users is adequate and requires no customization or additional work.

When the ActionServlet receives a request, it inspects the URL and based on the Struts configuration files, it delegates the handling of the request to an Action class. As you can see from Figure 3, the Action class is part of the controller and is responsible for communicating with the model layer. The Struts framework provides an abstract Action class that you must extend for your own needs.

Example 1 shows you an example of an Action class from the Beer4All Struts application that extends the base Action class.

Example 1. The Beer4All LoginAction class is called by the ActionServlet when users attempt to log in to the site.

public class LoginAction extends Action {
    /**
     * Called by the ActionServlet when the a user attempts to login.
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        /*
         * Get the user's login name and password. They should have been
         * validated by the ActionForm.
         */
        String username = ((LoginForm) form).getUsername();
        String password = ((LoginForm) form).getPassword();

        // Login through the security service
        Beer4AllService serviceImpl = this.getBeer4AllService();

        // Authenticate the user with the backend
        UserView userView = serviceImpl.authenticate(username, password);

        // Invalide the current session and create a new one
        HttpSession session = request.getSession(false);
        session.invalidate();
        session = request.getSession(true);

        // Store the user object into the session
        session.setAttribute("USER", userView);

        return mapping.findForward("success");
    }
}

The Action class in Example 1 is called when a user attempts to log in to the Beer4All website, probably to order their next shipment of ale. The URL that the browser would have sent to the ActionServlet would have looked something like http://beer4all.com/login.do. When the ActionServlet gets this request, it consults its mapping (which was loaded from the Struts configuration files at startup) and discovers that the LoginAction is the Action class that handles the login.do request. The ActionServlet then calls the Action's execute() method to perform whatever task the Action class was meant to perform. Within the execute() method, you can put in whatever logic you need in order to fulfill the request. For example, you could acquire a Hibernate session and query the database, invoke a Stateless Session Bean (SLSB) or maybe use JavaMail to send an email to a registered user, just to name a few.

The LoginAction from Example 1 authenticates the user through some service (the details of which are not shown), presumably to a database. When the Action class is finished performing its logic, it typically stores objects (JavaBeans) into the request, session, or even application scope, and informs the controller servlet whether it was successful or not. Based on the mappings for the LoginAction class, the ActionServlet will determine the next page the user should be shown. Because the JSP has access to the same request, session, or application scope, it can access those stored objects and use them to render the view for the client.

The Struts framework includes several pre-built Actions that make it easier to build out functionality. You don't always have to map a web request to a separate Action class. The org.apache.struts.actions.DispatchAction, for example, is designed to support multiple requests. In the Beer4All application, we have the typical e-commerce shopping cart functionality (view the cart, add items, checkout, etc.). Instead of creating separate Action classes for each action, we can use the DispatchAction to contain all of the methods that work on the user's cart. Using the DispatchAction class keeps the number of Action classes to a minimum, which helps to simplify the maintenance of the application.

Choosing a Model Layer for Struts

As we said earlier, the Struts framework doesn't provide much in the way of the model, but it can integrate with any current model approach, including JDBC and EJB, as well as third-party packages like Hibernate, iBATIS, and Object Relational Bridge. One of the most important best practices for the Struts framework is that business logic should stay out of the Action class, regardless of what you're using for the Model layer. Putting business logic in the Action classes hurts reusability of the Action class and couples the framework too tightly with the business tier. Instead, the Action classes should utilize a service layer, even when using straight JDBC. Back in Example 1, for example, the authenticate() method was called on a service called Beer4AllService. This might have been a Stateless Session Bean, a RMI object, or maybe just a simple Java class that wraps JDBC code. The good news is that you're not limited with Struts.

The Struts Presentation Layer

The Struts presentation layer is almost as flexible as the model layer. You can (and most users do) use JavaServer Pages, of course. But you can also use one of many alternative presentation technologies if JSP isn't your thing. From Velocity Templates to XSLT to JavaServer Faces, Struts easily integrates with many.

If you are using JSP, then you're in luck, because Struts has a fairly exhaustive set of JSP custom tags.

The Venerable Struts Tag Library

The support for custom tags was added to the JSP language to allow developers to extend the JSP library. The Struts framework includes over 60 JSP custom tags grouped into one of the five libraries shown in Table 1.

Table 1. Struts includes many custom tags that many building JSP applications easier.

Tag Library

Purpose

HTML Tag Library

Contains tags used to create Struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces.

Bean Tag Library

Contains tags useful for accessing beans and their properties, as well as defining new beans.

Logic Tag Library

Contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

Nested Tag Library

Contains tags useful for dealing with object graphs and nested properties.

Tiles Tag Library

Tiles builds on the "include" feature provided by the JavaServer Pages specification to provide a full-featured, robust framework for assembling presentation pages from component parts.

The Struts framework also works quite nicely with the JSP Standard Tag Library (JSTL), which was created to provide a set of standard tags that will work in all compliant JSP containers.

Presentation Validation

Another great feature of Struts is the presentation validation that's included with the Commons Validator. The Validator framework was created by David Winterfeldt and integrated into Struts in version 1.1. The Validator provides for presentation validation (and with some customization, business validation) by declaring the rules in an external XML file. The framework comes with many pre-built validation rules, like checking for required fields, max and min lengths, and date validations. It also supports regular expressions. You can even create you own validation rules and easily add them to your application.

Struts' Other Great Features

We're running out of time. I promised you that it wouldn't take longer than five or ten minutes to read this and unfortunately, there are many other areas of Struts that deserve the same amount of attention. Just look at the following list of features that we haven't even talked about yet:

We could go on all day, but you would eventually need another drink and your boss is expecting you to get some work done today, so we should end now and let you get back to work.

More Information on Struts

Hopefully, this quick review of the Struts framework has helped you in some way. Maybe you looked at the framework a long time ago and weren't aware of the vast changes that the framework has undergone. If you're interested in getting your hands on the latest version of Struts, you can find it from the main Struts site. The resources available on the Struts site have really improved with the last several versions. You can find wiki pages, projects and products built using the framework, FAQs, and many more interesting things. When I started using Struts in 2001, there were no books on Struts available. I believe my book Programming Jakarta Struts, published by O'Reilly (now in its second edition), was the second one published. You can see that there are now many books about Struts on the market, which gives you an indication of how popular the framework has truly become. Go and prosper!

Chuck Cavaness is a graduate from Georgia Tech with degrees in computer engineering and computer science. He has built Java-based enterprise systems in the healthcare, banking, and B2B sectors. He is also the author of two O'Reilly books, Programming Jakarta Struts and Jakarta Struts Pocket Reference.

Programming Jakarta Struts

Related Reading

Programming Jakarta Struts
By Chuck Cavaness

Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.