【问题标题】:Map with custom formatter in thymeleaf view在 thymeleaf 视图中使用自定义格式化程序映射
【发布时间】:2014-09-02 09:30:50
【问题描述】:

我正在尝试使用自定义格式化程序转换地图。

我创建了一个@LongCurrency Annotation,它可以像这样转换长值:

长 -> 字符串

22 -> 00,22

3310 -> 33,10

字符串 -> 长

3 -> 3

22,11 -> 2211

(Custom Annotation-driven Formatting Spring MVC)

到目前为止一切正常。现在我想用该格式化程序转换地图。下面是一些伪代码,它应该显示我要完成的工作。

@LongCurrency
private Map<Integer, Long> test;

//only to make clear what I am trying to do.
private Map<Integer, @LongCurrency Long> test; 

第二种方法可能是使用来自 Thymeleaf 的转换实用程序对象。 http://www.thymeleaf.org/doc/thymeleafspring.html#the-conversion-service

我尝试过这样的事情:

控制器:

 model.addAttribute("test", 3333L);

百里香:

<td th:text="${#conversions.convert(${test},LongCurrency)}}"></td>

但它不起作用。 错误消息:org.thymeleaf.exceptions.TemplateProcessingException:无法解析为表达式:“${#conversions.convert(${test},LongCurrency)}}”

我会感谢您提供一种或两种方式的帮助或想法。

EDIT1:“正常”带注释的长值有效

豆子:

@LongCurrency
private long test2;

百里香

<div th:text="${{test2}}" >

【问题讨论】:

  • 试试这个转换服务方法:${#conversions.convert(test,T(full.class.name.LongCurrency))}
  • 出现错误:对于注解和 LongCurrencyFormatter 都实现了 Formatter,目标类没有可用的转换。 (全类名)
  • 看来conversionService 没有找到对应的转换器。您可能需要在转换服务内部进行调试,以了解他为什么找不到格式化程序。例如,我不知道“long”和“Long”是否会影响这一点。
  • 谢谢,我会这样做的。顺便说一句,我有第三种方式(见我的回答)

标签: spring thymeleaf


【解决方案1】:

我有第三种方式为我工作。我创建了一个 LongCurrencyService,它调用了我的 Formatter 类的解析和打印方法。

@Named
@Singleton
public class LongCurrencyService {

    public static String LongToStringCurrency(Long value) {
        LongCurrencyFormatter longCurrencyFormatter = new LongCurrencyFormatter();
        return longCurrencyFormatter.print(value, Locale.GERMAN);
    }

    public static Long StringToLongCurrency(String value) throws ParseException {
        LongCurrencyFormatter longCurrencyFormatter = new LongCurrencyFormatter();
        return longCurrencyFormatter.parse(value, Locale.GERMAN);
    } 
}

在我的 Thymeleaf 中,我使用了那个 EL:

 <h1 th:text="${@longCurrencyService.LongToStringCurrency(test)}"></h1>

根据需要打印 33,33。

我的方式对我有用,但如果我应该接受自己的答案,我不会。 这不是我的问题的答案,如何使用格式化程序注释地图。

【讨论】:

    【解决方案2】:

    在一个spring boot项目中,我创建了一个标准的Spring Service

    @Service
    public class ThemeLeafService {
        public String formatTime(Integer time){
            var min= Optional.of(time).orElse(0);
            return String.format("%02d:%02d", min/60, min%60);
        }
    }
    

    我在我的模板中引用了

    <span th:text="${@themeLeafService.formatTime(spettacolo.ora)}"></span>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多