Struts2.x tutorial (I) Struts2 Introduction

Source: Internet
Author: User

Struts2.x tutorial (I) Struts2 Introduction
I. What is Struts2?Struts2 is developed based on WebWork2. Like Struts1, Struts2 is also a web layer framework based on MVC. Now that we have Struts1, why do we need Struts2? Although both Struts2 and Struts1 are based on MVC Web frameworks, their implementation mechanisms are completely different. Struts1 is implemented based on Servlet, and Struts1 API is too dependent on containers, resulting in complicated Action development and testing. Struts2 is implemented based on filters and APIs are no longer dependent on containers, the Web Container environment does not need to be simulated during the testing process. Development and testing are much more advanced than Struts1. The Action of Struts1 shares an ActionServlet for all requests in the singleton mode. Therefore, the thread must be secure, and each request of Struts2 is bound to an Action, so there is no thread security issue. Struts2 began to support annotation and provides a more powerful OGNL tag library and value stack. The development from class to page is more concise and efficient. Both Struts2 and Struts1 are based on the MVC Web layer framework. Therefore, they work in the same principle. They all intercept, distribute, and process requests, and then return to the page, however, their implementation mechanisms are different. Therefore, the working principle of Struts2 is not described too much. Let's look at how to use Sturts2 to build a Web development environment.Ii. Use of Struts2Let's first use Sturts2 to display a Helloworld. 1. Create a web project struts2_helloworld and add support for Struts2 dependencies.

Struts2-core-2.3.8.jarxwork-core-2.3.8.jarcommons-lang3-3.1.jarognl-3.0.6.jarjavassist-3.11.0.GA.jarasm-3.3.jarasm-commons-3.3.jarasm-tree-3.3.jarfreemarker-2.3.19.jarcommons-fileupload-1.2.2.jarcommons-io-2.3.jar
2. Configure struts2 in web. xml

Name> Struts2 Name>
Class> Org. apache. struts2.dispatcher. ng. filter. StrutsPrepareAndExecuteFilter Class>


