项目中需要使用原始的静态资源来搜寻到最新的静态资源文件,初步设想采用的是自定义freemaker函数来进行查询转换,网上搜索资料整理了一下
首先定义自定义函数类 需要继承TemplateMethodModelEx 参数的话 就是页面传入的参数列表
public class ChangeUriFunction implements TemplateMethodModelEx{
public Logger loger = LoggerFactory.getLogger(ChangeUriFunction.class);
private ServiceStaticResource staticResourceService = (ServiceStaticResource) ToolSpring.getBean("staticResourceService");
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arg0) throws TemplateModelException {
String fileuri = arg0.get(0).toString();//页面去除的静态资源路径(文件名)
String isOnline = PropertiesUtil.getValue(PropertiesUtil.CURRENT_CONTENT);
try {
if ("true".equals(isOnline) && fileuri != null && fileuri.length() != 0) {
System.err.println("fileuri :"+fileuri);
StaticResource staticResource = staticResourceService.getResourceByUri(null, fileuri);
//如果未查询到记录 则返回原路径
return staticResource == null ? fileuri : staticResource.getNewFileUrl();
}
} catch (Exception e) {
loger.info("调用freemaker自动以函数查询静态资源路径时发生异常!"+e.getMessage());
return fileuri;
}
return fileuri;
}
}
写完自定义标签 肯定需要在页面生效的,如果采用的是spring来管理的话,那么只需要在spring配置文件中试图解析配置上加一段配置即可
<!-- freemarker的配置 -->
<bean id="freemarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/" />
<property name="defaultEncoding" value="UTF-8" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
</props>
</property>
<!-- freemaker自定义函数配置 -->
<property name="freemarkerVariables">
<map>
<description>配置前端使用更改静态文件路径</description>
<entry key="changeUrl" value-ref="changeUrl"></entry>
</map>
</property>
</bean>
<!-- 自定义的freemaker函数-->
<bean id="changeUrl" class="jootun.platform.business.impl.ChangeUriMethod"></bean>
当然如果你不是采用spring 来进行试图解析的,也完全可以将自定义函数设置到全局进行使用的,
Configuration cfg = new Configuration();
cfg.setEncoding(Locale.CHINA, "UTF-8");
cfg.setSharedVariable("block", new BlockDirective());
//添加变更静态资源url的自定义函数
cfg.setSharedVariable("loadstatic", new ChangeUriFunction());
cfg.setServletContextForTemplateLoading(servletContext, "/WEB_INF/templates";
将自定义标签或者是函数设置到root下 ,这样即可在所有该Configuration 管理下的页面使用了;
另外,自定义标签对freemaker的页面继承效果也是很好的,对页面的扩展以及公共资源的维护上可以简化很多,开发起来简单快捷
具体高级使用 还是参考api进行学习。