我想在Java中創建一個模板文件,並使用即時通訊的Eclipse IDE。我想創建一個模板文件這樣一個程序,它從用戶得到的參數,它應該是能夠將這些參數粘貼到模板文件,然後將其保存爲獨立的文件。我怎樣才能做到這一點 ?如何在Java中創建基於模板文件?
請指導我。
感謝 N.B
我想在Java中創建一個模板文件,並使用即時通訊的Eclipse IDE。我想創建一個模板文件這樣一個程序,它從用戶得到的參數,它應該是能夠將這些參數粘貼到模板文件,然後將其保存爲獨立的文件。我怎樣才能做到這一點 ?如何在Java中創建基於模板文件?
請指導我。
感謝 N.B
有一噸的Java的模板解決方案。
這裏是你將如何在我的開源模板引擎,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(只需將在主題類路徑/ my_template.txt)
My name is {$name}.
My favorite color is {$favorite_color}.
輸出:
My name is Lancelot.
My favorite color is blue.
您的模板可以通過添加製成有點聰明|過濾器和:默認爲您的標籤。
my_template.txt - 例如2
My name is {$name|defang:[not provided]}.
My favorite color is {$favorite_color|defang|lc:[not provided]}.
在這個例子中,defang
濾波器消除,這可能有助於形成一個XSS攻擊的任何字符。該lc
過濾器更改文本爲小寫。如果值爲空,冒號後的任何內容都將被輸出。
沒有可用於編輯組塊的Eclipse plugin在Eclipse IDE中直接模板。該插件爲模板文檔提供語法高亮顯示和大綱視圖。
組塊可以做更多的事情,拿在docs偷看了一個快速瀏覽。充分披露:我喜歡Chunk,部分原因是我創建了它。
讓我們打入步驟如下:
獲得來自用戶的輸入參數:
但是你這樣做(發送到一個servlet的請求,使用CLI,或傳遞參數到主要方法),您需要以某種對象或數據結構捕獲輸入。要做到這一點,我將創建一個簡單的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
希望它能幫助!
(一般來說這是很好的透露affiliations :) – 2013-01-05 16:36:56
更新,以幫助警告人們,這個答案是一個無恥的自我插件:) – 2013-01-05 23:52:42
容易設置!我用自己的方式鍛鍊了一下。但最後,得到它的工作! :) 非常感謝! – alexander 2015-04-18 07:39:21