【问题标题】:Spring display format vs editing formatSpring 显示格式 vs 编辑格式
【发布时间】:2018-10-01 16:41:32
【问题描述】:

背景

我有一个小型 Spring MVC Web 项目(使用标准 JSP 作为视图引擎),我认为如果布尔值可以显示为“是”或“否”会很好 - 我认为这看起来更友好比“真”和“假”。所以我创建了一个自定义的BooleanFormatter 来为我做这件事。到目前为止,一切顺利。

但是,当布尔字段呈现为复选框时,Spring 会执行以下操作来确定是否应选中该复选框:

  1. 将布尔值转换为“是”或“否”。
  2. 检查应用Boolean.valueOf 的结果。

当然,Boolean.valueOf("yes")false,因此复选框永远不会被呈现为选中状态。

这是个问题。

我的问题

有没有办法告诉 Spring 格式化程序应该在显示值时使用,而不是在渲染(或解析)编辑器时使用?

(我正在寻找类似于 ASP.NET MVC 的 DisplayTemplate vs EditorTemplate 或 DisplayFormat.ApplyFormatInEditMode

或者,我是不是完全走错了路?

【问题讨论】:

标签: java spring-mvc jsp formatting


【解决方案1】:

我查看了AbstractPropertyBindingResult 的代码,以了解为什么Spring checkbox JSP Tag is broken when using Converter for type Boolean 的答案有效。这是渲染复选框/其他输入时使用的代码:

protected Object formatFieldValue(String field, @Nullable Object value) {
    String fixedField = fixedField(field);
    // Try custom editor...
    PropertyEditor customEditor = getCustomEditor(fixedField);
    if (customEditor != null) {
        customEditor.setValue(value);
        String textValue = customEditor.getAsText();
        // If the PropertyEditor returned null, there is no appropriate
        // text representation for this value: only use it if non-null.
        if (textValue != null) {
            return textValue;
        }
    }
    if (this.conversionService != null) {
        // Try custom converter...
        TypeDescriptor fieldDesc = getPropertyAccessor().getPropertyTypeDescriptor(fixedField);
        TypeDescriptor strDesc = TypeDescriptor.valueOf(String.class);
        if (fieldDesc != null && this.conversionService.canConvert(fieldDesc, strDesc)) {
            return this.conversionService.convert(value, fieldDesc, strDesc);
        }
    }
    return value;
}

在数据绑定期间,遵循类似的过程,

  1. 尝试查找PropertyEditor
  2. 尝试查找Converter/Formatter

因此:

  • 要仅为编辑器指定格式,请使用PropertyEditor
  • 要指定仅用于显示的格式,请使用FormatterConverter,但也可以使用PropertyEditor 来执行默认行为。

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 2019-09-10
    • 2021-05-08
    • 2012-04-05
    • 2019-02-27
    • 2016-05-04
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多