Struts2 technical details

Source: Internet
Author: User
Tags i18n xslt

 

1. When an action sets an attribute, Struts encapsulates these attributes in a property called struts. valuestack. Obtain the valuestack object: valuestack Vs = (valuestack) request. getattribute ("struts. valuestack ");
Call the Vs. findvalue ("books") method of valuestack (books is the attribute in action );

2. The action class of struts2 is a common pojo class (usually contains a non-argument execute method) to reuse code.

4. struts2 usually uses action to encapsulate HTTP Request Parameters. Therefore, the action must define the attributes corresponding to the Request Parameters and provide corresponding getter and setter methods for the attributes.

5. Even if the request name and pass parameters to be processed by the action are two HTTP request parameters, the action class may not contain the name and pass attributes, because the system uses the corresponding getter and setter methods to process request parameters. Instead of Processing request parameters through properties. Therefore, it is not important for the action class to include the name and pass attributes. It is important to use the setter and getter methods.

6. The properties of the action class can not only encapsulate request parameters, but also encapsulate processing results and output corresponding property values through the struts2 tag. For example, <s: property value = "tip">.

7. actioncontext class. The struts2 action is not directly coupled with any servlet API, making it easier to test the action (you can test the action by leaving the Web container ). However, for Web application controllers, it is almost impossible to access servlet APIs. For example, tracking the http session status. The accessed servlet APIs are httpserveltrequest, httpsession, and servletcontext. These three classes are request, session, and application in the JSP built-in objects respectively. The Web application provides an actioncontext class. The struts2 action can access the servlet through this class.
API.
The actioncontext of this class provides the getcontext method to get the actioncontext instance,
Methods for this class:
① Object get (Object Key), which is similar to the getattribute (string name) method of httpservletrequest;
② Map getapplication (), returns the map object, which simulates the instance of the application's servletcontext
③ Static actioncontext getcontext (): obtains the actioncontext instance provided by the system.
④ Map getparameters () obtains all request parameters, similar to calling the getparammetermap method of the httpservletrequest object.
⑤ Map getsession () the map object simulates the httpsession instance.
⑥ Void setapplication (map application) directly transmits a map instance and converts the key-value pair of the map instance to the attribute name and attribute value of the application. Similarly, setsession (MAP session)
7. Put (Object key, object Value) directly sets attributes for httpservletrequest. It is equivalent to request. setattribute (Key, value). It can be output through El expression.

8. servletactioncontext class (a subclass of the actioncontext class ). Although struts2 provides actioncontext to access servlet APIs, such access cannot directly obtain servlet API instances. to directly access servlet APIs in action, struts2 provides the following interfaces: servletcontextaware, servletrequestaware, and servletresponseaware. If action implements these interfaces, it can directly access the servletcontext, httpservletrequest, and httpservletresponse instances requested by the user.
In addition, to directly access the servlet API. Struts2 provides a servletaction class. Through the servletactioncontext class, you can access the servlet API more conveniently. This type of main method (all static ):
① Getactioncontext (httpservletrequest req) obtains the current actioncontext instance.
② Getactionmapping () obtains the actionmapping instance (the Action mapping is context ).
③ Getrequest () obtains the httpservletrequest instance (gets the HTTP Servlet request object ).
④ Getresponse () Get the httpservletresponse instance (gets the HTTP servlet response object .)
⑤ Getservletcontext () Get the servletaction instance (gets the servlet context .)
⑥ Getvaluestack (httpservletrequest req) gets the valuestack instance.
7. setrequest (httpservletrequest request) (sets the HTTP Servlet request object) includes setresponse (httpservletresponse response) and setservletcontext (servletcontext ).

9. Although httpservletresponse can be obtained in the action class, it is impossible to generate server response through httpservletresponse because action is only a controller (it does not directly generate any corresponding response to the browser ). That is, if you write the following code in the action: Response. getwriter (). println ("Hello World ");
Is meaningless.

10. For applications that use the struts2 framework, try not to link a hyperlink to a view resource,
This method adds additional risks. We recommend that you send all requests to the struts2 framework so that the framework can process user requests,
Even a simple hyperlink.

11. logical view name refers to the string returned by action, and physical view refers to the actual name of the page.
Struts2 configures the ing between the logical view name and the physical view. Once the system receives a logical view returned by the action, the system displays the corresponding physical view to the user.

