在freemarker使用java类方法

要想使用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)!} 



你可能感兴趣的:(freemarker)