1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.util;
19
20 import java.util.Map;
21
22 import ognl.DefaultTypeConverter;
23
24 /***
25 * <!-- START SNIPPET: javadoc -->
26 *
27 * Base class for type converters used in Struts. This class provides two abstract methods that are used to convert
28 * both to and from strings -- the critical functionality that is core to Struts's type coversion system.
29 *
30 * <p/> Type converters do not have to use this class. It is merely a helper base class, although it is recommended that
31 * you use this class as it provides the common type conversion contract required for all web-based type conversion.
32 *
33 * <p/> There's a hook (fall back method) called <code>performFallbackConversion</code> of which
34 * could be used to perform some fallback conversion if <code>convertValue</code> method of this
35 * failed. By default it just ask its super class (Ognl's DefaultTypeConverter) to do the conversion.
36 *
37 * <p/> To allow the framework to recognize that a conversion error has occurred, throw an XWorkException or
38 * preferable a TypeConversionException.
39 *
40 * <!-- END SNIPPET: javadoc -->
41 *
42 */
43 public abstract class StrutsTypeConverter extends DefaultTypeConverter {
44 public Object convertValue(Map context, Object o, Class toClass) {
45 if (toClass.equals(String.class)) {
46 return convertToString(context, o);
47 } else if (o instanceof String[]) {
48 return convertFromString(context, (String[]) o, toClass);
49 } else if (o instanceof String) {
50 return convertFromString(context, new String[]{(String) o}, toClass);
51 } else {
52 return performFallbackConversion(context, o, toClass);
53 }
54 }
55
56 /***
57 * Hook to perform a fallback conversion if every default options failed. By default
58 * this will ask Ognl's DefaultTypeConverter (of which this class extends) to
59 * perform the conversion.
60 *
61 * @param context
62 * @param o
63 * @param toClass
64 * @return The fallback conversion
65 */
66 protected Object performFallbackConversion(Map context, Object o, Class toClass) {
67 return super.convertValue(context, o, toClass);
68 }
69
70
71 /***
72 * Converts one or more String values to the specified class.
73 *
74 * @param context the action context
75 * @param values the String values to be converted, such as those submitted from an HTML form
76 * @param toClass the class to convert to
77 * @return the converted object
78 */
79 public abstract Object convertFromString(Map context, String[] values, Class toClass);
80
81 /***
82 * Converts the specified object to a String.
83 *
84 * @param context the action context
85 * @param o the object to be converted
86 * @return the converted String
87 */
88 public abstract String convertToString(Map context, Object o);
89 }