Differences and contrasts between Struts1 and Struts2 (full version)

Source: Internet
Author: User

Struts2 In fact is not a strange web framework, STRUTS2 is to webwork design ideas as the core, absorbing the advantages of Struts1, therefore, can be considered Struts2 is Struts1 and webwork combination of products.

In simple terms, the difference is:

One is Stuts1, one is Stuts2, this is the biggest difference, technical aspects, STUTS1 has a core controller, but only provides an interface, that is, execute, but also to configure the Actionform and the like, very troublesome, so the dependence is stronger While STUTS2 is developed for interceptors, the so-called AOP idea, it can be more convenient to configure multiple actions, but because the interceptor before the request has some injected operations, the speed is slower relative to Stuts1.

I. Introduction to MVC

STRUTS2 is an MVC framework that is compatible with Struts1 and webwork, and since the MVC framework is mentioned, you have to do a brief introduction to the MVC framework, limited to simple introductions, and if you want to learn more about MVC, you can see the relevant documentation. Or find a Struts1 book, and believe that there is not very little space on MVC. To get to the point, in fact, the current framework of Java, the ultimate goal is to contact the coupling, whether it is spring, hibernate or MVC framework, the purpose is to contact the coupling increase multiplexing. MVC is in touch with the coupling between the view and the model.
MVC consists of three basic parts: Model, view, and Controller, which work together with minimal coupling to increase the scalability and maintainability of the program. The implementation techniques of each part can be summarized as follows:
1) Entitybean of Model:javabean and EJB
2) Taglib of view:jsp and struts
3) Controller:struts's Actionservlet, Action
The advantages of MVC are summed up in the following aspects:
1) Multiple views can correspond to a model. According to the MVC design pattern, a model corresponding to multiple views, can reduce code replication and code maintenance, once the model changes, but also easy to maintain
2) The data returned by the model is separated from the display logic. Model data can be applied to any display technology, such as using JSP pages, velocity templates, or directly generating Excel documents.
3) application is divided into three layers, reducing the coupling between the layers, which provides the extensibility of the application.
4) The concept of the control layer is also very effective, because it combines different models and different views to complete different requests. Therefore, the control layer can be said to contain the concept of user request permission
5) MVC is more in line with the spirit of software engineering management. Different layers have their own components, each layer has the same characteristics, which facilitates the production of hypervisor code through engineering and tooling.
The conceptual nature of MVC is nonsense, and the key is what each module implements.
Ii. introduction of Struts2
Struts2 since the development from the STRUTS1, but in fact Struts2 and Struts1 in the framework of the design of the idea is still a great difference, Struts2 is webwork design thought as the core, Why Struts2 do not use Struts1 design ideas, after all, Struts1 in the current enterprise application or there is a very large market in, then, look at some of the shortcomings of Struts1:
1) Support for presentation layer technology single
2) Severe coupling with the servlet API, which can be seen from the action's Execute method declaration
3) The code relies on the Struts1 API, which is intrusive, which can be seen when writing action classes and Formbean, and action must implement struts's action class
and Struts2 to webwork design thought as its core, a little is the recent rise of WebWork, and then webwork no Struts1 above those shortcomings, more in line with the concept of MVC design, but also more conducive to code reuse.
Based on the above introduction can be seen, STRUTS2 architecture and STRUTS1 architecture has a great difference, Struts1 is to use Actionservlet as its central processor, Struts2 uses an interceptor (Filterdispatcher) as its central processor, one of the benefits of separating the action class from the Servlet API.
The simple process of Struts2 is as follows:
1) The browser sends the request
2) Center processor find the corresponding action class for processing the request according to the Struts.xml file
3) WebWork's interceptor chain automatically applies common functions to the request, for example: WorkFlow, validation and other functions
4) If the method parameter is configured in the Struts.xml file, call the method in the action class that corresponds to the method parameter, otherwise call the generic Execute method to handle the user request
5) Respond to the browser the result returned by the corresponding method in the Action class
Three, Struts2 and Struts1 contrast
1) How the action class is implemented:
The STRUTS1 action must extend the action class or the subclass of the action when implemented, and the Struts2 action class can be implemented without implementing any classes and interfaces, although STRUTS2 provides a Actionsupport class, but Not necessary.
2) The Struts1 action class is a singleton pattern and must be designed to be thread-safe, and STRUTS2 generates an instance for each request
3) Struts1 's action class relies on the servlet API, from its Execute method signature, which shows that the Execute method has two servlet parameters HttpServletRequest and HttpServletResponse, Struts2 is not dependent on the servlet API
4) Because STRUTS1 relies on these web elements for the Servlet API, it is difficult to test the Struts1 action, with the help of other test tools, The STRUTS2 action can be tested just like the service class of some other model layers.
5) Struts1 action and view through Actionform or its sub-class data transmission, although there are lazyvalidationform such actionform appearance, but, It is still not possible to pass the data through a simple pojo like any other plane, and Struts2 the hope into reality.
6) Struts1 binding jstl, to facilitate the writing of the page, STRUTS2 integration Ongl, can also use JSTL, therefore, Struts2 expression language more powerful
Iv. comparison of Struts2 and WebWork
Struts2 is actually WebWork2.3, but Struts2 still has a little difference with webwork:
1) Struts2 no longer supports the built-in IOC container, instead of the spring IOC container
2) Struts2 the label for some AJAX features of WebWork instead of using dojo to replace

