Вы находитесь на странице: 1из 5

Comparing the Struts 1 and Struts 2 Web Application Frameworks

By Michael Klaene

Go to page: 1 2 3 4 5 6 Next

Because the Struts web application framework was initially released at the beginning of this decade, developers have utilized it to
construct many thousands of applications. Struts was, and still is, the most popular framework for building Java-based web applications.
Though not without its flaws, Struts simplifies the construction of robust and maintainable web-based software. Today, there are probably
twice as many applications using Struts than there are those using all other competing web frameworks combined. It is a tribute to Struts
that so many succeeding frameworks, such as JSF (JavaServer Faces), borrowed many of their concepts directly from Struts. Struts is far
from perfect, however, and in recent years developers have increasingly begun to turn to alternative solutions. To keep pace with
developer demand, the Struts team released a major update to the framework; it's generally known as 'Struts 2'. The purpose of this
article is to provide Struts 1 developers an overview of how Struts 2 works by looking at code. You will look at a sample application twice,
once as a Struts 1 application, and then a second time as a Struts 2 application. You won't be able to cover everything, but it should be
enough to get you started with Struts 2.

Background

Struts was first released in 2001. Its primary contributor was Craig McClanahan. Prior to Struts, web applications were often a jumbled mix
of Java scattered throughout JSP(JavaServer Pages) scriptlets, Java Servlets, and various Java classes. Applications produced in this
haphazard manner were typically hard to test and even harder to maintain. Struts promoted an MVC (Model-View-Controller) architecture.
With MVC, developers were able to produce more modular code that was flexible enough to allow an application to grow. The MVC style of
development has stood the test of time and has proven itself to be a successful approach for constructing web applications. In the last
several years, competing frameworks have emerged to address some of Struts' inadequacies. The Struts community began work on a
next-generation Struts to address some of these problems. Another framework, called WebWork, had in the meantime gained some
notoriety as a viable successor to Struts. Finally, the Struts team and WebWork decided to join forces; this union led to the emergence of
Struts 2. Struts 2, in many respects, represents a significant improvement over Struts 1.

Struts 1 Walkthrough

As previously mentioned, this article will attempt to provide a comparison of Struts 1 and Struts 2 by comparing the code used to develop
the same application with each framework. Some cursory knowledge of Struts 1 is assumed. The sample application you will create is
called 'defect-tracker'. It allows users to record application defects and developers to record resolutions to those defects. The application
is trivial with the most basic requirements, but it should provide sufficient opportunity to cover basic features common to most all web
applications.

To begin a Struts 1 application, the first file you need is the web.xml configuration file. The web.xml file must be modified for Struts 1
so application URI requests can be routed to a Struts controller:

<servlet> <servlet-
name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param> <param-
name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-
value> </init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<!--Map Struts-related request to action--


> <servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

URI requests matching the pattern '*.do' are received by the Struts ActionServlet. ActionServlet finds the Struts Action mapped to this
request as specified in the struts-config.xml configuration file. The ActionServlet and Action objects comprise the 'controller' portion in
the MVC architecture of a Struts application. To transport data between Struts Actions and the 'view', typically implemented as JSPs,
Struts uses ActionForm objects. ActionForm objects represent the 'model'. When a user submits a form, the ActionForm, along with its
data, is passed to the Action's execute method. The Action might validate the data, and then invoke any necessary business logic, which,
ideally, will be encapsulated in another layer that is completely unaware of Struts. Once business logic executes, the Action transfers
control to a view specified in one or more ActionForward objects, which are also configured in struts-config.xml. ActionForward entries
represent the possible outcomes of an Action. They can be defined for each Action or globally to apply to all Actions. A glimpse of the
struts-config file is provided below. The defect-tracker application has two sets of Actions and ActionForms. One set concerns the listing
of existing defects. The second set addresses the manipulation of defect data, typically referred to as 'CRUD' ('Create-Update-Delete').
struts-config.xml

<global-forwards>
<forward name="list" path="/list.do"/>
</global-forwards>

<form-beans>
<form-bean name="listForm" type="web.DefectsListForm" /> <form-
bean name="actionForm" type="web.DefectsActionForm" />
</form-beans>

<action-mappings>
<action
path="/list"
name="listForm"
scope="request"
type="web.DefectsList"
validate="false">
<forward name="list" path="/pages/defects.jsp"
/> </action>
<action
path="/action"
name="actionForm"
scope="request"
type="web.DefectsAction"
parameter="method"
validate="false">
<forward name="edit" path="/pages/editDefect.jsp" />
<forward name="add" path="/pages/addDefect.jsp" />
<forward name="list" path="/list.do" redirect="true" />
</action>
</action-mappings>

The last two entries in struts-config declare a properties file for displaying application messages and labels, and a separate
configuration file to be used to add validation rules for the ActionForm objects in your application.

The defect-tracker application has a single domain object, Defect, that represents a system defect. Upon startup, the user is redirected
to 'list.do', which maps to the DefectsList Action object's execute method that will retrieve a list of defects.

DefectsList execute method

