Basic struts knowledge

Source: Internet
Author: User

1. Entry to the Struts framework:
1 JSP page:
Hello. jsp: <a href = "$ {pagecontext. Request. contextpath}/Hello. Action"> entry to struts </a>
Success. jsp: Result processing page
2. Configure the front-end configurator in Web. xml:
</Welcome-file-List>
<Filter>
<Filter-Name> struts2 </filter-Name>
<Filter-class> org. Apache. struts2.dispatcher. Ng. Filter. strutsprepareandexecutefilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-Name> struts2 </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>

3. Struts configuration file: distribute requests
<Struts>
<Constant value = "false" name = "struts. Enable. dynamicmethodinvocation"/>
<Constant value = "false" name = "struts. devmode"/>
 
<Package name = "default" namespace = "/" extends = "struts-Default">
<! -- <A href = "$ {pagecontext. Request. contextpath}/Hello. Action"> get started with struts2 </a> -->
<! -- Distribute the request to an action -->
<! -- The name of the action is hello. Action. Remove the extension -->
<Action name = "hello" class = "cn. itcast. struts2.demo1. helloaction">
<Result name = "hehe">/success. jsp </result>
</Action>
</Package>
</Struts>

4 Java class:
Helloaction:
Package CN. itcast. struts2.demo1;

Public class helloaction {
Public String execute (){
System. Out. println ("hello ");
Return "hehe ";
}
}

Use of the config Brower plug-in
(Omitted, easy to understand)

2 struts2 running process analysis
1. Running Process
Request ---- strutsprepareandexecutefilter core controller ----- interceptors Interceptor (implementing code functions) ----- execuute of Action --- result page result
* Interceptor defined in struts-default.xml
* The Interceptor is referenced in defaultstack.

---- Source code-level breakpoint debugging proves that the interceptor is executed

2. Configure struts. XML to prompt for Problems
If the Aptana editor is installed, do not use the XML editor provided by Aptana to compile the struts2 configuration file.
The Struts. xml prompt comes from the DTD constraint,
<! Doctype struts public
"-// Apache Software Foundation // DTD struts configuration 2.3 // en"
Http://struts.apache.org/dtds/struts-2.3.dtd>
If you can access the Internet, the DTD is automatically cached and the prompt function is provided.
If you cannot access the Internet, you can configure the local DTD prompt.

* ** When importing a DTD, it should be consistent with the configuration of the DTD version.

3. Associate struts2 source code
Associated zip package

4. Use the config Brower plug-in
Allows you to view struts2 configuration loading information in a browser.

Copy the extracted struts2/lib/struts2-config-browser-plugin-2.3.7.jar under the WEB-INF/lib

Access http: // localhost: 8080/struts2_day1/config-Browser/index. Action to view struts2 configuration Loading

Iv. Common struts2 configurations
Learning path
1) struts. xml constant configuration (configuration file sequence), Action access (servlet API), and result set (use struts2 to write simple cases)
2) request data
3) response page generation

1. Order of loading struts2 configuration files
The struts2 configuration file is loaded by the core controller strutsprepareandexecutefilter (preprocessing, filtering)
Init_defaultproperties (); // [1] ---------- ORG/Apache/struts2/Default. Properties
Init_traditionalxmlconfigurations (); // [2] --- struts-default.xml, struts-plugin.xml, Struts. xml
Init_legacystrutsproperties (); // [3] --- custom struts. Properties
Init_customconfigurationproviders (); // [5] ----- custom configuration provides
Init_filterinitparameters (); // [6] ----- web. xml
Init_aliasstandardobjects (); // [7] ---- bean Loading

Conclusion:
Default. properties this file is saved in the org. Apache. struts2 package in the struts2-core-2.3.7.jar
(Default value of a constant)
Struts-default.xml this file is saved in the struts2-core-2.3.7.jar (bean, interceptor, result type)
Struts-plugin.xml this file is saved in the struts-Xxx-2.3.7.jar (exists in the plug-in package, configure plug-in information)

Struts. XML: this file is the default struts configuration file for Web applications. XML )******************************
Struts. properties this file is the default configuration file of struts (configuration constant)
Web. xml this file is the Web application configuration file (configuration constant)

* The struts2 constant in the uploaded file overwrites the content of the previously loaded file constant.

