使用场景
- 导出共享变量,比如给js添加version,这样每次重新启动服务,刷新js缓存
- 导出一个静态方法,在模板中可以直接直接调用静态方法对数据进行处理
3、根据生产,测试环境使用不同的js版本(开发版本,生产版本)
代码
要导出的静态方法toJSON
public class JSON {
public static final String NAME = "JSON";
public static String toJSON(Object src) {
return com.alibaba.fastjson.JSON.toJSONString(src);
}
}
Spring Boot配置,主要是使用freemarker的Configuration
的setSharedVariable
方法
@Configuration
public class FreeMarkerConfig {
@Value("${spring.profiles.active:prod}")
private String env;
@Autowired
private freemarker.template.Configuration configuration;
@PostConstruct
public void config() throws Exception {
BeansWrapper wrapper = new BeansWrapperBuilder(freemarker.template.Configuration.VERSION_2_3_30).build();
//wrapper.getStaticModels().get(className), className是导出类的完整路径
//getStaticModels,通过方法名能够知道是获取静态Model的,这样在模板中就可以调用导出类的j静态方法了
TemplateModel templateModel = wrapper.getStaticModels().get(JSON.class.getName());
//setSharedVariable 设置共享变量,setSharedVariable(String name, TemplateModel tm)
// 在模板中可以通过name获取导出的model
configuration.setSharedVariable(JSON.NAME, templateModel); //权限操作
configuration.setSharedVariable("version", new Date().getTime());
configuration.setSharedVariable("env", env);
}
}
模板中的代码
//控制js的版本号
<script src="http://static.cehuio.com/cehui/js/axios.min.js?version=${version}" type="text/javascript"></script>
//控制生成,开发环境使用的vue版本
<script src="http://static.cehuio.com/cehui/js/vue-${env}.js?version=${version}"></script>
调用静态方法
JSON.toJSON
中的JSON
是setSharedVariable
方法的name
参数的值,toJSON
是要调用的静态方法
<script type="text/javascript">
<#if Session.session_user??>
window.user = JSON.parse('${JSON.toJSON(Session.session_user)?no_esc}');
</#if>
</script>