指令方法
Freemarker中自定义指令需要实现TemplateDirectiveModel接口,并实现execute方法
//使用注解方式,这里也可以使用spring的bean的方式
@Service
public class RoleDirectiveModel implements TemplateDirectiveModel {
/**
* @param environment 环境变量,如果在开发复杂功能的是时候,可能会用到该参数
* @param map 指令参数
* @param templateModels 指令变量
* @param templateDirectiveBody 指令内容
* @throws TemplateException
* @throws IOException
* 这里的参数除了Body不能为空外,其他都能为null
*/
public void execute(Environment environment,
Map map,
TemplateModel[] templateModels,
TemplateDirectiveBody templateDirectiveBody)
throws TemplateException, IOException {
//获取指令的参数,这里需要先转化为TemplateScalarModel类型
TemplateScalarModel user = (TemplateScalarModel) map.get("user");
TemplateScalarModel password = (TemplateScalarModel) map.get("password");
//使用getAsString()将TemplateScalarModel类型的参数转成string类型
System.out.println(user.getAsString()+":"+password.getAsString());
List<String> role = new ArrayList<String>();
if(user.getAsString().equals("admin") && password.getAsString().equals("123")){
templateModels[0] = TemplateBooleanModel.TRUE;
role.add("save");
role.add("delete");
}else{
role.add("你没有权限!");
}
//使用SimpleSequence将list转化为模板序列
templateModels[1] = new SimpleSequence(role,null);
//输出内容
templateDirectiveBody.render(environment.getOut());
}
}
配置
自定义指令,还需要在freemarkerConfig中添加
<property name="freemarkerVariables">
<map>
<!--role:指令名
value-ref:使用的指令方法,即上面定义的类-->
<entry key="role" value-ref="roleDirectiveModel"></entry>
</map>
</property>
action页面跳转
@RequestMapping("/role")
public String role(){
return "role";
}
页面引用自定义指令
user、password为入参,入参是使用key,value形式,如果有多个入参,直接跟在后面写,使用空格隔开。与出参使用分号隔开。
result1,result2:为出参,多个出参之间使用逗号
<@role user='admin' password='123';result1,result2>
<#if result1>
用户名是:admin;
</#if></html></br>
权限有:
<#list result2 as item>
${item}
</#list>
</@role>
方法获取到的参数