Summary of STRUTS2 Learning knowledge points

Source: Internet
Author: User
Tags exception handling file upload gettext i18n regular expression save file

1The global logical controller is a filter that is responsible for filtering all requests. The API class referenced by this filter is
Org.apache.struts2.disapatcher.FilterDispatcher

2. MVC: Page request (JSP)--Logic controller (Filter)--Business controller (Action)--business logic components--Business process/dao

3The. Struts2 configuration file is placed under Classpath.

4Type conversions for. STRUTS2:
A. Inherit Defaulttypeconverter,
public Object Convertvalue (Map context, object value, Class ToType) method that overrides the parent class
B. Inheriting Strutstypeconverter,
Overrides the parent class's public Object convertfromstring (Map context, string[] values, class Toclass)
This method is responsible for converting the data passed from the page.
Public String converttostring that overrides the parent class (Map context, Object O)
This method is responsible for converting the data processed in the action into a string of the appropriate format.

5Data validation for. STRUTS2:
A. Use the encoding method for validation. The Business controller action inherits the Actionsupport class, overriding the public void Validate () method.
Data validation is performed in this method. If the method for handling business in action is test, you can write public void validatetest ()
method to validate the data of the test method. (After the Validatetest method is executed, the Validate method is followed and
To execute the appropriate business code. )
If there is a serious error, you can call Addfielderror or call the Addactionerror method to add the appropriate error message.
B. Use the configuration XML file for validation. The name of the validation file is: Xxxaction-validation.xml. Validation includes field validation and non-field validation.
Where field validation indicates that certain types of validation are performed on a field. Non-field validation indicates that a field is validated with a type of validation. Two different ways
The lower level implementation is the same, but the way of expression is different, the field verification method is more intuitive.
There are several types of validation: Required,requiredstring,int,date,double,expression,fieldexpression
Email,url,visitor,conversion,stringlength,regex (regular expression).
For a validation type, you can specify the Shourt-circuit parameter to True to perform a short-circuit validation.
If the method that executes the business in Action is test, you can write the Xxxaction-test-validation.xml method to make the data of the test method
Verify. The validation of the default validation file Xxxaction-test-validation.xml is also performed after the private validation file of the test method is executed.
C.struts2 the client for verification. First you need to use the STRUTS2 tag library, and the tag library's Theme property cannot be simple, then set the label's
The Validate property is true.
Note: The client-side validation of STRUTS2 relies on the server's authentication configuration file.

6. struts2 Interceptors. The Struts2 interceptor is the core of the struts2, and its underlying implementation uses the Java reflection mechanism and dynamic proxy. In the STRUTS2 configuration file
When an interceptor is introduced for an action, the configured default interceptor is not invoked and needs to be manually configured into the action.
Ways to implement STRUTS2 interceptors:
A. Implement the Interceptor interface and implement the Init,destrory and intercept methods.
B. Inherit the Abstractinterceptor class, overriding the Intercept method.
C. Inherit the Methodfilterinterceptor class, overriding the Intercept method. This class can intercept specific methods.
The interceptor stack can contain interceptors and interceptor stacks.

7. File Upload and download:
A. Use the Commons-fileupload and Commons-io packages developed by the Apache organization, and configure the FileUpload interceptor and corresponding upload parameters as required.
For example, upload the file type, upload the size of the file. Multi-File upload can use JS code to modify the list of uploaded files on the page, in action
It uses three lists to save file objects (files), filenames, and file types (filecontenttype).
B. File download using stream for reading: return ServletActionContext.getServletContext.getResourceAsStream ("file name")
The result return class of the action is set to stream, which is the stream. Configure the appropriate parameters as needed.

8. The internationalization of struts2. The underlying implementation of STRUTS2 internationalization uses two classes of locale (region) and ResourceBundle (message Resource) in the Java base Class library.
The internationalization of struts2 is mainly used in several places:
A.jsp page: When using the struts2 tag, specify the label's key property (corresponding to the key in the message resource file).
Using <s:text name= "key" >
<s:param></s:param>
</s:text>
The tag gets the message resource information.
You can also use the <s:i18n name= "basename" ></s:i18n> tag to specify a specific message resource file.
B.action: Call GetText (key) or GetText (Key,args) method to get the message resource in the message resource file.
C.xml Validation File: Specifies the key property of the message element (corresponding to key in the Messaging resource file). (How to pass parameters.) )
D. Type conversion process: By viewing the source code of the Xwork package can be found: The Ge.properties file can be found in the following key-value pairs:
Xwork.default.invalid.fieldvalue=invalid field value for field ' {0} '.
Re-specify the key-value pair in the message resource file.
In addition, set the key value to STRUTS.I18N.ENCODING=GBK in Struts.properties, can solve the Chinese garbled problem.

