freemarker 处理网站静态化完整实例,包含自定义标签的使用

代码中未使用任何框架,使用原生Servlet实现。

自定义标签的使用:

1、在freemarker.template.Configuration中初始化标签。

//初始化标签
config.setSharedVariable("hello", new HelloWorldDirective());

 2、在标签类中实现TemplateDirectiveModel接口中的execute方法

public class HelloWorldDirective implements TemplateDirectiveModel {

	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
	TemplateDirectiveBody body) throws TemplateException, IOException {
	List<User> list = getUserList(params);
	env.setVariable("list", ObjectWrapper.DEFAULT_WRAPPER.wrap(list));
	body.render(env.getOut());
	}


	@SuppressWarnings("unchecked")
	private List<User> getUserList(Map params){
	List<User> userList = new ArrayList<User>();
	SimpleNumber vid = (SimpleNumber)params.get("id");
	for(int i=0;i< vid.getAsNumber().intValue();i++){
	User user = new User();
	user.setAge((int)Math.round(Math.random()*10));
	user.setId(i);
	user.setName("good");
	userList.add(user);
	}
	return userList;
	}

}

 3、模板中即可使用自定义标签hello

<table border="1">
	<tr>
  		<td>用户名</td>
	  	<td>年龄</td>
	  	<td>生日</td>
	  	<td>id</td>
	  	<td>操作</td>
  	</tr>
	<@hello id=3>
	     <#list list as user>
		<tr>
	  		<td>${user.name}</td>
		  	<td>${user.age}</td>
		  	<td>
			<#if user.birthday ??>
		  		${user.birthday?string("yyyy-MM-dd HH:mm:ss")}
			</#if>
		  	</td>
		  	<td>${user.id}</td>
		  	<td><a href="http://localhost/htmlpage/DelUser.do?id=${user.id}">删除</a></td>
	  	</tr>
	     </#list>
	</@hello>
  </table>

 即可实现静态化。

完整代码下载。

原文地址:https://www.cnblogs.com/treemanfm/p/2994861.html