12. Default Value: If <result .. /> If the location parameter is not specified for the element, the system will set <result...>... <result .. /> the string in the middle is used as the actual view resource. If the parse parameter is not configured, the default value is true (this parameter specifies whether the actual view name can use the ognl expression ); if the name attribute is not specified, the default value is the default processing result type (dispacher) of struts2 ).

13. To sum up, struts2 supports the following built-in result types (14 ):
① Chain result type: type of action chain processing result.
② Chart result type: The result type used to integrate jfreechart.
③ Dispatch result type: The result type used for JSP integration.
④ Freemarker result type: The result type of freeamarker integration.
⑤ Httpheader result type: The result type used to control HTTP behavior.
⑥ Jasper result type: The result type used for jasperreports integration.
7. JSF result type: The result type used to integrate JSF integration.
Optional redirect result type: The result type used to directly jump to another Uri.
⑨ Redirectaction result type: it is used to directly jump to the result type of other actions.
⑩ Stream result type: it is used to return an inputstream to the browser (generally used for file download ).
⑾ Tiles result type: The result type used for integration with tiles.
⑿ Velocity result type: The result type used for integration with velocity.
⒀ XSLT result type: The result type used for integration with XML/XSLT.
⒁ Plaintext result type: The result type used to display the original code of a page.

14. [redirect] result type.
This result type is opposite to the dispatch result type. The dispatch result type is to forward the request)
To the specified jsp resource. The redirect result type means the request redirect (redirection)
To the specified view resource.
The difference between the dispatch result type and the Redirect result type is the difference between forwarding and redirection:
Redirection will lose all request parameters and attributes-of course, the processing result of the action will also be lost.
The effect of using the Redirect result type is that the system will call the sendredirect (string) method of httpservletresponse to redirect the specified view resource. The effect of this redirection is to generate a new request. Therefore, all the attributes encapsulated in request parameters, request attributes, Action instances, and actions are lost.

15. [redirectaction] result type.
When the redirectaction result type is used, the system will generate a new request,
The request URI is not a specific resource but an action. Therefore, the processing result of the previous action
, Request parameters, request parameters will be lost.

16. Besides configuring action (result) with wildcards, you can also use ognl expressions.
The usage allows request parameters to determine the result. For example:
<Action name = "save" class = "..." method = "save">
<Result name = "input">/. jsp </result>
<Result type = "Redirect"> edit. Action? Skillname =$ {currentskill. name} </result>
</Action>
For the above expression syntax, the corresponding action instance must contain the currentskill attribute, and the currentskill attribute must contain the name attribute -- otherwise, the $ {currentskill. name} expression is null.

17. model-driven:
For the actionform object of struts1. The unique function of struts1 is to encapsulate Request Parameters. After struts1 intercepts a user's request, struts1 encapsulates the request parameters as actionform objects.
If struts2 developers miss this development method, they can use the model-driven model provided by struts2,
This mode also encapsulates request parameters through a special JavaBean.
Compared with the action class of struts1, the action of struts2 bears too many responsibilities. It is used to encapsulate parameters of back-and-forth requests and protect the control logic. This mode is not clear. For the sake of clarity, a separate model instance should be used to encapsulate Request Parameters and processing results. This is called model-driven.
Role: The model object of struts2 can encapsulate more information. It can encapsulate not only user request parameters, but also action processing results. Use a single JavaBean instance to run through the MVC process.
When model-driven, action must implement the modeldriven interface and the GetModel method,
This method is used to associate an action with the corresponding model instance.
Simply put, the model driver uses a separate VO (Value Object) to encapsulate Request Parameters and processing results.

18. [property-driven ]:
Property is used as the information carrier throughout the MVC process. Of course, attributes cannot exist independently and must be attached to an object, which is an action instance,
To put it simply, property drivers use action instances to encapsulate Request Parameters and processing results.

