Basic configuration and type conversion for Struts2 Development

Source: Internet
Author: User

I. default values in Action configuration

<Package name = "csdn" namespace = "/test" extends = "struts-default">
<Action name = "helloworld" class = "cn. csdn. action. HelloWorldAction" method = "execute">
<Result name = "success">/WEB-INF/page/hello. jsp </result>
</Action>
</Package>
1> if no class is specified for action, ActionSupport is used by default.
2> if no method is specified for the action, the execute () method in the action is executed by default.
3> If the name attribute of result is not specified, the default value is success.

Ii. Various forwarding types of result in Action

<Action name = "helloworld" class = "cn. csdn. action. HelloWorldAction">
<Result name = "success">/WEB-INF/page/hello. jsp </result>
</Action>
Result configuration is similar to forward in struts1, but struts2 provides multiple result types. Common types include dispatcher (default), redirect, redirectAction, and plainText.

The following is an example of the redirectAction result type. If the redirected action is under the same package:
<Result type = "redirectAction"> helloworld </result>
If the redirected action is in another namespace:
<Result type = "redirectAction">
<Param name = "actionName"> helloworld </param>
<Param name = "namespace">/test </param>
</Result>
Plaintext: displays the content of the original file. For example, this type can be used when the source code of the jsp file needs to be displayed as is.
<Result name = "source" type = "plainText">
<Param name = "location">/xxx. jsp </param>
<Param name = "charSet"> UTF-8 </param> <! -- Specify the encoding of the file to be read -->
</Result>
You can also use the $ {attribute name} expression in result to access the attributes in action. The attribute names in the expression correspond to the attributes in action. As follows:
<Result type = "redirect"> view. jsp? Id =$ {id} </result>

3. Multiple actions share one view-global result Configuration

When the same view is used in multiple actions, we should define the result as a global view. Global forward is provided in struts1, and similar functions are also provided in struts2:
<Package...>
<Global-results>
<Result name = "message">/message. jsp </result>
</Global-results>
</Package>

Iv. Inject values into the Action attributes

Struts2 provides the dependency injection function for the attributes in the Action. In the struts2 configuration file, we can easily inject values for the attributes in the Action. Note: The property must provide the setter method.
Public class HelloWorldAction {
Private String savePath;

Public String getSavePath (){
Return savePath;
}
Public void setSavePath (String savePath ){
This. savePath = savePath;
}
......
}

<Package name = "csdn" namespace = "/test" extends = "struts-default">
<Action name = "helloworld" class = "cn. csdn. action. HelloWorldAction">
<Param name = "savePath">/images </param>
<Result name = "success">/WEB-INF/page/hello. jsp </result>
</Action>
</Package>
The preceding statement uses the <param> node to inject "/images" to the savePath attribute of the action"

5. Specify the request suffix that requires Struts 2 to process

Previously we used the. action suffix to access the Action by default. In fact, the default suffix can be modified through the constant "struts. action. extension". For example, we can configure Struts 2 to process only the request paths suffixed with. do:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC
"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>
<Struts>
<Constant name = "struts. action. extension" value = "do"/>
</Struts>

If you need to specify multiple request suffixes, multiple suffixes are separated by commas. For example:
<Constant name = "struts. action. extension" value = "do, go"/>

6. elaborate on the definition of constants

Constants can be configured in struts. xml or struts. properties. We recommend that you configure them in struts. xml. The two configuration methods are as follows:
Configure constants in the struts. xml file
<Struts>
<Constant name = "struts. action. extension" value = "do"/>
</Struts>

Configure constants in struts. properties
Struts. action. extension = do

Since constants can be defined in the following configuration files, we need to understand the search sequence of struts2 loading constants:
Struts-default.xml
Struts-plugin.xml
Struts. xml
Struts. properties
Web. xml
If the same constant is configured in multiple files, the constant value configured in the last file overwrites the constant value configured in the previous file.

7. Introduction to common Constants