3. Complete action configuration in struts. xml
1) The <package> element must be configured for the <action> element (struts2 configures the action around the package)
Configure three common attributes of a package
<Package name = "default" namespace = "/" extends = "struts-Default">
Name package name. The package name in the struts2 configuration file cannot be the same. Name is not the real package name, just to manage the action
The name attribute of namespace and <action> determines the access path of the action (start)
Extends inherits which package, usually development inherits Struts-default package (Struts-default package defined in struts-default.xml)
* After inheriting the Struts-default package, you can use the package to define the interceptor and result type.
2) configure the action through the <action> element
<Action name = "hello" class = "cn. itcast. struts2.demo1. helloaction">
The name of <action> and the namespace attribute of <package> jointly determine the action access path !!!!!!!!
 
For example:
<Package name = "default" namespace = "/user" extends = "struts-Default">
<Action name = "hello" class = "cn. itcast. struts2.demo1. helloaction">
Access path/user/Hello. Action
3) <action> default value of element configuration
<Package> namespace default value/
The default value of <action> class is actionsupport class.
<Result> default value of name success
 
3. Default processing classes for action and action
1) The default action solves the problem that the client access action does not exist. If the client accesses the action and the action cannot be found, the default action will be executed.
<Default-action-ref name = "Name of the Action Element"/>

2) The default processing class. When the client accesses the action, the matching <action> element has been found, but the <action> element does not have the class attribute, and the default processing class is executed.
<Default-class-ref class = "complete Class Name"/>
* Configure the default processing class actionsupport in struts-default.xml

Configure the default action code:
<Action name = "hello" class = "cn. itcast. struts2.demo1. helloaction">
<Result name = "hehe">/success. jsp </result>
</Action>
<Default-action-ref name = "error"> </default-action-ref>
<Action name = "error" class = "processing class address"> </Action>


4 common Constants
<Constant name = "struts. i18n. encoding" value = "UTF-8"/> ----- equivalent to request. setcharacterencoding ("UTF-8"); handle POST request garbled
<Constant name = "struts. Action. Extension" value = "action"/> --- access the struts2 Framework Action access path extension (required)
* Struts. Action. Extension = action. By default, the extension ending with. Action and the unspecified extension are distributed to action.
<Constant name = "struts. Serve. Static. browsercache" value = "false"/> "false" does not cache. "True" indicates that the browser caches static content, and sets "true" for the product environment and "false" for the development environment.
<Constant name = "struts. devmode" value = "true"/> provides a detailed error page. After modifying struts. XML, you do not need to restart the server (required)

5. struts2 configuration file Separation
Split the struts2 configuration file by <include file = "struts-part1.xml"/>

6. Action access
HTTP request submission struts2 strutsprepareandexecutefilter core controller ------ request distribution to different actions

1. enable requests to access action-action writing methods
The first action can be a pojo (plainoldjavaobjects) simple Java object) ---- No need to inherit any parent class and implement any interface
* The struts2 framework reads struts. XML to obtain the complete action class name.
* OBJ = Class. forname ("full class name"). newinstance ();
* Method M = Class. forname ("full class name"). getmethod ("execute"); M. Invoke (OBJ); execute the execute method through reflection

Second, write the action to implement the action interface.
Define the default five logical view names in the Action Interface
Public static final string success = "success"; // data processing succeeded (successful page)
Public static final string none = "NONE"; // return NULL is not redirected to the page; the effect is the same
Public static final string error = "error"; // data processing sending error (error page)
Public static final string input = "input"; // incorrect user input data, which is usually used for form data validation (input page)
Public static final string login = "login"; // main permission authentication (login page)

* Five logic views. After processing data by action, jump to the page

Third, write action to inherit actionsupport (recommended)
In action, form verification, error information setting, and international information reading are used.

7. Call the Action Method
1) when the <action> element is configured, the method attribute is not specified. By default, the execute method in the action class is executed.
<Action name = "request1" class = "cn. itcast. struts2.demo3. requestaction1"/>
2) Add the method attribute inside the <action> element to specify the method in which the action is executed.
<Action name = "regist" class = "cn. itcast. struts2.demo4. registaction" method = "regist"/> the regist Method for executing registaction
* Write multiple request business methods to an action class
<Action name = "addbook" class = "cn. itcast. struts2.demo4. bookaction" method = "addbook"> </Action>
<Action name = "delbook" class = "cn. itcast. struts2.demo4. bookaction" method = "delbook"> </Action>
 