19. [Exception Handling Mechanism] of struts2 ]:
Manually capture exceptions in the execute method. When a specific exception is caught, a specific view is returned --
This method is cumbersome and requires a large number of catch blocks to be written in execute. The biggest drawback is that
The exception is also coupled with the Code. Once you need to change the exception handling method, you must modify the code!
Struts2 provides a declarative exception handling method.
On the JSP page that outputs error messages, there are two output methods:
① Use the struts2 label to output the message attribute of the exception object. <S: property value = "exception. Message"/>.
② Outputs stack information through the struts2 tag. <S: property value = "exceptionstack"/>.
Note: Do not use partial results for the result attribute of global exception ing. You can use or disable the result attribute of local exception ing.

20. For Web applications, all request parameters are of the string type.

21, [type converter ]:
The struts2 type converter is actually implemented based on ognl. There is a typeconverter interface in the ognl project. Because the implementation method is too troublesome, The ognl project also provides an implementation class for this interface: defatypetypeconverter, which inherits the class to implement its own converter.
To implement custom type conversion, you must override the convertvalue method of the defaulttypeconverter class.

22. The above Type converters are implemented based on the defaulttypeconverter class of ognl.
The convertvalue method is used to convert a string to a type that complies with the actual type.
Therefore, we must first use the totype parameter to determine the conversion direction and then implement different conversion logics.
To simplify the implementation of type conversion, struts2 provides a strutstypeconverter abstract class (class Converter Based on struts2)
This abstract class is a subclass of the defatypetypeconverter class.

23. For the above type conversion, we always only process the first element of the string array-we assume that the request parameter is a single value. In fact, the request parameters must be considered as character arrays. Assume that the request parameters of user information are all named "user. The two request parameters must be obtained through the getparametervalues method. In this case, the user request parameter must be of the array type or list type (in fact, the list and array are completely the same ).

24. Because struts2 supports built-in ognl expressions, you can use another method to convert request parameters to composite types, such as (in the JSP page ):
<Input type = text name = "user. Name"/>, <input type = text name = "user. Pass"/>.
In this way, you can also convert a string to a composite type. Note the following:
① Because struts2 directly needs to create a composite class (User class) instance, the system must construct a construction method without parameters for the composite class.
② If you want to use user. the name request parameter is in the form of user attribute and pass attribute values for the action instance. The setname method must be provided for the combination type corresponding to the user attribute, struts2 assigns values to attributes through this method class. Of course, the action class should also contain the setuser method.

25. The form Element enctype attribute specifies the form data encoding method. The property has the following three values:
① Application/X-WWW-form-urlencoded: This is the default encoding method. It only processes the value attribute values in the form. Using this encoding method, the value of the form field is processed as URL encoding.
② Multipart/form-data: This encoding method processes form data in a binary stream. This encoding method also encapsulates the file content specified by the file field into the request parameters.
③ Text/plain: This encoding method is convenient when the form's action attribute is in the form of mailto: URL. This method is mainly applicable to sending emails directly through the form.

26. By using action to output prompt information on the JSP page, we can
① Add an attribute to the action (set the attribute value through the setxx method), and then output it on the JSP page through the struts2 tag (<s: Properties value = "XX"/>.
② The actioncontext class is used for processing, for example, actioncontext. getcontext. Put (Key, value); then the El expression is used for output.

27. To obtain the value of the action attribute in the form, obtain the context path ]:
① <% = Request. getcontextpath () %>
② You can also get $ {pagecontext. Request. contextpath} through the El expression}

28. Which of the following methods can be used to obtain the [valuestack] object:
① Methods in the servletactioncontext class: static getvaluestack (httpservletrequest req) [gets the current value stack for this request ];
② Methods in the actioncontext class: getvaluestack () [gets the ognl value stack .];
③ Valuestack Vs = (valuestack) request. getattribute ("struts. valuestack ");
(Request. getattribute () returns an object type)

29. [interceptor ]. By default, if we define an interceptor for an action, the interceptor intercepts all methods of the action. In some cases, we do not need to intercept all the methods of the struts2 Interceptor. In this case, we only need to intercept some methods.

30. The [verification] of struts2 can inherit the actionsupport class to override the validate method, and save the error information through the key using the addfielderror method of actionsupport, the error message is output through the fielderror attribute of the struts2 tag on the JSP page. Note: The struts2 verification requires an input page (<result name = "input">) When configuring the action ). This is to verify all methods in the action.
If you want to verify the method specified in the action, change the validate method name to validatexxx, where XXX is the name of the specified method to be verified.

