Request Parameters are converted to the data type at the presentation layer to express the Data Type

Source: Internet
Author: User

Request Parameters are converted to the data type at the presentation layer to express the Data Type

I. Introduction

Note:There is no type concept for data transmission over HTTP. on the server side, the request parameter is String or String [] type through the request. getParameter () and request. getParameterValue () methods.

However, this is inconvenient to use. We hope that the open-source framework can automatically complete type conversion and can directly obtain the target type when using it.

Ii. Struts2 type conversion

1. Struts2 automatically converts the string type to the basic data type. In other cases, we need to define our own type converter. =

2. Processing Method When type conversion fails

(1) by default, Struts2 does not process any type conversion failures.

(2) If an error occurs while converting the request parameter to the target basic type, the default value is assigned to the target basic type.

(3) If an error occurs in converting the request parameter to the target basic type packaging class, the target field is assigned null.

(4) If you want to give a prompt when an error occurs, you need to implement the com. opensymphony. xwork2.ValidationAware interface for the target Action class. The ActionSupport interface has been implemented for us.

Com: com. opensymphony. xwork2.ValidationAware

Contains two levels of error messages: ActionErrors and FieldErrors. The Action class of this interface is implemented. When an error occurs in type conversion, the result of name = input is returned. If no error is configured, returns 404.

If an error occurs in type conversion, the method is returned instead of the target method. It corresponds to an interceptor.

(5) On the error display page, you can get the error message from the Action class of the value stack, and the error message can be customized.

Custom error message: add the ActionName. properties attribute file under the package where the current Action class is located, and then add the following key-value pairs to the property file:

Invalid. fieldvalue. Target field name = custom error message

(6) In the value stack, the data structure of the error message is Map <String, List <String>, which can be obtained through the OGNL expression, you can also obtain the Struts2 tag as follows:

<s:fielderror fieldName="errorFiledName"></s:fielderror>

3. Custom type converter

Inherits the StrutsTypeConverter class and has two abstract methods.

Public Object convertFromString (Map context, String [] values, Class toClass): context can be seen as a Map stack. values represents the input request parameters, and toClass represents the target Class to be converted.

Public String convertToString (Map context, Object o): converts input o to a String.

(1) category level

InCreate a class containing the property to be converted under the same packageSimple class name + "-conversion. properties", such as: TypeConverterTestAction-conversion.properties, TypeConverterTestAction class contains a person attribute.

Add the property = full Class Name of the type converter to be converted to the created type conversion resource file, such as: person = com. nucsoft. struts2.convert. MyTypeConverter

(2) Global

Create the: xwork-conversion.properties property file under the root directory of the class path

Content: full Class Name of the class to be converted = full Class Name of the type converter, for example, com. nucsoft. struts2.helloworld. Person = com. nucsoft. struts2.convert. MyTypeConverter

The error handling method for custom type conversion is the same as before.

4. type conversion of complex types of data

(1) The target Action does not implement the ModelDriven interface, that is, the top object of the stack is the current Action class.

[1] A separate complex object. The form tag corresponds to the object property: person

<s:form action="converter/typeConverter" method="post">        <s:textfield name="person.userName" label="userName"/>        <s:textfield name="person.age" label="age"/>        <s:submit value="submit"/></s:form>

(2) The target Action implements the ModelDriven interface. The top object of the stack is of the getModel return value type.

[1] A single complex type corresponds to multiple tags

<s:form action="converter/typeConverter" method="post">        <s:textfield name="userName" label="person"/>        <s:textfield name="age" label="age"/>        <s:submit value="submit"/></s:form>

[2] A single complex object with only one form tag is converted to a corresponding complex object according to the specified format:

<s:form action="converter/typeConverter" method="post">        <s:textfield name="person" label="person"/>        <s:submit value="submit"/></s:form>

Input Format:

AA, 12

You need to customize the person type converter or global type converter for the target Action, such:

/*** @ Author solverpeng * @ create 2016-07-09-*/public class MyTypeConverter extends StrutsTypeConverter {@ Override public Object convertFromString (Map context, String [] values, class toClass) {Person person = null; if (Person. class = toClass) try {person = (Person) toClass. newInstance (); String strs = values [0]; person. setUserName (strs. split (",") [0]); person. setAge (Integer. parseInt (strs. split (",") [1]);} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace () ;}return person ;}@ Override public String convertToString (Map context, Object o) {return null ;}}MyTypeConverter

[3] a complex object contains another complex object. For example, a Person contains an Address.

Multiple tags:

<s:form action="converter/typeConverter" method="post">        <s:textfield name="userName" label="person"/>        <s:textfield name="age" label="age"/>        <s:textfield name="address.addressName" label="addressName"/>        <s:textfield name="address.location" label="location"/>        <s:submit value="submit"/></s:form>

Three tags, fixed format: address uses one tag, fixed format: addressName, location

<s:form action="converter/typeConverter" method="post">        <s:textfield name="userName" label="userName"/>        <s:textfield name="age" label="age"/>        <s:textfield name="address" label="address"/>        <s:submit value="submit"/></s:form>

Because the Person class contains the Address property, a new Person-conversion.properties file is created under the Person package

Content: address = com. nucsoft. struts2.convert. MyTypeConverter

Type converter:

/*** @ Author solverpeng * @ create 2016-07-09-*/public class MyTypeConverter extends StrutsTypeConverter {@ Override public Object convertFromString (Map context, String [] values, class toClass) {if (Person. class = toClass) {Person person = null; try {Person = (Person) toClass. newInstance (); String strs = values [0]; person. setUserName (strs. split (",") [0]); person. setAge (Integer. parseInt (strs. split (",") [1]);} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} return person;} if (Address. class = toClass) {Address address = null; try {address = (Address) toClass. newInstance (); String strs = values [0]; address. setAddressName (strs. split (",") [0]); address. setLocation (strs. split (",") [1]);} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace () ;}return address;} return null ;}@ Override public String convertToString (Map context, Object o) {return null ;}}MyTypeConverter

5. type conversion in the Set Element Object

[1] The target Action class contains complex objects of the List, such as List <Person>. When the Address type is converted,Or use the Person ConverterBecause it is List <Person>, you do not need to implement the ModelDriven interface, so the top object of the stack is the current Action class object.

<s:form action="converter/typeConverter" method="post">        <s:textfield name="persons[0].userName" label="userName[0]"/>        <s:textfield name="persons[0].age" label="age[0]"/>        <s:textfield name="persons[0].address" label="address[0]"/>        <s:textfield name="persons[1].userName" label="userName[1]"/>        <s:textfield name="persons[1].age" label="age[1]"/>        <s:textfield name="persons[1].address" label="address[1]"/>        <s:submit value="submit"/> </s:form>

[2] There is only one complex object, but this complex object contains the List attribute. For example, the Person class has the List <Address> attribute. Because there is only one complex object, the ModelDriven interface is implemented.

<s:form action="converter/typeConverter" method="post">        <s:textfield name="userName" label="userName"/>        <s:textfield name="age" label="age"/>        <s:textfield name="addresses[0].addressName" label="address[0].addressName" />        <s:textfield name="addresses[0].location" label="address[0].location" />        <s:textfield name="addresses[1].addressName" label="address[1].addressName" />        <s:textfield name="addresses[1].location" label="address[1].location" />        <s:submit value="submit"/></s:form>

6. type conversion of json data

 

 

Not complete, to be continued.

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.