3) Use wildcard * to simplify struts. xml configuration
<A href = "$ {pagecontext. Request. contextpath}/user/customer_add.action"> Add a customer </a>
<A href = "$ {pagecontext. Request. contextpath}/user/customer_del.action"> delete a customer </a>
 
Struts. xml
<Action name = "customer _ *" class = "CN. itcast. struts2.demo4. customeraction "method =" {1} "> </Action> --- {1} is the first * Matching content.
Dynamic method call (no route configuration)
Access the specified method in action and do not configure it
1) Make sure struts. Enable. dynamicmethodinvocation = true
2) use "! Method Name"
Page
<A href = "$ {pagecontext. Request. contextpath}/user/product! Add. Action "> Add product </a>
Configuration
<Action name = "product" class = "cn. itcast. struts2.demo4. productaction"> </Action>
Execute the add method in productaction.
8. Use servlet API in action
1. Indirectly accessing servlet API --------- using actioncontext object in action
In struts2, Action API has been decoupled from servlet API (no dependency)
* Common servlet API operations: Form submission request parameter acquisition, data access to the request, session, and application ranges

Actioncontext = actioncontext. getcontext ();
1) actioncontext. getparameters (); obtain the map set of all Request Parameters
2) actioncontext. Put ("company", "Chuanzhi podcast");/actioncontext. Get ("company") access data within the request range
3) actioncontext. getsession (); obtain the session data map and access the data within the session range.
4) actioncontext. getapplication (); obtain the servletcontext Data Map and access the data of the application.

2. Use interface injection to operate servlet APIs (coupling)
Servletcontextaware: injects the servletcontext object
Servletrequestaware: injects the request object
Servletresponseaware: injects a response object.

* The servlet object used by the program to implement the corresponding interface

3. Get the servlet API directly through servletactioncontext in the action
Servletactioncontext. getrequest (): Get the request object (Session)
Servletactioncontext. getresponse (): Get the response object
Servletactioncontext. getservletcontext (): Get the servletcontext object
* The static method has no thread problems. threadlocal

Conventions and annotations:
1. It is agreed that struts2 provides default rules for Zero Configuration
1) Import jar package 11 jar + struts2-convention-plugin-2.3.7.jar
2) configure the front-end controller in Web. xml
3) Compile the page
4) plugin configuration file
<Constant name = "struts. Convention. Package. locators" value = "action, actions, struts, struts2"/>
Write the action class, which must be included in four packages: Action, actions, struts, and struts2
<Constant name = "struts. Convention. Action. suffix" value = "action"/>
End with action
 
* *** <Constant name = "struts. Convention. Result. Path" value = "/WEB-INF/content/"/> result page storage location
After an action is scanned, how do I determine the access path of the action?
CN. itcast. struts2.helloaction (helloaction is located under four scan packages, namespace is/, and action name is Hello) ----/Hello. Action
CN. itcast. Actions. Books. booksearchaction (booksearchaction is not directly under four scan packages, namespace is/books, and action name is book-search)
* Access path/books/book-search.action
CN. itcast. Struts. User. useraction access/user. Action
CN. itcast. estore. Action. Test. loginaction access/test/login. Action

5) depending on the constant configuration result page is located under/WEB-INF/Content
Page naming conventions: actionname + resultcode + suffix
Example: CN. itcast. Struts. User. useraction ------/user. Action, return success
Results page/WEB-INF/content/user/user-success.jsp --- not found/WEB-INF/content/user/user-success.html --- not found/WEB-INF/content/user. jsp

2. Annotation
Annotation development step 1: automatic scanning based on conventions

Convention only solves the problem of Action access and result page Jump
* In development, you must specify an interceptor for the action to configure the result in more details.
* The conventions are not flexible enough. The annotation function is equivalent to the xml configuration method.

Use the @ action annotation to configure the access path @ result annotation configuration result page:
Code embodiment:
@ Action (value = "login", Results = (@ result (name = "success", location = "/index. jsp ")))

Automatically reload action files:
<Filter>
<Filter-Name> struts2 </filter-Name>
<Filter-class> org. Apache. struts2.dispatcher. Ng. Filter. strutsprepareandexecutefilter </filter-class>
<Init-param>
<Param-Name> struts. Convention. classes. Reload </param-Name>
<Param-value> true </param-value>
</Init-param>
</Filter>


@ Parentpackage configuration <package> which package does extends inherit?
@ Namespace configuration package namespace

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.