STRUTS2 Development Basic configuration and type conversion _java

Source: Internet
Author: User
Tags constant reflection

The default values in the 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 you do not specify a class for the action, the default is Actionsupport.
2> If no method is specified for the action, the Execute () methods in the action are executed by default.
3> If you do not specify the Name property of result, the default value is success.


The 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>
The result configuration is similar to the forward in struts1, but there are several types of results available in struts2, commonly used types: Dispatcher (default), redirect, Redirectaction, plaintext.

The following is an example of a redirectaction result type, if the redirected action is under the same package:
<result type= "Redirectaction" >helloworld</result>
If the redirected action is under another namespace:
<result type= "Redirectaction" >
<param name= "ActionName" >helloworld</param>
<param name= "namespace" >/test</param>
</result>
PlainText: Display the original file content, for example: when we need to display the JSP file source code, we can use this type.
<result name= "source" type= "plaintext" >
<param name= "Location" >/xxx.jsp</param>
<param name= "CharSet" >UTF-8</param><!--Specifies the encoding to read the file-->
</result>
In result, you can also use the ${property name} expression to access the properties in the action, and the property names in the expression correspond to the properties in the action. As follows:
<result type= "redirect" >view.jsp?id=${id}</result>

Three, multiple action share a view--global result configuration

When the same view is used in multiple action, we should define result as a global view. Similar features are provided in the global forward,struts2 in Struts1:
<package ....>
<global-results>
<result name= "Message" >/message.jsp</result>
</global-results>
</package>

Iv. injecting values for the property of the action

STRUTS2 provides dependency injection for attributes in the action, and in the Struts2 configuration file, we can easily inject values into the properties of the action. Note: The property must provide a 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>
"/images" is injected above through the Savepath property of the <param> node action.


V. Specify a request suffix that requires Struts 2 processing

We all use the. Action suffix to access the action by default. In fact, the default suffix can be modified by the constant "struts.action.extension", for example: we can configure struts 2 to handle only the request path with the. do suffix:

<?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 a user needs to specify more than one request suffix, multiple suffixes are separated by commas (,). Such as:
<constant name= "struts.action.extension" value= "Do,go"/>


Vi. to elaborate on the definition of constants

Constants can be configured in Struts.xml or struts.properties, and it is recommended that you configure them in Struts.xml, both of which are configured in the following ways:
To configure constants in the Struts.xml file
<struts>
<constant name= "struts.action.extension" value= "Do"/>
</struts>

To configure constants in Struts.properties
Struts.action.extension=do

Because constants can be defined in the following multiple configuration files, we need to understand the search order for STRUTS2 Load constants:
Struts-default.xml
Struts-plugin.xml
Struts.xml
Struts.properties
Xml
If the same constant is configured in more than one file, the constant value that is configured in the latter file overrides the constant value that was configured in the previous file.


Introduction to Common constants

<!--Specifies the default encoding set for HttpServletRequest setcharacterencoding method and Freemarker, velocity output-->
<constant name= "struts.i18n.encoding" value= "UTF-8"/>
<!--This property specifies the request suffix required for Struts 2 processing, and the default value of the property is action, where all matching *.action requests are handled by STRUTS2.
If a user needs to specify more than one request suffix, 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 production environment), the development phase is best to close-->
<constant name= "Struts.serve.static.browserCache" value= "false"/>
<!--If the configuration file for struts is modified, the system automatically reloads the file, the default value is False (used in production), and the development phase is best to open-->
<constant name= "Struts.configuration.xml.reload" value= "true"/>
<!--development mode so that you can print more detailed error messages-->
<constant name= "Struts.devmode" value= "true"/>
<!--The default view theme-->
<constant name= "Struts.ui.theme" value= "simple"/>
When <!– is integrated with spring, specifies that spring is responsible for the creation of the Action object-->
<constant name= "struts.objectfactory" value= "Spring"/>
<!– This property to set whether Struts 2 supports dynamic method calls, and the default value of this property is true. If you need to turn off dynamic method calls, you can set this property to False. -->
<constant name= "Struts.enable.DynamicMethodInvocation" value= "false"/>
<!--size limits for uploaded files-->
<constant name= "struts.multipart.maxSize" value= "10701096"/>

Viii. specify multiple struts profiles for the application

In most applications, as the size of the application increases, the number of action in the system increases substantially, causing the Struts.xml configuration file to become bloated. To avoid struts.xml files that are too large and bloated to improve the readability of struts.xml files, we can decompose a struts.xml configuration file into multiple profiles and then include other profiles in Struts.xml files. The following struts.xml specifies multiple profiles through the <include> element:

<?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 Struts 2 action as a module in multiple configuration files.


Nine, dynamic method call