Comparison of Springmvc and Struts2:

Mechanism:

The entrance to Spring MVC is the servlet, and Struts2 is the filter (it is noted here that the filter and servlet are different.) Previously thought that filter was a special type of servlet, which led to a different mechanism between the two, which involved the difference between servlet and filter.

Performance:

Spring will be a little faster than struts. Spring MVC is a method-based design, and Sturts is class-based, each time a request is made with an action, each action is injected into the attribute, and spring is based on a method that is finer grained, but be careful to hold the same data as the servlet. SPRING3 MVC is a method-level interception that, after intercepting a method, injects the request data into a parameter based on annotations, and in Spring3 MVC, a method corresponds to a request context. The STRUTS2 framework is a class-level intercept, creating an action every time a request is made, and then invoking the setter getter method to inject the data from the request; Struts2 actually deals with the request through the setter getter method. ; in Struts2, an Action object corresponds to a request context.

Parameter passing:

Struts is a parameter that can be accepted with attributes when it accepts parameters, which means that the parameters are shared by multiple methods.

Design Ideology:

Struts is more consistent with OOP programming ideas, and spring is more cautious and extensible on the servlet.

The implementation mechanism of Intercepter:

With its own interceptor mechanism, Spring MVC uses an independent AOP approach. This leads to the profile of struts is still larger than spring MVC, although the configuration of struts can inherit, so I think in terms of use, Spring MVC use more concise, development efficiency Spring MVC is really higher than struts2. Spring MVC is a method-level intercept, a method that corresponds to a request context, and a method that corresponds to a URL, so it is easy to implement a restful URL spring3 mvc from the schema itself. STRUTS2 is class-level interception, a class corresponds to a request context, and implementing a restful URL is laborious because a method of struts2 action can correspond to a URL, and its class properties are shared by all methods. It is also not possible to identify the method that it belongs to by annotations or other means. The Spring3mvc method is basically independent, the request response data, requests the data through the parameter acquisition, the processing result passes modelmap to the frame method not to share the variable between, but Struts2 is disorderly, although the method is also independent, But all of its action variables are shared, which does not affect the program's operation, but it gives us code and trouble reading the program.

Summarize:

STRUT1 has rarely been used, the personal feeling springmvc in the ease of use is better than struts2.struts2 and SPRINGMVC in terms of performance is not the same, each camp has its own test data, it is difficult to say which is more excellent. The above information is part of the network, respecting the copyright of the original author and sharing to more readers.

http://blog.csdn.net/john2522/article/details/7436307

Struts2 is not an upgrade of struts1, but the lineage of inherited WebWork, which absorbs the advantages of struts1 and webwork.

See struts ' Action official note (struts1.3.8 source code) first

/**
* <p>an <strong>Action</strong> is a adapter between the contents of an
* Incoming HTTP request and the corresponding business logic this should be
* Executed to process this request. The controller (requestprocessor) would
* Select an appropriate Action for each request, create an instance (if
* necessary), and call the <code>execute</code> method.</p>
*
* <p>actions must is programmed in a thread-safe manner, because the
* Controller would share the same instance for multiple simultaneous requests.
* This means should design with the following items in mind: </p>
*
* <ul>
*
* <li>instance and static variables must not being used to store information
* Related to the state of a particular request. They may used to share
* Global resources across requests for the same action.</li>
*
* <li>access to other resources (JavaBeans, session variables, etc) Must be
* Synchronized if those resources require protection. (Generally, however,
* Resource classes should is designed to provide their own protection where
* necessary.</li>
*
* </ul>
*
* <p>when an <code>Action</code> instance is first created, the controller
* Would call <code>setServlet</code> with a non-null argument to identify the
* Servlet instance to which this Action is attached. When the servlet was to
* Be shut down (or restarted), the <code>setServlet</code> method would be
* Called with a <code>null</code> argument, which can is used to clean up any
* Allocated resources in use by this action.</p>
*
* @version $Rev: 471754 $ $Date: 2005-08-26 21:58:39-0400 (Fri, 2005)
*          $
*/