Name> Struts2 Name>
< Url-Pattern> /* Url-Pattern>
3. Create the struts. xml configuration file Struts2

DOCTYPEStruts PUBLIC
"-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN"
Http://struts.apache.org/dtds/struts-2.1.dtd>

Name= "Default" namespace = "/" extends = "struts-default">
< Action Name= "Hello" Class= "Com. boya. struts2.web. HelloAction">

/HelloWorld. jsp

Action>

Note that, unlike Struts1, the configuration file of Struts2 is not placed in the WEB-INF directory, but needs to be placed in the src Source Code root directory 4, create Action class
Public class HelloAction {
Public String execute (){
Return "success ";
}
}
5. Create the return page helloWorld. jsp and now a simple Struts2 application is completed. Start the Web server and access http: // localhost: 8080/struts2_helloworld/hello to see the helloWorld. jsp page we created. Iii. Introduction to Sturts2 Configuration 1. Configure Strut2 filter interception in web. xmlSturts1 intercepts requests through servlet ing, and Struts2 intercepts requests through filters. The former loads the core configuration file in ActionSerlvet, and the latter loads it in the StrutsPrepareAndExecuteFilter filter. Therefore, unlike Struts1, We need to configure the Filter of Struts2 in web. xml to intercept requests. For the configuration method, see the preceding section. 2. Strtus2 core configuration fileThe default configuration file of Struts2 is struts. xml, which must be placed in the source code root directory. The action tag in struts. xml works the same as that in Struts1. It defines a ing relationship. The package label indicates that the action and interceptor are managed in the form of a package. Generally, a group of business actions related to logic are managed in the same package as a module. The package has the following attributes: name: package name. Other packages use name to inherit the current package and cannot duplicate the namespace: defines the namespace of the current package and matches the path of the request URL, different namespaces can have multiple actionextends: the parent package inherited by the current package. After inheritance, the current package has any classes and interceptors defined in the parent package. abstract: define the current package as an abstract package. That is to say, there cannot be any action element in the current package. The action attribute: name: action name is used to match the request URLclass: specific Action implementation class, the default value is actionsuppmethod method: The method called when the action is executed. The default value is execute (). You can also specify it dynamically in the URL. For example, add the user result Tag: Define the return jump Page name of the action: define the page Jump name. The default value is success. Return a string with the corresponding name in the action, and the corresponding jsp page type will be returned: Set the type of the returned result, the default is dispatcher, used to return the jsp page 3. URL ing mechanismIn Struts1, we use path to map URL requests. In Struts2, The namespace + action name is used to map URLs. For example, if namespace = "/system" and action is set to "/user", the URL corresponding to this action is http: // host address/project name/system/user namespace addressing mechanism: For a URL request, such as http: // Host address/project name/path1/path2/path3/userStruts2 will automatically remove the Suffix in the URL and Host and project name, consider/path1/path2/path3 as a namespace. First, the namespace = "/path1/path2/path3" will be searched. If the namespace cannot be found, the system continues searching for namespace = "/path1/path2". If no namespace exists, the system continues searching for the namespace at the upper level until it finds namespace =. When the namespace is found, the namespace package searches for the action of name = "/user. Finally, the request is sent to the business processing class corresponding to the action. By default, namespace is "". If it cannot be mapped in other namespaces, It is searched in this namespace. Struts2 uses namespace and actionName to uniquely distinguish an Action. Therefore, an action with the same name cannot be configured in the same namespace. In different namespaces, there can be a duplicate action. 4. ing mode configurationIn the filter ing of web. xml, in addition to the following Configuration:
Name> Struts2 Name>
< Url-Pattern> /* Url-Pattern>
You can also configure the extension:
Name> Struts2 Name>
< Url-Pattern> *. action Url-Pattern>
Action is the default extension supported by struts2. /* Provides additional support for *. action basic ing.
A. It is used to access specific static resources in classpath (if it is a resource starting with/struts or/static, search for matched resources under a specific package in classpath ;) b. Support/* ing for action requests without suffixes: access the/struts or/static directory and do not want to load the static resource configuration method of strtus. You want to forcibly configure extension ing You can also use the preceding configuration to modify the default extension of struts2. When you do not want to map a directory (the directory must be a regular expression, so it must be represented) 5. Action Method ingA. the method ing of Action can be specified through method. If the method is not specified, execute () method B is executed by default. The ing method can also be dynamically specified in the URL (DMI is called by a dynamic method) for example, access http: // localhost: 8080/struts2_helloworld/hello! Print calls the print () method in the Action corresponding to hello. Note: You can use the struts. enable. DynamicMethodInvocation parameter to enable or disable DMI. It is enabled by default. C. Use wildcard ing /{0}. jsp Use {1} {2} {3 }... {9} matches * in the order of {9}, and {0} matches the whole. Note: The Struts2 wildcard configuration method is extremely inflexible and is not recommended. 6. Set the return result type.The type of the returned result can be configured through the type attribute of the result tag. The default type is dispatcher, which is used to return the jsp page. Common types of returned results include redirect, chain, json, and other redirect configurations (redirect to a new URL request ): /Hello. jsp? Name =$ {name}
/Hello. action
RedirectAction type configuration (redirect to other actions ): / User Login Boya 123456 Chain type configuration, configuration is similar to redirectAction (chain to other actions, that is, the forwarding operation ): / User Login Json type configuration a, add struts2-json-plugin-2.3.8.jar B, Action code (omit getter, setter method, omit User entity class ):
Public ClassJsonAction ExtendsActionSupport {
PrivateMap DataMap;

PublicString json (){
DataMap = NewHashMap ();
User user = NewUser ();
User. setName ("Zhang San ");
User. setAge (50 );
DataMap. put ("user", user );
ReturnSUCCESS;
}
}
C. Configure struts. xml
Name= "Json" extends = "struts-default, json-default">
< Action Name= "Json" Class= "Com. boya. struts2.web. JsonAction">
Type= "Json">
< Param Name= "Root"> dataMap Param>

Action>
The package must inherit the "json-default" result type and be configured as the json result parameter: root: Specifies the returned attribute. By default, the return value of all getter methods with returned values excludeNullProperties is: whether the returned value is an empty attribute. The value is boolean type ignoreHierarchy: whether to ignore the parent attribute. The value is boolean type includeProperties, which specifies the attributes in the returned root, and the value is a regular expression, you can use commas to separate multiple excludeProperties: Specify which attributes of root are excluded. The value is a regular expression. You can use commas to separate multiple d and return content: {"user ": {"age": 22, "name": "Zhang San" }} differences between excludeProperties and includeProperties: first, assume that the returned result in dataMap is {"users ": [{"age": 22, "name": "Zhang San", "password": "123456" },{ "age": 40, "name": "Li Si ", "password": "654321"}]} after the excluded or included attributes are set, the elements to be verified in the preceding results include users, users [0], and users [0]. age, users [0]. name, users [0]. password, users [1], users [1]. age, users [1]. name, users [1]. password to exclude the password attribute, you must set Users. * \. password, ExcludeProperties is to use the regular expression as the whole to match the above elements separately, so that the password will be excluded. If you want to include only the name attribute, you cannot set it Users. * \. name, IncludeProperties will split the regular expression into users. *. users. *\. name (delimiter, array index, and point connector between object attributes). The two regular expressions match those of the above elements, and users. * All elements are matched, so they cannot be excluded. To precisely include the name attribute, you must set it: Users \ [\ d + \] \. nameIn this case, the regular expression is split into users, users \ [\ d + \], users \ [\ d + \] \. name, and only the name attribute is output. Iv. Action Processing1. Receive parameter a. Use properties to receive parameters. For example, define the following attributes in UserAction and add the getter and setter Methods private String name; PrivateString password; the User Name of the control whose jsp name is used
Password
In this way, the submitted parameter values can be passed to the attributes of UserAction. You can also pass the parameter value to Action through URL, such as: http: // localhost: 8080/struts2-helloworld/user! Save? Name = admin & password = 123456
B. Use DomainModel to receive parameters. For example, to add attributes of the Entity Bean type to UserAction, add the getter and setter methods. Private User user;The jsp Control name is in the form of "object. property", such as the user name
Password
In this way, the submitted parameters are automatically encapsulated in the user object. In the Action method, the user. getName () can be used to obtain the submitted user name using the URL to pass the parameter is in the form of: http: // localhost: 8080/struts2-helloworld/user! Save? User. name = admin & user. password = 123456 2. Obtaining the request and session Struts2 of the web container is not dependent on the container as Struts1 does. By default, the container objects such as request and session are hidden, in addition, the Struts2 layer respectively uses RequestMap and SessionMap to encapsulate requests and sessions. We can use the key-value form of Map to operate requests and sessions. We can obtain RequestMap for use as a request, or obtain an HttpServletRequest object as traditional web development does. A. Non-IoC. This method mainly uses the com. opensymphony. xwork2.ActionContext class and the org. apache. struts2.ServletActionContext class to obtain RequestMap and HttpServletRequest objects respectively. Obtain the RequestMap and SessionMap objects Map request = (Map) ActionContext. getContext (). get ("request"); Map session = ActionContext. getContext (). getSession (); get HttpServletRequest and HttpSession object HttpServletRequest request = ServletActionContext. getRequest (); HttpSession session = request. getSession (); B, IoC. This method is similar to SpringIoc control inversion. It uses dependency injection to obtain request and session objects. Obtain the RequestMap and SessionMap objects. The Action must implement the RequestAware and SessionAware interfaces.
PrivateMap request; PrivateMap session; @ Override Public VoidSetRequest (Map request ){ This. Request = request;} @ Override Public VoidSetSession (Map session ){ This. Session = session ;}
Obtain the HttpServletRequest and HttpSession objects. The Action must implement the ServletRequestAware interface.
PrivateHttpServletRequest request; PrivateHttpSession session; @ Override Public VoidSetServletRequest (HttpServletRequest request ){ This. Request = request; This. Session = request. getSession ();}
Sample Code download: Struts2 HelloWorld sample: http://download.csdn.net/detail/boyazuo/7689429Struts2 Json sample: http://download.csdn.net/detail/boyazuo/7689925

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.