2017-08-16 415 views
3

我寫這樣的功能:如何在Thymeleaf中使用自定義Spring EL函數?

public interface SUtils { 

    static String reverseString(String input) { 
    StringBuilder backwards = new StringBuilder(); 
    for (int i = 0; i < input.length(); i++) { 
     backwards.append(input.charAt(input.length() - 1 - i)); 
    } 
    return backwards.toString(); 
    } 
} 

而且隨着StandardEvaluationContext.registerFunction註冊此功能。 而在控制器中我使用@Value("#{#reverseString('hello')}")就可以得到這個值。 但在thymeleaf當我使用${reverseString('hello')}得到了一個錯誤 Exception evaluating SpringEL expression: "reverseString('hello')"

如何在百里香中使用自定義拼寫?

回答

2

我最常做的,是作爲一個Bean使用@Component這樣定義Thymeleaf實用程序類。在春季EL中,您可以使用自動檢測功能@來簡單地引用它們。所以沒有必要註冊它們。

@Component 
public interface SUtils { 

    static String reverseString(String input) { 
    // ... 
    } 
} 

<span th:text="${@sUtils.reverseString('hello')}"></span> 
+0

吧!現在是工作!謝謝! –

0

不在的方式來測試前,但副手嘗試使用靜態調用:

th:text="${T(com.package.SUtils).reverseString('hello')}"

相關問題