我想使用Eclipse IDE在java和Im中创建模板文件。我想创建一个模板文件,使得一个程序从用户获取参数,它应该能够将这些参数粘贴到模板文件中,然后将其保存为单独的文件。我怎样才能做到这一点 ?
请指导我。
由于 N.B
答案 0 :(得分:7)
以下是我在开源模板引擎Chunk中执行此操作的方法。
import com.x5.template.Theme;
import com.x5.template.Chunk;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
...
public void writeTemplatedFile() throws IOException
{
Theme theme = new Theme();
Chunk chunk = theme.makeChunk("my_template", "txt");
// replace static values below with user input
chunk.set("name", "Lancelot");
chunk.set("favorite_color", "blue");
String outfilePath = getFilePath();
File file = new File(outfilePath);
FileWriter out = new FileWriter(file);
chunk.render(out);
out.flush();
out.close();
}
my_template.txt(只需放在themes / my_template.txt的类路径中)
My name is {$name}.
My favorite color is {$favorite_color}.
输出:
My name is Lancelot.
My favorite color is blue.
通过添加| filters和:默认为您的代码,您的模板可以变得更加智能。
my_template.txt - 示例2
My name is {$name|defang:[not provided]}.
My favorite color is {$favorite_color|defang|lc:[not provided]}.
在此示例中,defang
过滤器会删除可能有助于形成XSS攻击的任何字符。 lc
过滤器将文本更改为小写。如果值为null,则输出冒号之后的任何内容。
可以在Eclipse IDE中直接编辑Chunk模板Eclipse plugin。该插件提供语法突出显示和模板文档的大纲视图。
Chunk可以做更多事情,看看docs进行快速浏览。完全披露:我喜欢Chunk的部分原因是我创造了它。
答案 1 :(得分:2)
有大量的Java模板解决方案。
答案 2 :(得分:0)
答案 3 :(得分:0)
让我们分解为步骤:
从用户那里获取输入参数:
但是,您执行此操作(向servlet发送请求,使用CLI或将参数传递给main方法),您将需要捕获某种对象或数据结构中的输入。为此,我将创建一个简单的pojo类:
public class UserInput
{
protected String firstName;
protected String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
这很方便,所以你可以尝试几个模板库。最佳实践是使用界面,以便您可以轻松改变主意并切换到其他库。我最喜欢的图书馆是freemarker和mustache。以下是演示其常见流程的界面示例。
public interface ITemplateEngine
{
/**
* creates the template engines instance and sets the root path to the templates in the resources folder
* @param templatesResouceFolder
*/
public void init(String templatesResouceFolder);
/**
* sets the current template to use in the process method
* @param template
*/
public void setTemplate(String template);
/**
* compiles and writes the template output to a writer
* @param writer
* @param data
*/
public void process(Writer writer, Object data);
/**
* returns the template file extension
* @return
*/
public String getTemplateExtension();
/**
* finishes the write process and closes the write buffer
*/
public void flush();
}
第一个是 freemarker 模板的示例......
/**
* This class is a freemarker implementation of ITemplateEngine
* Use ${obj.prop} in your template to replace a certain the token
* Use ${obj.prop!} to replace with empty string if obj.prop is null or undefined
*
*
*/
public class FreemarkerTemplateEngine implements ITemplateEngine
{
protected Configuration instance = null;
protected String templatesFolder = "templates";
protected Template templateCompiler = null;
protected Writer writer = null;
@Override
public void init(String templatesResouceFolder)
{
if(instance == null){
instance = new Configuration();
instance.setClassForTemplateLoading(this.getClass(), "/");
this.templatesFolder = templatesResouceFolder;
}
}
@Override
public void setTemplate(String template)
{
try
{
templateCompiler = instance.getTemplate(templatesFolder + File.separatorChar + template + getTemplateExtension());
} catch (IOException ex)
{
Logger.getLogger(FreemarkerTemplateEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void process(Writer writer, Object data)
{
try
{
templateCompiler.process(data, writer);
this.writer = writer;
} catch (TemplateException | IOException ex)
{
Logger.getLogger(FreemarkerTemplateEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String getTemplateExtension()
{
return ".ftl";
}
@Override
public void flush()
{
try
{
this.writer.flush();
} catch (IOException ex)
{
Logger.getLogger(FreemarkerTemplateEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
这是小胡子模板引擎的一个例子......
/**
*
* Use {{obj.prop}} in your template to replace a certain the token
* If obj.prop is null or undefined, it will automatically replace it with an empty string
* If you want to exclude an entire section based on if a value is null, undefined, or false you can do this:
* {{#obj.prop}}
* Never shown
* {{/obj.prop}}
*/
public class MustacheTemplateEngine implements ITemplateEngine
{
protected MustacheFactory factory = null;
protected Mustache instance = null;
protected Writer writer = null;
protected String templatesFolder = "templates";
@Override
public void init(String templatesResouceFolder)
{
if(factory == null){
factory = new DefaultMustacheFactory();
this.templatesFolder = templatesResouceFolder;
}
}
@Override
public void setTemplate(String template)
{
instance = factory.compile(templatesFolder + File.separatorChar + template + getTemplateExtension());
}
@Override
public void process(Writer writer, Object data)
{
this.writer = instance.execute(writer, data);
}
@Override
public String getTemplateExtension()
{
return ".mustache";
}
@Override
public void flush()
{
try
{
this.writer.flush();
} catch (IOException ex)
{
Logger.getLogger(MustacheTemplateEngine.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Freemarker模板有一个' .ftl'扩展和小胡子模板有一个' .mustache'延期。让我们创建一个名为' test.mustache'的胡子模板,并将其放入' resources / templates'文件夹中。
Hello {{firstName}} {{lastName}}!
创建JUnit测试总是一个好主意
public class JavaTemplateTest
{
ITemplateEngine templateEngine = new MustacheTemplateEngine();
public File outputFolder = new File(System.getProperty("user.home") + "/JavaTemplateTest");
@Before
public void setUp()
{
outputFolder.mkdirs();
}
@After
public void tearDown()
{
for (File file : outputFolder.listFiles())
{
file.delete();
}
outputFolder.delete();
}
public JavaTemplateTest()
{
}
@Test
public void testTemplateEngine() throws Exception
{
//mock the user input
UserInput userInput = new UserInput();
userInput.setFirstName("Chris");
userInput.setLastName("Osborn");
//create the out put file
File file = new File(outputFolder.getCanonicalPath() + File.separatorChar + "test.txt");
//create a FileWriter
try (Writer fileWriter = new FileWriter(file.getPath()))
{
//put the templateEngine to work
templateEngine.init("templates");
templateEngine.setTemplate("test"); //resources/templates/test.mustache
templateEngine.process(fileWriter, userInput); //compile template
templateEngine.flush(); //write to file
}
//Read from the file and assert
BufferedReader buffer = new BufferedReader(new FileReader(file));
Assert.assertEquals("Hello Chris Osborn!", buffer.readLine());
}
}
基本上就是这样。如果使用maven进行设置,测试应在运行mvn install
目标时运行并通过。
以下是我为此示例创建的项目代码:https://github.com/cosbor11/java-template-example
希望它有所帮助!