If there are multiple methods in the action, we can use the!+ method name to invoke the specified method. As follows:
public class helloworldaction{
Private String message;
....
Public String Execute () throws exception{
This.message = "My first Struts2 application";
Return "Success";
}

Public String Other () throws exception{
This.message = "Second method";
Return "Success";
}
}
Suppose the URL path to access the action above is:/struts/test/helloworld.action
To access the other () method of the action, we can call this:
/struts/test/helloworld!other.action
If you do not want to use dynamic method calls, we can turn off dynamic method calls through constant struts.enable.DynamicMethodInvocation.
<constant name= "Struts.enable.DynamicMethodInvocation" value= "false"/>


Use wildcard characters to define action

<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 Struts2 application";
Return "Success";
}

Public String Other () throws exception{
This.message = "Second method";
Return "Success";
}
}

To access the other () method, you can access it by using a URL such as:/test/helloworld_other.action

Xi. Receive request parameters

Use the base type receive request parameter (Get/post)
to define an attribute with the same name as the request parameter in the action class, STRUTS2 can automatically receive the request parameter and give it a property of the same name.
Request Path: http://localhost:8080/test/view.action?id=78
public class Productaction {
       Private Integer ID;
      public void setId (Integer id) {//STRUTS2 Gets the request parameter value by using reflection technology to invoke the setter method of the property with the same name as the request parameter
             this.id = ID;
     }
      public Integer getId () {return ID;}
 }
Receive request parameters with composite type
Request path: http://localhost:8080/test/view.action?product.id=78
 public class productaction {
   private product product;
   public void Setproduct (product product) {  this.product = product; }
   public produ CT GetProduct () {return product}
}
Struts2 first creates the product object by invoking the default constructor of the product through reflection technology, and then calls the setter method for the attribute with the same name as the request parameter by reflection technology to get the request parameter value.


12, the meaning of type conversion

For an intelligent MVC framework, type conversions are unavoidable. Because the request parameters of the B/s (browser/server) structure are sent through the browser to the server, these parameters cannot have a rich data type, so the conversion of the data type must be done on the server side.

The MVC framework is a presentation layer solution that is supposed to provide support for type conversions, and STRUTS2 provides very powerful type conversion support.


13, the performance Layer data processing

For Web applications, the presentation layer is primarily used to interact with the user, including collecting user input data and rendering the server state to the user. Therefore, the data flow of the presentation layer has two main directions: input data and output data.


For input data: You need to complete the conversion from string data to multiple types of data. Programs are usually not automatically completed and need to be manually converted in code


For output data: either Java or JSP supports direct output of multiple data types.


Performance layer Another data processing is: Data checksum, divided into customer checksum and server-side checksum.


14. Type Conversion

HTTP parameters are string types. The saved data may be a string, number, Boolean, datetime, or JavaBean type. Manual type conversions, such as converting a string to a date by: getting a string by using the Request.getparameter method, checking for null, and converting a string to a Date object by the Dateformat.parse method


XV, STRUTS2 type conversion

STRUTS2 Built-in type conversions
The conversion between string and Boolean completion strings and Booleans
String and char the usual conversion between strings and characters
Conversion between string and int, integer completion strings and integral types
Conversion between string and long complete string
String and double, double to complete the conversion of strings and double-precision floating-point values
The conversion between string and float complete strings and single-precision floating-point
The conversion between string and date completion strings and dates, date format using the short format of the locale where the user request is in the format
string and arrays in the default case, the array element is a string, and if the user defines a type converter, it can be another composite data type
string and map, List

16. Struts Type Conversion API

The Struts2 type converter is actually implemented based on OGNL, and there is a Ognl.typeconverter interface in the OGNL project that implements the interface that the type converter must implement. The 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 implementation type converter must implement the above TypeConverter, but the method in the above interface is too complex, so the OGNL project also provides an interface implementation class: Ognl.defaulttypeconverter, Implement your own type converter by inheriting the class. The 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
}


The effect of the Convertvalue method
This method completes type conversions, although this type conversion is bidirectional and is implemented through this method when a string is required to be transformed into an object instance, which is also implemented by this method when converting an object instance to a string. This conversion is done through the ToType parameter type, which is the target type that needs to be converted. Therefore, the conversion direction can be judged according to the ToType parameters.
Convertvalue method parameters and return meaning
The first argument: context is the contexts of the type conversion environment
The second parameter: value is the parameter that needs to be converted, depending on the value of the different value parameters of the conversion direction.
Third parameter: ToType is the converted target type
The return value of the method is a type-converted value. The type of the value will also change as the direction of the transformation changes. This shows that the Convertvalue method of conversion accepts the value that needs to be converted, the target type that needs to be converted is a parameter, and then returns the converted target value
Value Why is it an array of strings?
For the Defaulttypeconverter converter, it must take into account the most common scenarios, so he treats all request parameters as string arrays rather than strings. Equivalent to the parameter value of 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.