如何在freemarker中调用java的方法
1个回答
2016-01-19 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
1 要想使用Freemarker支持的自定义方法,需要实现freemarker.template.TemplateMethodModel接口或 TemplateMethodModelEx接口
参考示例如下:
java 代码:
public class Object2HashMap implements TemplateMethodModelEx {
private static final Logger logger = LoggerFactory.getLogger(Object2HashMap.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object exec(List arguments) throws TemplateModelException {
Collection collection = (Collection) DeepUnwrap.unwrap((TemplateModel) arguments.get(0));
String keyProperty = arguments.get(1).toString();
String valueProperty = arguments.get(2).toString();
HashMap result = new HashMap();
if (collection == null) return result;
for (Object object: collection) {
try {
Object key = PropertyUtils.getProperty(object, keyProperty);
Object value = PropertyUtils.getProperty(object, valueProperty);
result.put(key, value);
} catch (Exception e) {
logger.error("处理异常", e);
}
}
return result;
}
}
freemarker使用示例,通过new()创建该对象。参考示例是 将wsdl的扩展字段 key,value值放到HashMap中。
<#assign
chineseAmount = "com.ccic.gateway.core.freemarker.encoder.ChineseAmountEncoder"?new()
object2hash = "com.ccic.gateway.core.freemarker.encoder.Object2HashMap"?new()
insuredExtendHash = object2hash(payload.responseBody.policy.extend, "key", "value")
>
取值:${(insuredExtendHash.ApproverCName)!}
参考示例如下:
java 代码:
public class Object2HashMap implements TemplateMethodModelEx {
private static final Logger logger = LoggerFactory.getLogger(Object2HashMap.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object exec(List arguments) throws TemplateModelException {
Collection collection = (Collection) DeepUnwrap.unwrap((TemplateModel) arguments.get(0));
String keyProperty = arguments.get(1).toString();
String valueProperty = arguments.get(2).toString();
HashMap result = new HashMap();
if (collection == null) return result;
for (Object object: collection) {
try {
Object key = PropertyUtils.getProperty(object, keyProperty);
Object value = PropertyUtils.getProperty(object, valueProperty);
result.put(key, value);
} catch (Exception e) {
logger.error("处理异常", e);
}
}
return result;
}
}
freemarker使用示例,通过new()创建该对象。参考示例是 将wsdl的扩展字段 key,value值放到HashMap中。
<#assign
chineseAmount = "com.ccic.gateway.core.freemarker.encoder.ChineseAmountEncoder"?new()
object2hash = "com.ccic.gateway.core.freemarker.encoder.Object2HashMap"?new()
insuredExtendHash = object2hash(payload.responseBody.policy.extend, "key", "value")
>
取值:${(insuredExtendHash.ApproverCName)!}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询