使用freemarker模板时,有事会用到一些公用的变量或方法,例如上下文,或特殊的日期格式化方法等等,如果每次请求都put一次,显然很不合理,后期也不易维护。
方法一
通过FreeMarkerViewResolver的getAttributesMap();获取静态的属性容器,然后添加我们自己的。
配置如下:
@Configuration
public class FreeMarkerConfig {
@Autowired
private FreeMarkerViewResolver viewResolver;
@Autowired
private Uri uri;
@Value("${server.servlet.context-path}")
private String context;
@PostConstruct
public void setSharedVariable() throws TemplateModelException {
Map<String, Object> attributesMap = viewResolver.getAttributesMap();
//设置变量
attributesMap.put("context", context);
//设置对象
attributesMap.put("Uri", uri);
}
}
用法:
// 变量的用法
<link rel="icon" href="${context}/static/favicon.ico" type="image/x-icon"/>
// 对象的用法
<link rel="icon" href="${Uri.getUrl('/static/favicon.ico')}" type="image/x-icon"/>
方法二
通过FreeMarker包下的Configuration配置类设置全局变量和方法
配置如下:
@Configuration
public class FreeMarkerConfig {
@Autowired
private freemarker.template.Configuration configuration;
@Autowired
private Uri uri;
@Value("${server.servlet.context-path}")
private String context;
@PostConstruct
public void setSharedVariable() throws TemplateModelException {
// 设置变量
configuration.setSharedVariable("context", context);
// 设置对象
configuration.setSharedVariable("Uri", uri);
// 设置函数
configuration.setSharedVariable("copy2", new TemplateMethodModelEx() {
@Override
public Object exec(List list) throws TemplateModelException {
Object o = list.get(0);
if (o instanceof SimpleScalar) {
SimpleScalar scalar = (SimpleScalar) o;
return scalar.toString()+ scalar.toString();
}
return "";
}
});
}
}
用法:
// 变量的用法
<link rel="icon" href="${context}/static/favicon.ico" type="image/x-icon"/>
// 对象的用法
<link rel="icon" href="${Uri.getUrl('/static/favicon.ico')}" type="image/x-icon"/>
// 函数的用法
${copy2("ABC")}