<! -- Specify the default sequence set, acting on the setCharacterEncoding method of HttpServletRequest and the output of freemarker and velocity -->
<Constant name = "struts. i18n. encoding" value = "UTF-8"/>
<! -- This attribute specifies the request suffix to be processed by Struts 2. The default value of this attribute is action, that is, all requests matching *. action are processed by Struts2.
If you need to specify multiple request suffixes, multiple suffixes are separated by commas. -->
<Constant name = "struts. action. extension" value = "do"/>
<! -- Set whether the browser caches static content. The default value is true (used in the production environment). It is best to disable it during development. -->
<Constant name = "struts. serve. static. browserCache" value = "false"/>
<! -- When the struts configuration file is modified, whether the system automatically reloads the file. The default value is false (used in the production environment). It is best to open the file during development. -->
<Constant name = "struts. configuration. xml. reload" value = "true"/>
<! -- Used in development mode to print more detailed error information -->
<Constant name = "struts. devMode" value = "true"/>
<! -- Default view topic -->
<Constant name = "struts. ui. theme" value = "simple"/>
<! -When integrating with spring, specify that spring is responsible for creating action objects -->
<Constant name = "struts. objectFactory" value = "spring"/>
<! -This attribute sets whether Struts 2 supports dynamic method calls. The default value of this attribute is true. To disable dynamic method calling, set this attribute to false. -->
<Constant name = "struts. enable. DynamicMethodInvocation" value = "false"/>
<! -- Size limit of uploaded files -->
<Constant name = "struts. multipart. maxSize" value = "10701096"/>

8. Specify multiple struts configuration files for the Application

In most applications, as the application scale increases, the number of actions in the system will also increase significantly, resulting in a very bloated struts. xml configuration file. To avoid struts. xml files are too large and bloated to improve struts. for the readability of xml files, we can set a struts. the xml configuration file is divided into multiple configuration files, and then in struts. the xml file contains other configuration files. The following struts. xml uses the <include> element to specify multiple configuration files:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC
"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>
<Struts>
<Include file = "struts-user.xml"/>
<Include file = "struts-order.xml"/>
</Struts>

In this way, we can add the Action of Struts 2 to multiple configuration files by module.

9. dynamic method call

If there are multiple methods in the Action, we can use it! + The method name calls the specified method. As follows:
Public class HelloWorldAction {
Private String message;
....
Public String execute () throws Exception {
This. message = "My first struts 2 Application ";
Return "success ";
}

Public String other () throws Exception {
This. message = "second method ";
Return "success ";
}
}
Assume that the URL path for accessing the preceding action is/struts/test/helloworld. action.
To access the action's other () method, we can call it like this:
/Struts/test/helloworld! Other. action
If you do not want to use dynamic method calls, you can use the constant struts. enable. DynamicMethodInvocation to disable dynamic method calls.
<Constant name = "struts. enable. DynamicMethodInvocation" value = "false"/>

10. Define action using wildcards

<Package name = "csdn" namespace = "/test" extends = "struts-default">
<Action name = "helloworld _ *" class = "cn. csdn. action. HelloWorldAction" method = "{1}">
<Result name = "success">/WEB-INF/page/hello. jsp </result>
</Action>
</Package>
Public class HelloWorldAction {
Private String message;
....
Public String execute () throws Exception {
This. message = "My first struts 2 Application ";
Return "success ";
}

Public String other () throws Exception {
This. message = "second method ";
Return "success ";
}
}

To access the other () method, you can use this URL to access:/test/helloworld_other.action

11. Request receiving Parameters

