Freemarker 自定义TemplateLoader解析字符串
- /**
- * Created: 2007-2-1
- * Modified: 2007-2-1
- *
- * Author: Keven Chen
- */
- package freemarker.loader;
- import java.io.IOException;
- import java.io.Reader;
- import java.io.StringReader;
- import freemarker.cache.TemplateLoader;
- /**
- * @author Keven Chen
- * @version $Revision 1.0 $
- *
- */
- public class StringTemplateLoader implements TemplateLoader {
- private String template;
- public StringTemplateLoader(String template){
- this.template = template;
- if(template == null){
- this.template = "";
- }
- }
- public void closeTemplateSource(Object templateSource) throws IOException {
- ((StringReader) templateSource).close();
- }
- public Object findTemplateSource(String name) throws IOException {
- return new StringReader(template);
- }
- public long getLastModified(Object templateSource) {
- return 0;
- }
- public Reader getReader(Object templateSource, String encoding)
- throws IOException {
- return (Reader) templateSource;
- }
- }
- /**
- * Created: 2007-2-1
- * Modified: 2007-2-1
- *
- * Author: Keven Chen
- */
- package freemarker;
- import java.io.File;
- import java.io.OutputStreamWriter;
- import java.io.StringWriter;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Map;
- import freemarker.loader.ClassPathTemplateLoader;
- import freemarker.loader.StringTemplateLoader;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- /**
- * @author Keven Chen
- * @version $Revision 1.0 $
- *
- */
- public class Test {
- public static void main(String[] args) throws Exception {
- Configuration cfg = new Configuration();
- cfg.setTemplateLoader(new StringTemplateLoader("欢迎:${user}"));
- cfg.setDefaultEncoding("UTF-8");
- Template template = cfg.getTemplate("");
- Map root = new HashMap();
- root.put("user", "Keven Chen");
- StringWriter writer = new StringWriter();
- template.process(root, writer);
- System.out.println(writer.toString());
- }
- }
相关推荐
81314797 2020-11-18
89314493 2020-11-03
81941231 2020-09-17
thisisid 2020-09-09
如狼 2020-08-15
82384399 2020-06-16
86384798 2020-05-12
80183053 2020-05-02
86384798 2020-04-26
86384798 2020-04-11
rionchen 2020-04-09
86384798 2020-04-07
86384798 2020-04-04
80183053 2020-03-07
87201943 2020-03-06
83961233 2020-02-26
87201943 2020-02-21