FreeMarker3.8中引入了一个非常实用的!功能,在FreeMarker3.8-中,如果要显示类似${user.phone.areacode}的值,需要层层判断是否为NULL,譬如如上的表达式一般在FTL中需要写成<#if user?exists><#if user.phone?exists><#if user.phone.areacode?exists>${user.phone.areacode}},不胜烦琐,而在FreeMarker3.8中可以使用${(user.phone.areacode)!}达到同样的目的。那么如果使用的是FreeMarker3.8-,有什么可选的替代方案呢?下面是我想的一种解决方案
java 代码
- /**
- * @author Ray (ayufox@gmail.com)
- */
- public class EmptyTemplateHashModel implements TemplateHashModel, TemplateScalarModel
- {
- public final static EmptyTemplateHashModel INSTANCE = new EmptyTemplateHashModel();
- public TemplateModel get(String n) throws TemplateModelException
- {
- return INSTANCE;
- }
- public boolean isEmpty() throws TemplateModelException
- {
- return true;
- }
- public String getAsString() throws TemplateModelException
- {
- return "";
- }
- }
- /**
- * @author Ray (ayufox@gmail.com)
- */
- public class DelegatingTemplateHashModel implements TemplateHashModel
- {
- private TemplateHashModel target;
- public DelegatingTemplateHashModel(TemplateHashModel target)
- {
- this.target = target;
- }
- public TemplateModel get(String name) throws TemplateModelException
- {
- TemplateModel model = this.target.get(name);
- if (model == null)
- {
- return EmptyTemplateHashModel.INSTANCE;
- }
- if (model instanceof TemplateHashModel)
- {
- return new DelegatingTemplateHashModel((TemplateHashModel) model);
- }
- return model;
- }
- public boolean isEmpty() throws TemplateModelException
- {
- return this.target.isEmpty();
- }
- }