9Exception handling for. Struts2. In action, our business logic processing methods declare exceptions to be thrown. The specific exception corresponds to the specific processing result.
In the action configuration:
<action name= "Upload" class= "uploadaction" >
<result name= "Exception" ></result>
<exception-mapping result= "Exception" exception= "specific exception type" ></exception-mapping>
</action>
You can also configure global exception handling:
<global-exception-mappings>
<exception-mapping result= "" exception= "" ></exception-mapping>
</global-exception-mappings>



Other things to Struts2:
1. For the package in Struts.xml:
A. Set <package abstract= "True" to indicate that there is no action configuration in the package and only one basic public component is defined.
B.package's namespace can separate the different request paths and use more in multi-person collaborative projects. When a request is received,
If there is no corresponding request address in the current namespace, it will go to the default namespace to find a matching address.

2The model-driven mechanism (Modeldriven) encapsulates each parameter in an action into a javabean (similar to struts1.x in
Actionform). The modeldriven<t> interface needs to be implemented and the Getmodel method implemented. When an action implements the Modendriven interface,
The action is intercepted by Modendriveninterceptor and the corresponding parameter is set.

3Prevent duplicate submissions of forms: Set the <s:token name= "* * *" ></s:token> tags in the form of a JSP. And in the corresponding action
Set the token interceptor and the return result named Invalid.token. The key for the corresponding error message is Struts.message.invalid.token.
Configure the key for internationalization.

4The action in the. Struts2 is coupled to the servlet container. There are three main ways of doing this:
A. Implement the Servletrequestaware or Servletresponseaware interface. and provide a familiar setup method for request or response.
B. Use Actioncontext (but cannot get response object). The method is convenient for unit test.
C. Use Servletactioncontext. Servletactioncontext is a subclass of Actioncontext.
Preferred to use Actioncontext, followed by Servletactioncontext.

5. Consolidate multiple struts profiles and use the Include element in the Struts2 configuration file to include additional configuration files. For multi-module development.

6The initialization parameters (deprecated) can be set on the STRUTS2 core filter filterdispatcher in Web. Xml.

7. Dynamic method Invocation (dynamicmethodinvocation).
A.action specified in configuration: <action name= "xxx" method= "" >
B. On the client-side page designation: <s:form action= "Method!actionname" >
C. Using wildcard characters: <action name= "*login" class= "com.action.LoginAction" method= "{1}";
If the action URL is hellologin, call Loginaction's Hello to handle the business. This method simplifies the configuration, but
Makes the program unclear and does not advocate the use of this method.

8The result type of the. struts2. In the Struts2-core package, there are several types of results that struts2 have already configured.
The default type is dispatcher, and also: Redirectaction,chain,freemaker,httpheader,redirect,
Redirectaction,stream,velocity,xslt,plaintext.

9. STRUTS2 integration with spring. Import the Struts2-spring-plugin package, set the spring Listener in Web. XML,
The API class for the Spring listener is: Org.springframework.web.context.ContextLoaderListener.
The Struts2-spring-plugin package sets the Struts2 object factory as the spring IOC container with the following code:
<struts>
<bean type= "com.opensymphony.xwork2.ObjectFactory" Name= "Spring" class= " Org.apache.struts2.spring.StrutsSpringObjectFactory "/>

<!--make the Spring object factory the automatic default---
<constant name= "struts.objectfactory" value= "Spring"/>

<package name= "Spring-default" >
<interceptors>
<interceptor name= "autowiring" class= "Com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" />
<interceptor name= "sessionautowiring" class= " Org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor "/>
</interceptors>
</package>
</struts>
It is clear that the struts.objectfactory is positioned as a org.apache.struts2.spring.StrutsSpringObjectFactory
The rest of the work was given to the spring IOC container.
Also: When we need to add the spring configuration file, we need to set the Contextconfiglocation parameter in Web. Xml. The code is as follows:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> Other spring profile names, separated by commas </param-value>
</context-param>


Some places to be aware of
1The storage Fielderror is a linkedhashmap<string,arraylist>; and actionerror is stored in a ArrayList.
The Getfielderror method in Actionsupport returns a new collection. The collection is a copy of the original Fielderror collection.
In the source code of STRUTS2, you return the following: New Linkedhashmap (Internalgetfielderror), which is a collection object.
So the execution code: This.getFieldErrors.put ("username", "errormsg"), does not affect the data of the original Fielderror collection.

2If an action registers a preresultlistner, it invokes the logical code of the corresponding result validation when the action returns.

3The default.properties and Struts-default.xml files in the. Struts2-core package Save some struts2 default configurations.
The corresponding configuration can be overwritten or reset in its own struts profile. For example, modify the request suffix name: in struts.properties
Join in:
Struts.action.extension = Do
The suffix name of the STRUTS2 request is modified to form the Do suffix name in struts1.

4Configure Struts.multipart.saveDir in the configuration file to set the storage location of temporary files when uploading files. Files under this path need to be cleaned up periodically.

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.