public ActionForward
execute( ActionMapping
mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
DefectsListForm defectsListForm = (DefectsListForm) form;

//Get data from business layer and assign it to the form


//object...
//...

return mapping.findForward("list");
}

The execute method obtains the application data and assigns it to a Collection of Defect instances using the setDefects() method on
ActionForm DefectsListingActionForm class.

DefectsListForm's Defects property

private List defects;

public List getDefects()


{ return defects;
}

public void setDefects(List defects)


{ this.defects = defects;
}

The defects.jsp file utilizes Struts 1 tag libraries to display these defects and to display labels and messages from a .properties file that
you declared in struts-config.xml.

defects.jsp displays all defects

The user can choose to add, edit, or delete a defect. When the user wants to edit a record, for example, the handler first obtains the ID
from the HTTPServletRequest, which is passed as a parameter to the Action's execute method. The execute method then will invoke a
method in the business layer to obtain the defect, and then it transfers to an editable form which will be populated with data. When adding
a new defect, a blank form appears. Because it does not make sense to allow a user to resolve a defect they have just entered, the add
form provides only a subset of fields.

addDefect.jsp to enter information about new defects

editDefect.jsp for updating defects


Features Struts1 Struts 2
Struts 1 requires Action classes to extend an An Struts 2 Action may implement an Action
abstract base class. A common problem in interface, along with other interfaces to enable
Struts 1 is programming to abstract classes optional and custom services. Struts 2 provides a
Action classes instead of interfaces. base ActionSupport class to implement
commonly used interfaces. Albeit, the Action
interface is not required. Any POJO object with a
execute signature can be used as an Struts 2
Action object.

Struts 1 Actions are singletons and must be Struts 2 Action objects are instantiated for each
thread-safe since there will only be one request, so there are no thread-safety issues. (In
instance of a class to handle all requests for practice, servlet containers generate many throw-
Threading that Action. The singleton strategy places away objects per request, and one more object
Model restrictions on what can be done with Struts does not impose a performance penalty or impact
1 Actions and requires extra care to garbage collection.)
develop. Action resources must be thread-
safe or synchronized.

Struts 1 Actions have dependencies on the Struts 2 Actions are not coupled to a container.
servlet API since the HttpServletRequest Most often the servlet contexts are represented as
and HttpServletResponse is passed to the simple Maps, allowing Actions to be tested in
execute method when an Action is isolation. Struts 2 Actions can still access the
Servlet
invoked. original request and response, if required.
Dependency
However, other architectural elements reduce or
eliminate the need to access the
HttpServetRequest or HttpServletResponse
directly.

A major hurdle to testing Struts 1 Actions is Struts 2 Actions can be tested by instantiating the
that the execute method exposes the Action, setting properties, and invoking methods.
Testability Servlet API. A third-party extension, Struts Dependency Injection support also makes testing
TestCase, offers a set of mock object for simpler.
Struts 1.

Struts 1 uses an ActionForm object to Struts 2 uses Action properties as input properties,
capture input. Like Actions, all eliminating the need for a second input object. Input
ActionForms must extend a base class. properties may be rich object types which may have
Since other JavaBeans cannot be used as their own properties. The Action properties can be
accessed from the web page via the taglibs. Struts 2
Harvesting ActionForms, developers often create
also supports the ActionForm pattern, as well as
Input redundant classes to capture input. POJO form objects and POJO Actions. Rich object
DynaBeans can used as an alternative to types, including business or domain objects, can be
creating conventional ActionForm classes, used as input/output objects. The ModelDriven feature
but, here too, developers may be simplifies taglb references to POJO input objects.
redescribing existing JavaBeans.
Struts 1 integrates with JSTL, so it uses the Struts 2 can use JSTL, but the framework also
Expression JSTL EL. The EL has basic object graph supports a more powerful and flexible expression
Language traversal, but relatively weak collection and language called "Object Graph Notation
indexed property support. Language" (OGNL).

Struts 1 uses the standard JSP mechanism Struts 2 uses a "ValueStack" technology so that
for binding objects into the page context for the taglibs can access values without coupling
Binding
access. your view to the object type it is rendering. The
values into
ValueStack strategy allows reuse of views across
views
a range of types which may have the same
property name but different property types.

Struts 1 ActionForm properties are usually Struts 2 uses OGNL for type conversion. The
all Strings. Struts 1 uses Commons- framework includes converters for basic and
Type
Beanutils for type conversion. Converters common object types and primitives.
Conversion
are per-class, and not configurable per
instance.

Struts 1 supports manual validation via a Struts 2 supports manual validation via the
validate method on the ActionForm, or validate method and the XWork Validation
through an extension to the Commons framework. The Xwork Validation Framework
Validation
Validator. Classes can have different supports chaining validation into sub-properties
validation contexts for the same class, but using the validations defined for the properties
cannot chain to validations on sub-objects. class type and the validation context.

Struts 1 supports separate Request Struts 2 supports creating different lifecycles on a


Control Of
Processors (lifecycles) for each module, but per Action basis via Interceptor Stacks. Custom
Action
all the Actions in the module must share the stacks can be created and used with different
Execution
same lifecycle. Actions, as needed.

Вам также может понравиться