Reputation: 15836
I am trying to convert a Map with a custom Formatter.
I created an @LongCurrency Annotation, which converts long values like this:
Long -> String
22 -> 00,22
3310 -> 33,10
String -> Long
3 -> 3
22,11 -> 2211
(Custom Annotation-driven Formatting Spring MVC)
Everything is working so far. Now I would like to convert a Map with that formatter. Here is some pseudocode which should show what I am try to accomplish.
@LongCurrency
private Map<Integer, Long> test;
//only to make clear what I am trying to do.
private Map<Integer, @LongCurrency Long> test;
A second way may be to use the conversions utility object from Thymeleaf. http://www.thymeleaf.org/doc/thymeleafspring.html#the-conversion-service
I tryed something like this :
Controller:
model.addAttribute("test", 3333L);
Thymeleaf:
<td th:text="${#conversions.convert(${test},LongCurrency)}}"></td>
but it does not work. Errormessage: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "${#conversions.convert(${test},LongCurrency)}}"
I would be thankful for help or ideas for one or both ways.
EDIT1: a "normal" annotated long value works
Bean:
@LongCurrency
private long test2;
Thymeleaf
<div th:text="${{test2}}" >
Upvotes: 3
Views: 2805
Reputation: 865
In a spring boot project, I created a standard 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);
}
}
I referenced in my template
<span th:text="${@themeLeafService.formatTime(spettacolo.ora)}"></span>
Upvotes: 0
Reputation: 15836
I got third way working for me. I created a LongCurrencyService which calls the parse and print methods of my Formatter-class.
@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);
}
}
In my Thymeleaf I use that EL:
<h1 th:text="${@longCurrencyService.LongToStringCurrency(test)}"></h1>
which prints 33,33 as wanted.
My way is working for me, but I don't if I should accept my own answer. It is not the answer to my question, how to annotate a map with a formatter.
Upvotes: 3