Struts2 Converter

converter

  • From an HTML form to an Action object, type conversion is from string to non-string
  • Http has no concept of "type". The input of each form can only be a string or an array of strings. On the server side, String must be converted to a specific data type
  • The job of mapping request parameters to action attributes in struts2 is handled by the Parameters interceptor , which is a member of the default interceptor and can automatically complete the conversion between strings and basic data types
  • From this, it can be known that in the previous case, no exception will occur without any processing, because the types we want on the server side are all basic types , and the parameters interceptor has done our job for us.

How will Struts2 handle when what the server needs is not a primitive type?

  • If the Action does not implement the ValidationAware interface : Struts2 will still call its Action method when it encounters a type conversion error, as if nothing happened
  • If the Action implements the ValidationAware interface : Struts2 will not continue to call the Action method when encountering a type conversion error, Struts2 will check whether the declaration of the relevant action element contains a result with name=input, if there is a Struts2 will control the The right is transferred to the result element . If there is no result element struts2, a 404 exception will be thrown, indicating that the result with name = input cannot be found.

example

  • If the Action class implements the ValidationAware interface and contains the result element, then when we enter a string (such as a letter) in a field of type Integer, Struts2 will report an error, as follows
  • Code display
    • As shown above, where Action class - Conversion implements ActionSupport can also achieve the same effect as the ValidationAware interface because ActionSupport implements the ValidationAware interface

think

  • How to customize error messages?
    • Create a new ActionClassName.properties file in the package where the corresponding Action class is located, where ClassName is the class name of the Action class that contains the input field
    • Add key-value pair in properties file to configure error message (invalid.fieldvalue.fieldName=message)
  • Example
    • Create a new configuration file under the Action package, and enter the error message to be displayed in the corresponding field. The input error message cannot directly enter Chinese characters. You can enter the corresponding Chinese characters in the properties file of eclipse and it will be automatically converted to the code shown in the figure (not If you know of any other methods, please let me know)

custom type converter

  • The above is what to do when we enter the wrong basic type of data, so when we need to use non-basic type data, Parameters will not help us automatically convert what should we do?
  • At this point, we need to define the converter ourselves to convert the corresponding fields
  • Custom converter implementation steps
    • Implement the StrutsTypeConverter class
    • Configure type converters
      • Field based configuration:

        • Create a new ModelClassName-c onverter.properties under the package of the Model (maybe Action, maybe a JavaBean) where the field is located
      • Enter key-value pairs in this file: fieldName = full class name of the type converter
      • Type-Based Configuration
        • Create xwork-conversion.properties under src
        • Type: type to be converted = full class name of type converter
      • As above, when the field is written in the Action, the configuration file at this time should be SelfConversion-converter.properties . When the field in the Action is packaged as a Customer class, the configuration file is in the same package as the Customer, and is named Customer-converter.properties
      • The content of the configuration file is the same (in this example, the custom converter converts the date type, that is, the conversion of the field birthday)

        birth=com.self.conversion.SelfTypeConverter
    • Implementing the StrutsTypeConverter class needs to implement two methods, as follows
    • Code example (convert the acquired field to Date type, and convert back)

      public class SelfTypeConverter extends StrutsTypeConverter {
          private DateFormat dateFormat;
      
          public SelfTypeConverter() {
              System.out.println("Constructs...");
          }
      
          public DateFormat getDateFormat() {
              if (dateFormat == null) {
                  ServletContext servletContext = ServletActionContext.getServletContext();
                  String pattern = servletContext.getInitParameter("pattern");
                  return new SimpleDateFormat(pattern);
              }
              return dateFormat;
          }
      
          @Override
          public Object convertFromString(Map map, String[] strings, Class aClass) {
              System.out.println("Succ");
              if (aClass == Date.class) {
                  if (strings != null && strings.length > 0) {
                      String value = strings[0];
                      try {
                          return getDateFormat().parseObject(value);
                      } catch (ParseException e) {
                          e.printStackTrace();
                      }
                  }
              }
              return null;
          }
      
          @Override
          public String convertToString(Map map, Object o) {
              if (o instanceof Date) {
                  Date date = (Date) o;
                  return getDateFormat().format(date);
              }
              return null;
          }
      }
      
      web.xml 文件
      <context-param>
          <param-name>pattern</param-name>
          <param-value>yyyy-mm-dd hh:mm:ss</param-value>
      </context-param>
  • The error handling of custom converters and default converters is the same, and will not be described here. This is the content of the converter, and I hope to point out the problem, thank you!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325025618&siteId=291194637