FreeMarkerアシスト
6352 ワード
/**
* FreeMarker
* @author Rubekid
*
*/
public class FreeMarkerHelper {
/**
*
*/
private static final String TEMPLATE_PATH = "/templates/freemarker/";
/**
*
* @param tpl
* @param rootMap
* @return
* @throws IOException
* @throws TemplateException
*/
public static String fetch(String tpl, Object rootMap) throws IOException, TemplateException{
Template template = getTemplate(tpl);
Writer out= new StringWriter();
template.process(rootMap, out);
String result = out.toString();
out.flush();
return result;
}
/**
*
* @param tpl
* @param rootMap
* @param out
* @throws IOException
* @throws TemplateException
*/
public static void display(String tpl, Object rootMap, Writer out) throws IOException, TemplateException{
Template template = getTemplate(tpl);
template.process(rootMap, out);
out.flush();
}
/**
*
* @param tpl
* @return
* @throws IOException
*/
private static Template getTemplate(String tpl) throws IOException{
Configuration config = new Configuration();
String path = WebUtils.getContextPath() + TEMPLATE_PATH;
String name = tpl;
int pos = tpl.lastIndexOf("/");
if(pos > -1){
path += tpl.substring( 0, pos+1 );
name += tpl.substring( pos+1 );
}
config.setDirectoryForTemplateLoading(new File(path));
config.setObjectWrapper(new DefaultObjectWrapper());
return config.getTemplate(name ,"utf-8");
}
/**
* ( )
* @param source
* @throws IOException
*/
private static Template getTemplate(String name, String source) throws IOException{
Configuration config = new Configuration();
StringTemplateLoader loader = new StringTemplateLoader();
loader.putTemplate(name, source);
config.setTemplateLoader(loader);
return config.getTemplate(name, "utf-8");
}