Architecture & DesignApache Struts Framework: The Big Picture

Apache Struts Framework: The Big Picture

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

A framework for Web development is a set of related classes, utilities, and modules that simplify a project’s creation by providing pre-build parts. In this article, I will focus exclusively on Apache Struts J2EE framework, even though a cornucopia of other frameworks exists for any imaginable development problem. Struts is extremely flexible and is a good fit for most Web-based projects; however, if you find that, after reading this article (and perhaps a few other books on Struts), it is not a 100 percent match for your project, please look at another viable framework. I have described several in my previous article “Modern Java Frameworks for Web Development”. I have also described WebWork framework in more detail in a separate article, “Working with the WebWork Framework“. The list of some other frameworks is provided in the references section.


In this article, I will describe how to work with Struts, go over its main features, and discuss setting it up in an enterprise development environment, such as JBuilder 2005.


Overview of Struts


Struts became very popular as an open source framework/project because it solved a lot of problems and provided a higher level of abstraction for application developers. In addition to a very stable framework, Struts provides plug-in capability, among other things. Developers who use Struts don’t need to implement a lot of common functionality because it’s already provided for them. The structure of the framework also forces any project to adhere to the Model-View-Controller (or Model2) paradigm. For example, provided components—such as main Servlet controller, abstract and concrete action classes to inherit from (for the model layer and actions), numerous utilities and tags, as well as user data validation—all enforce MVC structure. This is particularly beneficial for novice Web developers who may have tendencies to embed model logic in the presentation layer or GUI elements in the model layer.


The Struts framework is an open-source product for building Web applications based on the model-view-controller (MVC) design paradigm. It uses and extends the Java Servlet API and was originally created by Craig McClanahan. Please note: Because of the extensiveness of the Struts framework, there are entire books written just about it. It will be impossible to describe all the features of the framework in the constraints of this article. However, I will talk about the most important aspects of the framework. Also, I am assuming that you are familiar with some enterprise Integrated Development Environment (IDE), such as JBuilder 2005 or Eclipse and know how to create a Web application with it.


Major Features


Any application that wants to use Struts components must include its libraries. The project must include struts jars as well as any other libs such as third-party database connection drives.

At the heart of Struts is a struts-config.xml file that is located in the WEB-INF directory of your project and describes everything about the coordination of requests and responses for the application. It also describes form bean classes, database connection data-sources, action mappings, instructions in the event of error for each action, and plug-ins (such as validation, to which I will get in a moment).


This config file must be included in you application, and it can be created by hand or with an IDE. For example, JBuilder provides a very user-friendly GUI Struts Config Editor. See below.

Struts Config Source Example Code

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//
DTD Struts Configuration 1.1//EN”
“http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd”>
<struts-config>
<data-sources>
<data-source type=”com.mysql.jdbc.jdbc2.optional.
MysqlDataSource”>
<set-property property=”url”
value=”jdbc:mysql://localhost/database” />
<set-property property=”user” value=”root” />
<set-property property=”password” value=”root” />
<set-property property=”maxCount” value=”5″ />
<set-property property=”driverClass”
value=”com.mysql.jdbc.Driver” />
<set-property property=”minCount” value=”1″ />
</data-source>
</data-sources>
<form-beans>
<form-bean dynamic=”no”
name=”Login” type=”com.entity.SomeClass” />
</form-beans>


<action-mappings>
<action path=”/someAcion2″
type=”com.action.ScheduleEntryAction”>
<forward name=”success” path=”/SomeView.jsp” />
</action>
<action input=”/Login.jsp”
name=”Login” path=”/addUser”
scope=”session” type=”com..action.AddAction”
validate=”true”>
<forward name=”success” path=”/someAction1.do” />
<forward name=”error” path=”/Error.jsp” />
</action>
<action path=”/deleteUser” />
</action-mappings>
<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
<set-property property=”pathnames”
value=”/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml” />

</plug-in>
</struts-config>

The Struts framework provides a controller servlet as well as the skeleton classes for actions that developers need to extend and implement the “execute” method.


The actions and outcome of the request and response can be mapped out graphically in JBuilder as well. For example, here is an action (class that extends org.apache.struts.action.Action) and flow of logic that it involves.

Similar graphical editors exist for other parts of Struts application in JBuilder as well.


The main controller and the reference to the struts config file must be placed in the standard web.xml config file for whichever application server is used.