public class Action {

Code omitted ....

}

Look at Struts2 's action note (struts2.3.1.2)

Package COM.OPENSYMPHONY.XWORK2;

/**
* All actions <b>may</b> implement this interface, which exposes the <code>execute () </code> Metho D.
* <p/>
* However, as of Xwork 1.1, this is <b>not</b> required and are only here to assist users. You is free to create POJOs
* That honor the same contract defined by this interface without actually implementing the interface.
*/
Public interface Action {

/**
* The action execution was successful. Show result
* View to the end user.
*/
public static final String SUCCESS = "SUCCESS";

/**
* The action execution is successful but does not
* Show a view. This is the useful for actions
* Handling the view in another fashion like redirect.
*/
public static final String none = "None";

/**
* The action execution was a failure.
* Show An error view, possibly asking the
* User to retry entering data.
*/
public static final String error = "Error";

   /**
     * The action execution require more input
   & nbsp * In order to succeed.
     * This result was typically used if a form
     * Handling action has B Een executed so as
     * to provide defaults for a form. The
     * form associated with the handler should is
     * shown to the EN D user.
     * <P/>
     * This result is also used if the given input
&NB sp;    * params is invalid, meaning the user
     * should try providing input Agai N.
     */
    public static final String input = "INPUT";

   /**
     * The action could not execute, since the
   & nbsp * User most is not logged in. The login view
     * should be shown.
     */
    public static final String login = "Login";


   /**
     * Where The logic of the action is executed.
     *
     * @return A string representing the logical result of the execution .
     *         See constants in this interface for a List of standard result values.
     * @throws Exception thrown if a system level Exception occurs.
     *                    <b>Note:</b> Application level exceptions should is handled by returning
     *                    An error value, such as <code>action.error</code>.
     */
    public String execute () throws Exception;

}

differences and contrasts between Struts1 and Struts2:

Action class:
STRUTS1 requires the action class to inherit an abstract base class. A common problem with Struts1 is to use abstract class programming instead of interfaces, while Struts2 's action is an interface.
The Struts 2 action class can implement an action interface or other interfaces to make possible optional and custom services. STRUTS2 provides a actionsupport base class to implement commonly used interfaces. The action interface is not required, and any Pojo object that has an execute identity can be used as the Struts2 action object.

Threading Mode:
The struts1 action is a singleton pattern and must be thread-safe because only one instance of the action handles all requests. The singleton strategy limits what Struts1 action can do, and is especially careful when developing. The action resource must be thread-safe or synchronous.
The struts2 Action object generates an instance for each request, so there is no thread safety issue. (In fact, the servlet container produces many objects that can be discarded for each request and does not cause performance and garbage collection issues)

Servlet dependencies:
The struts1 action relies on the servlet API because HttpServletRequest and HttpServletResponse are passed to the Execute method when an action is invoked.
Struts 2 Action does not depend on the container, allowing the action to be tested separately from the container. If required, the STRUTS2 action can still access the initial request and response. However, other elements reduce or eliminate the need for direct access to Httpservetrequest and HttpServletResponse.

Testability:
• One of the main problems in testing the STRUTS1 action is that the Execute method exposes the servlet API (which makes the test dependent on the container). A third-party extension--struts testcase--provides a set of Struts1 mock-up objects (to be tested).
Struts 2 action can be tested by initializing, setting properties, calling methods, and "Dependency injection" support makes testing easier.

Capture Input:
Struts1 uses the Actionform object to capture the input. All Actionform must inherit a base class. Because other JavaBean cannot be used as actionform, developers often create extra class-capture inputs. Dynamic Beans (Dynabeans) can be used as a choice for creating traditional actionform, but developers may be re-describing (creating) existing JavaBean (still causing redundant javabean).
Struts 2 uses the Action property directly as an input property, eliminating the need for a second input object. The input attribute may be a rich object type with its own (child) attribute. The Action property can be accessed through taglibs on a Web page. STRUTS2 also supports Actionform mode. Rich object types, including business objects, that can be used as input/output objects. This modeldriven feature simplifies taglib references to pojo input objects.