Receiving Request Parameters Using basic types (get/post)
Define an attribute with the same name as the request parameter in the Action class. Then, struts2 can automatically receive the request parameter and assign it to the attribute with the same name.
The Request Path is http: // localhost: 8080/test/view. action? Id = 78
Public class ProductAction {
Private Integer id;
Public void setId (Integer id) {// struts2 uses the reflection technique to call the setter method of the attribute with the same name as the request parameter to obtain the request parameter value.
This. id = id;
}
Public Integer getId () {return id ;}
}
Request Parameters received using compound types
The Request Path is http: // localhost: 8080/test/view. action? Product. id = 78
Public class ProductAction {
Private Product product;
Public void setProduct (Product product) {this. product = product ;}
Public Product getProduct () {return product ;}
}
Struts2 first calls the default constructor of Product to create the product object through reflection technology, and then calls the setter method of the property in the product with the same name as the request parameter to obtain the request parameter value.

12. Significance of type conversion

For an intelligent MVC Framework, type conversion is inevitable. because the Request Parameters of B/S (Browser/Server) structure applications are sent to the server through a browser, these parameters cannot have a wide range of data types, so data type conversion must be completed on the server side.

The MVC Framework is a presentation layer solution that should provide support for type conversion. Struts2 provides very powerful support for type conversion.

13. data processing at the presentation layer

For web applications, the presentation layer is mainly used to interact with users, including collecting user input data and presenting the server status to users. Therefore, the data flow at the presentation layer has two main directions: input data and output data.

For input data: the conversion from string data to multiple types of data is required. The program cannot be completed automatically. You need to manually convert it in the code.

For output data: both java and jsp support direct output of multiple data types.

Another data processing in the presentation layer is data validation, which is divided into customer verification and server-side verification.

Iv. type conversion

All HTTP parameters are strings. The stored data may be string, number, Boolean, date and time, or JavaBean type. Manual type conversion. For example, to convert a string to a Date, use the request. getParameter method to obtain the string; check whether the string is empty; and use the DateFormat. parse method to convert the string to a Date object.

15th, Struts2 type conversion

Struts2 built-in type conversion
String and boolean are used to convert the String and boolean values.
Conversion between String and char String and character
String, int, and Integer are converted between strings and integers.
String and Long are used to convert String and Long integer values.
String, double, and Double are used to convert the String and double-precision floating point values.
String and Float are used to convert a String to a single-precision floating point.
String and Date convert the String and Date types. The Date format uses the SHORT format of the Locale where the user request is located.
String and array by default. The array element is a String. If you define a type converter, it can also be another composite data type.
String, Map, List

16. Struts type conversion API

The Struts2 type converter is actually implemented based on OGNL. There is an OGNL. TypeConverter interface in the ognl project, which is the interface required to implement the type converter. This interface is defined as follows:

Public interface TypeConverter {
Public Object convertValue (Map arg0, Object arg1, Member arg2, String arg3,
Object arg4, Class arg5 ){
Return null;
}

The preceding TypeConverter must be implemented to implement the type converter, but the methods in the preceding interface are too complex. Therefore, the OGNL project also provides an implementation class for this interface: ognl. defatypetypeconverter, which inherits the class to implement its own type converter. this class is defined as follows:

Public class DefaultTypeConverter extends Object implements TypeConverter {
Public Object convertValue (Map <String, Object> context, Object value, Class toType ){
}
...... // Other methods
}

Functions of the ConvertValue Method
This method completes type conversion, but this type conversion is bidirectional. This method is used to convert strings to object instances, this method is also used to convert an object instance to a string. The type of the toType parameter is the target type to be converted. Therefore, you can determine the conversion direction based on the toType parameter.
ConvertValue method parameters and returned meaning
The first parameter: context is the context of the type conversion environment.
The second parameter: value is the parameter to be converted, and the value varies according to the conversion direction.
The third parameter: toType is the converted target type.
The return value of this method is the value after type conversion. The type of the value also changes with the change of the conversion direction. It can be seen that the convertValue method for conversion accepts the value to be converted. The target type to be converted is a parameter, and then the converted target value is returned.
Why is Value a string array?
For defatypetypeconverter converter, it must take into account the most common situation, so it treats all request parameters as a string array rather than a string. It is equivalent to the parameter value obtained by getParameterValues ().

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.