任何人都知道如何扩展百里香的表达? (我需要百里香的“多样性”功能)
克隆“数字”表达式有效,但是......
当我自己表达时,我有错误:
SEVERE:带有路径[]的servlet [appServlet]的Servlet.service()抛出异常
[Request processing failed;
nested exception is org.thymeleaf.exceptions.TemplateProcessingException:
Exception evaluating SpringEL expression:
"Variety.Variety(review.usefulScore, 'osoba', 'osoby', 'osób')"
(static:/cms/fragments/reviews:49)] with root cause
org.springframework.expression.spel.SpelEvaluationException:
EL1011E:(pos 8): Method call:
Attempted to call method Variety(java.lang.Integer,java.lang.String,java.lang.String,java.lang.String) on null context object
有什么建议吗?
编辑(我的代码): 包org.springframework.expression;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public abstract class Variety extends StandardEvaluationContext {
private boolean in_array(int needle, int[] haystack) {
for(int i = 0; i < haystack.length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
public String Variety(int number, String varietyFor1, String varietyFor234, String varietyForOthers) {
if(number == 1)
return varietyFor1;
if(number % 100 >= 10 && number % 100 <= 20)
return varietyForOthers;
if(in_array(number%10, new int[] {2,3,4}))
return varietyFor234;
return varietyForOthers;
}
}
编辑(忘了,像所有人一样): 我想使用它:$ {utils.Variety(...)}
答案 0 :(得分:4)
以下异常表明上下文中没有Variety
个对象。
Attempted to call method Variety(java.lang.Integer,java.lang.String,java.lang.String,java.lang.String) on null context object
必须通过方言添加表达式对象。如果您已将方言添加到模板引擎,则可以使用#utils.variety(...)
。
public class UtilsDialect implements IExpressionEnhancingDialect {
public static final String UTILS_EXPRESSION_OBJECT_NAME = "utils";
private final Variety utils;
public UtilsDialect (final Variety utils){
this.utils = utils;
}
@Override
public Map<String, Object> getAdditionalExpressionObjects(final IProcessingContext processingContext) {
final Map<String, Object> objects = new HashMap<>();
objects.put(UTILS_EXPRESSION_OBJECT_NAME, variety);
return objects;
}
}
还要确保以大小写混合的方式编写方法:
public abstract class Variety extends StandardEvaluationContext {
private boolean inArray(...){
...
}
public String variety(...){
...
}
}