Expression language:
Struts1 integrates the Jstl, so the Jstl EL is used. This El has a basic object graph traversal, but support for collections and indexed properties is weak.
Struts2 can use Jstl, but it also supports a more powerful and flexible expression language-"Object Graph Notation Language" (OGNL).

Bind value to page (view):
Struts 1 uses the standard JSP mechanism to bind objects to pages for access.
Struts 2 uses "valuestack" technology to enable taglib to access the values without having to bind your page (view) and objects together. The Valuestack policy allows pages (view) to be reused through a series of properties with the same name but different types.

Type conversions:
The Struts 1 Actionform property is usually of type string. Struts1 uses commons-beanutils for type conversion. Each class is a converter that is not configurable for each instance.
Struts2 uses OGNL for type conversion. A converter that provides basic and common objects.

Check:
The Struts 1 supports manual validation in the Validate method of the Actionform, or is verified by an extension of Commons validator. The same class can have different checksum content, but it cannot validate child objects.
STRUTS2 supports validation through the Validate method and the Xwork check framework. The Xwork checksum framework uses checksum content validation defined for the attribute class type to support the chain check sub-property

Control of Action Execution:
Struts1 supports each module with a separate request processors (life cycle), but all the actions in the module must share the same life cycle.
Struts2 supports creating different lifecycles for each action through the Interceptor Stack (Interceptor Stacks). Stacks can be used in conjunction with different actions as needed.

One, the first version of the introduction struts was released in May 2001. Its original idea was to make the view of Web applications and business/application logic clearly separate by combining JSPs and Servlets. Before struts, the most common practice was to include business and application logic in the JSP, or to generate the view through println () in the servlet.

Since the release of the first edition, Struts has actually become an industry-accepted standard for Web applications. Its popularity has also brought improvements and changes for itself, so not only to keep up with the changing needs of the Web application framework, but to merge with the features of a growing number of highly competitive frameworks. In the end, several next-generation struts solutions were produced. Two of the most notable programs are shale and struts Ti.

Shale is a component-based framework and has recently become the top-level project for Apache. Struts ti, on the basis of the successful experience of struts, continues to make improvements to the front-end controllers (Front Controller) and the MVC (Model-view-controller) model. The WebWork project, released in March 2002, revolutionized the struts framework by introducing new ideas, concepts, and functions that were not compatible with the original struts code. WebWork is a mature framework that has undergone several major improvements and releases. In December 2005, WebWork and Struts TI announced the merger. At the same time, struts Ti was renamed Struts Action Framework 2.0 to become a true successor to struts. Finally, it is not said that struts or webwork projects have ceased to develop. Since people are still very interested in these two projects and many developers are still willing to use them, these two projects are still under development, continue to fix bugs, improve functionality and continue to add new features.

Second, the action of the difference for a rich struts1.x development experience of friends, are very clear action is the core of the entire struts framework, of course, STRUTS2 is no exception. However, struts1.x differs greatly from the action model of STRUTS2. The difference between Struts2 and struts1.x, the most obvious is that STRUTS2 is a PULL-MVC architecture.

What does that mean? From the developer's point of view, the data that needs to be displayed to the user can be obtained directly from the action, and unlike struts1.x, the corresponding bean must be stored in the page, request, or session. struts1.x must inherit org.apache.struts.action.Action or its subclasses, and the form data is encapsulated in Formbean.

Struts 2 does not need to inherit any type or implement any interface, the form data is contained in the action, obtained through Getter and setter (as in the following ACTIONFORSTRUTS2 code example). Although, in theory Struts2 action does not need to implement any interface or inherit any class, however, in the actual programming process, in order to more convenient implementation of the action, In most cases, the Com.opensymphony.xwork2.ActionSupport class is inherited, and the string execute () method in this class is overloaded (override).

First, it can be seen from ACTIONFORSTRUTS2 that the returned object is not a actionforward, but a string. If you don't like to appear in your code as a string, a helper interface action can provide common results in a constant manner, such as "success", "None", "Error", "Input", and "login".

In addition, as is customary, only the "execute" method in struts1.x can invoke action, but is not necessary in Struts2, and any declaration of the public String MethodName () method can be configured to invoke action.

Finally, the biggest revolutionary difference with struts1.x is that the method that is called during the Struts2 Processing action (the "Execute" method) is without parameters.

So how do you get the objects you need? The answer is to use the IOC (inversion control, inversion of controls), also known as the "Dependency injection (Dependency injection)" pattern (for more information on this, see Martin Fowler's article http. www.martinfowler.com/articles/injection.html). The spring framework makes this pattern popular, but Struts2 's predecessor (WebWork) also applies this pattern.

Third, IOCIOC (inversion of control, the following translates as controlled inversion), with the Java community in the lightweight container (lightweight contianer) to promote and more and more familiar to everyone. Here, there is no need to explain "what is control reversal" and "why control reversal". Because there are a lot of articles on the Internet that have made wonderful and accurate answers to such questions.

Readers can read "Expert One-on-one development without EJB" by Rod Johnson and Juergen Hoeller, or Martin Fowler, "inversion of Control Containers and the Dependency injection pattern. As we all know, Struts2 is based on the development of WebWork 2. In the WebWork version before WebWork 2.2, its own set of control inversion implementation, WebWork 2.2 in the spring framework of the full development of the background, decided to abandon the development of the control reversal function, the spring implementation.

It is worth mentioning that spring is indeed a learning framework because more and more open source components, such as Ibatis, are abandoning the development of features that overlap with spring. Therefore, STRUTS2 recommends that you implement control inversion through spring.

To better understand inversion control, here's an example of how the IOC can access the current request Httpserverrequest object during action processing. In the example, the dependency injection mechanism used is interface injection. Like its name, interface injection requires an interface that has already been implemented.

This interface contains the setter for the corresponding property, providing a value for the action.

The Servletrequestaware interface is used in the example, as follows:

Public interface Servletrequestaware {public void setservletrequest (HttpServletRequest request);

When this interface is inherited, the original simple action looks a bit complicated, but you can now get the Httpserverrequest object to use.

public class IoCForStruts2 implements Servletrequestaware {

private HttpServletRequest request;

public void Setservletrequest (HttpServletRequest request) {

This.request = Request; }

Public String Execute () throws Exception {

You can start working with the Request object

return action.success; }

}

It seems that these attributes are class-level, not thread-safe, and there are problems.

In fact, there is no problem in Struts2, because each request comes up with a new action object instance that does not share an object with other requests, so there is no need to consider thread safety issues.

The Interceptor Interceptor (the Interceptor) is used in AOP (aspect-oriented programming) to intercept a method or field before it is accessed, and then add some actions before or after.

Interception is an implementation strategy of AOP. The Chinese document in WebWork is interpreted as--interceptors are objects that dynamically intercept action calls. It provides a mechanism to enable a developer to define code that executes before and after an action executes, or to prevent it from executing before an action executes. It also provides a way to extract the reusable parts of an action. Struts1.x's standard framework does not provide any form of interceptor, although an additional project called Saif implements such a function, but its scope of application is still limited.

Interceptors are a powerful tool for Struts2, and many functions (feature) are built on top of it, such as internationalization, converters, checksums, etc. When it comes to interceptors, there is also a popular word-the Interceptor chain (Interceptor Chain, called the Interceptor Stack interceptor stack in Struts2).

The Interceptor chain is a chain that binds the interceptor in a certain order. When accessing an intercepted method or field, interceptors in the interceptor chain are called in the order in which they were previously defined.

The interceptor implementation of Struts 2 is relatively straightforward. When the request arrives at Struts2 's servletdispatcher, struts 2 looks for the configuration file, instantiates the relative interceptor object based on its configuration, then strings it into a list, and finally invokes the interceptor in the list, struts 2 has provided a wide range of fully functional interceptor implementations.

Readers can check the configuration of the default interceptor and interceptor chain to the struts-default.xml of the Struts2-all-2.0.6.jar or Struts2-core-2.0.6.jar package. As a framework, extensibility is indispensable because there is no universal in the world.

While Struts 2 provides us with such a rich interceptor implementation, this does not mean that we lose the ability to create custom interceptors, and on the contrary, it is quite easy to customize interceptors in Struts 2.

The origins of Struts2 are briefly described, and the differences between STRUTS2 and struts1.x are detailed, and the reader should be aware of the basics of Struts2-including the high-level framework concept and the basic request flow, and understand the difference in action between struts1.x and STRUTS2, STRUTS2 enhanced support for interceptors and IOC, and in struts1.x, these features are hard to imagine.

At the same time, readers should understand that STRUTS2 is a webwork upgrade, not a struts 1.x upgrade. Although Struts 2 provides compatibility with struts1.x, it is not a struts1.x upgrade. For developers who already have struts1.x development experience, the development experience of struts1.x is not very helpful for Struts2, whereas for developers who already have webwork development experience, webwork development experience will be very Good reference to the significance.

Differences and contrasts between Struts1 and Struts2 (full version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.