我有以下枚举类型:
public enum SearchLocationTypes {REGISTRATION, WORKPLACE}
我已经为这个枚举 + 格式化程序注释工厂创建了转换器和格式化程序(以防万一)。
格式化程序:
public class SearchLocationTypesFormatter implements Formatter<SearchLocationTypes> {
@Override
public String print(SearchLocationTypes type, Locale locale) {
String strType = "";
switch(type) {
case REGISTRATION:
strType = "rg";
break;
case WORKPLACE:
strType = "wp";
break;
}
return strType;
}
@Override
public SearchLocationTypes parse(String strType, Locale locale) throws ParseException {
if(strType.equals("rg")) return SearchLocationTypes.REGISTRATION;
if(strType.equals("wp")) return SearchLocationTypes.WORKPLACE;
else throw new IllegalArgumentException();
}
}
工厂:
public class SearchLocationTypesAnnotationFormatterFactory
implements AnnotationFormatterFactory<SearchLocationTypesFormat> {
@Override
public Set<Class<?>> getFieldTypes() {
return new HashSet<Class<?>>(Arrays.asList(new Class<?>[] {SearchLocationTypes.class}));
}
@Override
public Printer<?> getPrinter(SearchLocationTypesFormat a, Class<?> type) {
return new SearchLocationTypesFormatter();
}
@Override
public Parser<?> getParser(SearchLocationTypesFormat a, Class<?> type) {
return new SearchLocationTypesFormatter();
}
}
注解:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface SearchLocationTypesFormat {}
转换器:
public class SearchLocationTypesConverter implements Converter<SearchLocationTypes, String> {
@Override
public String convert(SearchLocationTypes type) {
String strType = "";
switch(type) {
case REGISTRATION:
strType = "rg";
break;
case WORKPLACE:
strType = "wp";
break;
}
return strType;
}
}
servlet.xml 的一部分:
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="ru.riado.web.format.SearchLocationTypesConverter" />
</set>
</property>
<property name="formatters">
<set>
<bean class="ru.riado.web.format.SearchLocationTypesAnnotationFormatterFactory" />
<bean class="ru.riado.web.format.SearchSortTypesFormatter" />
</set>
</property>
</bean>
当我从 JSP 调用以下代码时,一切都按预期工作。
示例:假设我有一个属性为“locType”的bean“form”设置为“REGISTRATION”。
public class Form {
@SearchLocationTypesFormat
private SearchLocationTypes locType;
// setters and getters
}
现在,我正在使用以下代码,它的输出是“rg”:
<s:eval expression="form.locType">
但是弹簧形式不会将其值转换为“rg”。而不是这个,它将值设置为“注册”,就像它使用默认转换器一样。我试图关闭默认转换,但这没有帮助。
谁能告诉我我在这里缺少什么?