Struts2 type conversion (1), struts2 type conversion

Source: Internet
Author: User

Struts2 type conversion (1), struts2 type conversion
1. type conversion Overview 1. From an HTML form to an Action object, type conversion is from string to non-string. Because HTTP does not have the concept of "type", each form input can only be a string or a string array. Therefore, on the server side, you must convert String to a specific data type. (For details, refer to section 6.1.1 in "OGNL, Data Transfer Catalyst" in "Struts2 technical insider-in-depth analysis of Struts2 Architecture Design and Implementation Principles"-difficulties in data transfer) 2. In struts2, the job of ing request parameters to action attributesParameters interceptorResponsible. It is a member of the default interceptor stack defaultStack. The Parameters interceptor can automatically convert string and basic data types. Ii. How to Handle type conversion errors if type conversion fails:-if the Action class does not implement the ValidationAware interface: Struts will continue to call its Action Method in case of a type conversion error, it's like nothing happened. -If the Action class implements the ValidationAware interface: When Struts encounters a type conversion error, it will not continue to call its Action method, struts checks whether the declaration of related action elements contains a result with name = input. If yes, Struts transfers the control to the result element. If no input result exists, Struts throws an exception. (Note: Generally, actions indirectly implement the ValidationAware interface by inheriting the ActionSupport class .) Iii. Display and customization of type conversion error messages when Action implements the ValidationAware interface, if the type conversion fails, Struts will find the result of "name = input" defined in the configuration file, as a member of the default defastack stack interceptor stack, the ConversionError interceptor is responsible for adding error messages related to type conversion (prerequisite: The Action class must implement the ValidationAware interface) and save the original values of each request parameter to display the error message and echo form on the page (the error message is automatically displayed only under the non-simple topic of Struts2 ). Example 1: 1) The main code of the JSP page is as follows:

1 <s:debug></s:debug>2 3 <s:form action="testConversion">4     <s:textfield name="age" label="Age"></s:textfield>5     <br><br>6 <s:submit></s:submit>7 </s:form>

2) The main Java code is as follows:

 1 package com.atguigu.struts2.app; 2  3 import com.opensymphony.xwork2.ActionSupport; 4  5 public class ConversionAction extends ActionSupport{ 6  7     private int age; 8      9     public int getAge() {10         return age;11     }12 13     public void setAge(int age) {14         this.age = age;15     }16 17     public String execute(){18         System.out.println("age: " + age);19         return "success";20     }21     22 }

3) The basic configuration of struts. xml is as follows:

<package name="default" namespace="/" extends="struts-default">    <action name="testConversion" class="com.atguigu.struts2.app.ConversionAction">        <result>/success.jsp</result>        <result name="input">/index.jsp</result>    </action>         </package>

Run the project after release. The running result after the project is submitted with a non-integer character is as follows:

As you can see, in a non-simple topic of Struts2, an error message in the following format is generated if an illegal field is entered: Invalid field value for field "fieldName". The following problems are raised for the above results: Question 1: How to overwrite the default error message?

1) Create the ActionClassName. properties attribute file in the package where the corresponding Action class is located. ActionClassName is the class name of the Action class containing the input field.
2) Add the following key-value pairs to the property file: invalid. fieldvalue. fieldName = custom error message

Example 2:

Add the attribute file ConversionAction for example 1. properties, and submit the key-Value Pair invalid in the file. fieldvalue. age = \ u9519 \ u8BEF \ u7684 \ u5E74 \ u9F84 \ u683C \ u5F0F. ("Incorrect age format. ")

The running result is as follows:


Question 2: If it is a simple topic, will the error message be automatically displayed? What if it is not displayed?

After the topic is changed to simple, the error message cannot be displayed automatically. Therefore, you can use the following methods to display the error message:

1) through the debug tag, we can see that if a conversion error occurs, there will be a fieldErrors attribute in the value stack Action (which implements the ValidationAware Interface) object,
The type of this attribute is Map <String, List <String>. The key column is the field (attribute name) and the value is the List composed of error messages. Therefore, you can use EL or OGNL to Display error messages: $ {fieldErrors. age [0]}

2). You can also use the s: fielderror label to display the error of the specified field. You can use the fieldName attribute to display the error of the specified field.

Example 3: Modify the JSP page code in Example 1 as follows:
1 <s:form action="testConversion" theme="simple">2     Age: <s:textfield name="age" label="Age"></s:textfield>3     ${fieldErrors.age[0]}4     <s:fielderror fieldName="age"></s:fielderror>5     <br><br>6     <s:submit></s:submit>7 </s:form>

The running result is as follows:

From the running results, we can see that the ul and li formats generated by the <s: fielderror> label are not what we want when an error message is displayed, so how can I modify the style of the error message to customize?

Question 3: If a simple topic is displayed with the <s: fielderror fieldName = "age"> </s: fielderror> label, the message is in the ul, li, span. How to remove ul, li, and span?

Idea 1: because each error message is packaged in an HTML span element, you can change the format of the error message by overwriting the css style marked as errorMessage. However, this method is not conducive to maintaining the overall style of our system.

★★★Idea 2: In the fielderror. ftl file under the template. simple package of Struts2, the s: fielderror label under the simple topic is defined to display the error message style, so modify the configuration file.
★★★Modify template: Create a template under src. simple package, create fielderror. ftl file, put the native fielderror. copy the content in ftl to the newly created fielderror. ftl, and remove ul, li, and span.


A simple struts2 type conversion problem

When exception capture is added to the method executed in the action, the method is certainly abnormal. If the exception of the action Method in struts2 is not captured, sometimes an INPUT string is returned, this error occurs if no corresponding configuration exists in your configuration file. (When will the input be automatically returned? I have not studied it carefully and have encountered it several times)

Use the Struts2 framework to complete a Web Project (struts2 type conversion exercise)

Public static void main (String [] args ){
// TODO Auto-generated method stub
SimpleDateFormat format = new SimpleDateFormat ("HH: mm: ss ");
String nowTime = format. format (new Date ());

System. out. println (nowTime );
}

This is implemented in a main method and two packages need to be imported:
Java. text. SimpleDateFormat;
Java. util. Date;

The current system time will be output on the console after running

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.