31. Enter the verification process:
① The type converter converts the Request Parameters and assigns the converted values to the properties in the action.
② If an exception occurs during type conversion, the system saves the exception information to actioncontext, And the conversionerror interceptor adds the exception information to fielderrors. No matter whether the type conversion fails or not, it will be transferred to step 3.
③ The system calls the validatexxx method in action through reflection technology.
④ Call the validate method.
⑤ If an error message exists in fielderrors, the system automatically forwards the request to the input view. If there is no error message, the method in action will be executed.
NOTE: If there is no problem in the validate method, but the input page is returned, it may be a problem with type conversion. Therefore, there are two reasons for returning the input view (type conversion problems or verification errors ).

32, based on XML configuration method to verify all the methods in the action, the naming rules of XML files are: ActionClassName-validation.xml
If you only need to validate the method specified in the action, the naming rule for the XML file is: ActionClassName-ActionName-validation.xml. The actionname (logical name of the action ). Its Configuration generally uses wildcards (which helps the experiment ).
① Based on the xml configuration method of validation, if the ActionClassName-validation.xml and ActionClassName-ActionName-validation.xml exist at the same time, the two files are summarized, in the validation. If there is a conflict between the validation rules of the Two XML files, execute the following XML file.
② If action inherits another action, first find the Parent Action validation file, find the child action validation file, and then set 4 (each action has a specified method name or a non-specified method name) files.

33. [internationalization ]. Resource files in the global, action, and package range are internationalized. The naming rule for the properties file is: xxx_language_country.properties (XXX is the User-Defined name, and the second part is the language type .)
I. After defining the international file. XML file configuration <constants name = "struts. custom. i18n. resources "value =" Name of the International File (XXX) "> [This is a global international resource file]. You can display the international information on the JSP page <s: text name = "key"/>.
Ii. You can also use the action class to inherit the actionsupport class, and then call the key (gettext ("key") of the resource file of the gettext method. Then, you can use the El expression to output data on the JSP page.
You can also use the key attribute of the form tag of struts2. For example, <s: textfield key = "key"/> or <s: textarea key = "key"/>
Output international information with placeholders:
① <S: Text name = "key"> <s: param>... </S: Text>
② Use gettext (string key, string [] Str) or gettext (string key, list) of the actionsupport class)

34. International resource files within the package Scope,
In large applications, the entire application has a large amount of content that needs to be internationalized. If we place the internationalized content in the global resource attribute file, obviously, resource files become too large and bloated, which is not easy to maintain. In this case, we need to use packages to organize international files for different modules.
Create a resource file named package_language_country.properties under the Java package. The package is fixed and the language_country is the corresponding language type. Both the package and the sub-package can access the resource file. When the corresponding resource file cannot be found within the package range, it will be searched globally.

35. Resource file in the action range. Create actionclassname_language_country.properties in the action path.
If there are global, package, and Action-range internationalized resource files at the same time, the order of the system search is: Action --> package --> global.

36. The above three configurations are configuration-based internationalized resource files. You can also directly access a resource file without configuration.
Use struts2 labels, such:
<S: i18n name = "XXX">
<S: Text name = "key">
</S: i18n> XXX indicates the prefix of the name of the global range file.
If you want to directly access the international resource files within the package range
<S: i18n name = "com. Johnny. Action. Package">
<S: Text name = "key">
</S: i18n> the package is fixed.

37. ognl expression (Object graphic Navigation language object graph Navigation language). When struts2 accepts a request, it quickly creates actioncontext, valuestack, and action, and stores the action in valuestack, therefore, the ognl expression can quickly access the attributes of the Action instance.
Ognl expressions are generally used with the struts2 tag.
In struts2, the El expression can only access the attributes in the root of ognlvaluestack. That is, the action attribute (because the action attribute is placed in the root attribute of ognlvaluestack ). Use the ognl expression to create a list/map object. <s: Set Var = "" value = "" Scope = ""/> scope specifies the placement range of the variable, it can be application, session, request, page, and action. If no attribute is set, the default value is ognlcontext (ognl context). If ognlcontext is accessed, # is not used. If scope is request..., # is required #. Value: the value assigned to the variable. If this attribute is not available, the value at the top of the valuestack stack is assigned to the variable.

38. To prevent repeated forms, you must first have the struts token tag. Then use the system interceptor.

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.