For example, here is web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//
   DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
   <servlet>
      <servlet-name>action</servlet-name>
      <servlet-class>
         org.apache.struts.action.ActionServlet
      </servlet-class>
      <init-param>
         <param-name>application</param-name>
         <param-value>com.myapp.action.ResourceFile</param-value>
      </init-param>
      <init-param>
         <param-name>config</param-name>
         <param-value>/WEB-INF/struts-config.xml</param-value>
      </init-param>
      <init-param>
         <param-name>debug</param-name>
         <param-value>2</param-value>
      </init-param>
      <load-on-startup>2</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
   </servlet-mapping>
   <session-config>
      <session-timeout>30</session-timeout>
   </session-config>
   <taglib>
      <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
   </taglib>
   <taglib>
      <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
   </taglib>
   <taglib>
      <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
   </taglib>
   <taglib>
      <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
   </taglib>
   <taglib>
      <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
   </taglib>
   <taglib>
      <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
   </taglib>
</web-app>

Note: *.do is mapped to the action servlet, which means that any request to any action that ends with “.do” will go through the main controller servlet first.

The web.xml includes a definition of yet another great Strut’s feature—a vast collection of pre-built tag libraries.

Bean tags contain JSP custom tags to manipulate java beans in any application scope, as well as render of them to the output.

Custom HTML tags include numerous form inputs, dynamic user interfaces, and other very useful tags.

Logic tags deal with application flow management, such as iteration over collections and generation of output.

I welcome you to read more about all included tags on the Struts Web site http://struts.apache.org/. All of these tags help to reduce the amount of Java scriplet code in the JSP, and they can be used with the Java Standard Tag Library (JSTL) or any other custom tags and are extremely useful. In addition, because Struts is one of the most popular frameworks, all these tags have been mapped as Macromedia Dreamweaver (or Ultra-Dev) plug-ins so that HTML developers and designers can use them without knowing anything about Java.

Another tremendously helpful and efficient feature of Struts is resource files and internalization. It is very likely that any Web application will have some components that appear in more then one place throughout the application. Labels, button names, page comments, titles, headers or footers, as well as error messages can be included as a property recourse file in any Struts application. All that needs to be done is to add a text properties file with name-value pairs placed in the application path, and referenced as a parameter to the Struts controller servlet.

Struts also supports internalization by reading the user locale, which arrives as part of the HTTP request. It can use different properties files for different locales and match them to the user responses. For example, if ResourceFile_it file exists and the user’s request identifies it as Italian, this resource file will be used instead of the default one.

Validation

The Struts framework provides a very clever way to validate user input fields and comes with pre-built modules for it. The first thing needed for the setup of validation is a custom validation.xml file, and a Struts-provided validator-rules.xml file. Both of these files need to be in the same WEB-INF dir as the web.xml and struts-config.xml files. The validation.xml file needs to be included in the struts-config file as well.

Here is the example of validation.xml file.

<form-validation>
   <formset>
      <form name="someForm">
      <field property="text"
             depends="required,minlength">
         <arg0 key="prompt.text"/>
         <arg1 name="minlength"
            key="${var:minlength}" resource="false"/>
         <var>
            <var-name>minlength</var-name>
            <var-value>0</var-value>
         </var>
      </field>
      </form>
   </formset>
</form-validation>

When creating a form in JSP, you need to place a form element (field) with the property “text” or whatever you defined the validation for.

<html:text property="text" size="16"/>

Also, code for showing validation error messages needs to be placed somewhere on the JSP as well. For example, this code will show error messages.

<logic:messagesPresent>
   <h3><font color="red">
      <bean:message key="errors.header"/>
   </font></h3>
   <ul>
      <html:messages id="error">
         <li><bean:write name="error"/></li>
      </html:messages>
   </ul>
   <p/>
</logic:messagesPresent>

Struts is smart enough to show errors and re-populate all fields from the response object in case the user was redirected to the same page after entering invalid data.

Conclusion

In this article, I described some of the major features of Struts, including its structure, main configuration files, tags, resource files, and internalization support. I also briefly showed its plug-in support, such as validation. I believe that the Struts framework is general enough to be useful in any enterprise Web-based project, yet granular enough to provide a lot of control over the application. Not only can it simplify development process and save work, but it also can provide a layer of abstraction that will take care of the “plumbing” and let developers concentrate on implementation of the business requirements. If you are looking for a Web development framework, you should definitely consider Struts.

Web Development Framework References

Struts: http://struts.apache.org/, http://www.springframework.org/

Hibernate: http://www.hibernate.org/

WebWork: http://www.opensymphony.com/webwork/

Tapestry: http://jakarta.apache.org/tapestry/

About the Author

Vlad Kofman is a Senior System Architect working on projects under government defense contracts. He has also been involved with enterprise-level projects for major Wall Street firms and the U.S. government. His main interests are object-oriented programming methodologies and design patterns.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories