STRUTS2 Basic Configuration

Source: Internet
Author: User
Tags abstract bind reflection requires

Struts2 is the second version on the big version, but basically it has completely overturned the struts1.x in terms of configuration and usage (STRUTS2 is still based on the MVC pattern, the action-driven, maybe it's the only thing that hasn't changed), though. Struts2 is actually an MVC framework built on a webwork basis. We can see from the source code of STRUTS2 that there are many packages that are directly used by Xwork (webwork core technology).

1, the role of Web.xml

Web.xml Core Code:

        <url-pattern>/*</ Url-pattern>

1, notify the Web server (tomcat), as long as the/* request path, are referred to the filter to handle.

2, by parsing and reflecting the core filter of Struts2, after instantiating, loading struts2 related configuration file, such as Struts.xml

After parsing the Struts.xml file, a JavaBean object is formed in memory, which does not need to be reloaded for each access, and accesses the memory directly.

When redeploying, the Struts.xml is reloaded to form a new JavaBean object.


In the external memory: Struts.xml

    <action name= "x" class= "y" method= "z"/>

In memory: The Struts.xml is parsed to form the following JavaBean object

public class root{     private action action;  
} public class action{    private String name= "x";    Private String class= "Y";    Private String method= "z";    
   Setter/getter ().  

Note: If you change the content in Struts.xml, you need to redeploy to complete the update of the JavaBean object in memory.

2, the role of Struts.xml

The request, the processing class and the corresponding business method are flexibly configured through Struts.xml.


<action name= "helloworldaction" class= "com.amos.web.action.HelloWorldAction" method= "execute" > </action >

Please request helloworldaction and configure it with the Execute method in class Com.amos.web.action.HelloWorldAction.

Helloworldaction (Request)------->com.amos.web.action.helloworldaction (Class)-------->execute (method)

You can change the Name property directly in the configuration file when you want to change the request name ABC, or change the request to another method in the class, and you only need to change the method name in the configuration file. As follows:

ABC (Request)------->com.amos.web.action.helloworldaction (Class)-------->othermethod (method)

3, struts2 attribute summary:

<package name= "com.amos.web.action" namespace= "extends=" Struts-default "> <action name=
" Helloworldaction "class=" com.amos.web.action.HelloWorldAction "method=" execute "> </action>
</ Package>

Name= "com.amos.web.action"------Package Name

Namespace= "/"------access to space

extends= "Struts-default"------extend STRUST2 's internal functionality

Name= "helloworldaction"------Execution path

class= "Com.amos.web.action.HelloWorldAction"------use full path for reflection

Method= "Execute"------the business method that needs to be performed, also by reflection

Note: Struts2 recommends that the relevant action class be placed under the same package, such as CRUD operations, similar to the relationships of packages and classes in Java

4, STRUTS2 Basic configuration detailed

1), Access to action rules

Namespace attribute value in rule:<package> the name tag in <action>, the concatenation character is "/"

For example, will namespace= "/hi/amos", after the stitching URL is as follows:


Test rule:

Current namespace as '/':

 [ok]http://localhost:8080/struts2/hi/amos/ Helloworldaction
[ok]http://localhost:8080/ Struts2/helloworldaction [OK]

The current namesapce is '/hi ':

  [ok]http://localhost:8080/struts2/hi/amos/ Helloworldaction
 [ok]http://localhost:8080/ struts2/helloworldaction [NO]

Summary: For the Action access rule (* indicates any path):

*/*/helloworldaction can satisfy the '/' namespace

*/hi/*/helloworldaction can satisfy the '/hi ' of the namespace, a sentence summary is as long as contains namespace,strust2 will automatically match.

In addition, namespace defaults to "/" and does not assign values to this property.

2), <action> do not specify the class attribute what would be the result?

As shown above, if you do not specify a class value, the 404 status value is returned. You can also see that the default value for the class attribute is "Com.opensymphony.xwork2.ActionSupport"

If you do not write the class attribute value, and you return the correct result, you must add the results attribute in <action>, and the value must be "success" as follows:

<package name= "com.amos.web.action" namespace= "extends=" Struts-default "> <action name=
        " Helloworldaction "method=" "Execute" >            <result name= "Success" >
                suc.jsp            </result>

In addition, you need to change the return value of the Excute method to "success," as follows:

    Override the Execute () method public
    String execute () throws Exception {
        System.out.println ("Welcome to struts2!");        Return "Success";

Then in the WebApp directory to create a new suc.jsp, in the body to join the "Success!! "Run the code, and the results are as follows:

It is well known that the class attribute value is not required, but it is recommended that you assign a value to the class attribute to avoid unnecessary hassles.

The difference between Struts1 and struts2:

Comparison of Struts2 and Struts1

1, in the Action implementation class:

STRUTS1 requires the action class to inherit an abstract base class; A specific problem with STRUTS1 is the use of abstract classes to program

Rather than an interface. The STRUTS2 action class can implement an action interface, or it can implement other interfaces that make optional and custom services possible.

STRUTS2 provides a actionsupport base class to implement commonly used interfaces. Even if the action interface is not necessarily implemented, only one contains

The Pojo class of the Execute method can be used as a Struts2 action.

2, Threading mode aspect:

The Struts1 action is a singleton pattern and must be thread-safe because only one instance of the action handles all requests. A single example strategy limits what Struts1 action can do, and is particularly careful when developing. The action resource must be thread-safe or synchronized; The Struts2 action object produces an instance of each request, so there is no thread-safe issue.

3,servlet Reliance Aspect:

The Struts1 action relies on the servlet API because there are httpservletrequest and HttpServletResponse methods in the Execute method of the Struts1 action.

The STRUTS2 action no longer relies on SERVLETAPI, allowing the action to run away from the Web container, thereby reducing the difficulty of testing the action. Of course, if the action requires direct access to the HttpServletRequest and HttpServletResponse parameters, the Struts2 action can still access them. But most of the time, the action doesn't need to be accessed directly

HttpServletRequest and HttpServletResponse, thus giving developers more flexibility to choose from.

4, can test the aspect:

A major problem with testing the STRUTS1 action is that the Execute method relies on the servlet for Servletapi, which makes the test still dependent on the Web container. To get out of the Web container test Struts1 action, you must use a third party extension: Struts TestCase, which contains a series of mock objects that break away from the Web container to test the Struts1 action class.

Struts2action can be tested by initializing, setting properties, and invoking methods.

5, encapsulation request parameter aspect:

Struts1 uses the Actionform object to encapsulate the user's request parameters, and all actionform must inherit a

Base class: Actionform. Ordinary JavaBean cannot be used as actionform Therefore, developers must create a large number of actionform classes to encapsulate user request parameters. Although STRUTS1 provides dynamic actionform to simplify the development of actionform, it is still necessary to define Actionform in the configuration file. STRUTS2 directly uses the action attribute to encapsulate user request attributes, avoiding the complexity of developers needing to develop actionform classes, which can actually be rich object types that contain child attributes. If developers still miss the Struts1 Actionform model

Struts 2 provides a modeldriven mode that allows developers to use a separate model object to encapsulate a user request parameter, but the model object does not inherit any Struts2 base class, is a pojo, and thus

Reduced code contamination.

6, the expression of language:

Struts1 consolidates Jstl, so you can use the JSTL expression language. This expression language has a basic object graph

Calendar, but not powerful in support of collections and indexed properties

Struts2 can be used Jstl, but it incorporates a more powerful and flexible expression

Language: OGNL (Object Graph notation Language), so the expression language is more powerful under STRUTS2.

7, binding values to the view aspect:

STRUTS1 uses the standard JSP mechanism to bind objects to the view page;

Struts2 uses the "Valuestack" technology to enable labels to access values without the need to bind objects and view pages together.

8, the aspect of the type conversion:

The Struts 1 Actionform properties are usually string types. Struts1 use

Commons-beanutils is a type conversion that supports the conversion between basic data types and common objects.

9, data verification aspects:

STRUTS1 supports manual checksums in the Actionform rewrite validate method, or by consolidating the Commonsalidator framework to complete data validation.

STRUTS2 supports validation by rewriting the validator method, and also supports the consolidation of Xwork validation framework for validation

10,action the aspect of execution control:

STRUTS1 supports each module for one request processing (the concept of life cycle), but all the action in the module must share the same lifecycle.

STRUTS2 supports the creation of an impassability lifecycle for each action through the interceptor stack. Developers can create a corresponding heap search as needed to work with different action.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.