SpringBoot 实例代码(1)-Freemarker 生成 HTML

    科技2022-08-13  86

    在SpringBoot工程根目录下创建如下文件或文件夹

    src/main/java/HelloWorldMainApplication.java src/main/resources/templates/index.ftl html

    HelloWorldMainApplication.java

    import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import freemarker.cache.FileTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; @SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) { try { Configuration config = new Configuration(); String path = "src\\main\\resources\\templates"; TemplateLoader templateLoader = new FileTemplateLoader(new File(path)); config.setTemplateLoader(templateLoader); Template template = config.getTemplate("index.ftl",Locale.SIMPLIFIED_CHINESE); Map<String,String> map = new HashMap<String,String>(); map.put("name", "宫水三叶"); FileWriter fileWriter = new FileWriter("html\\index.html"); template.process(map, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub SpringApplication.run(HelloWorldMainApplication.class, args); } }

    index.ftl

    <!DOCTYPE html> <html lang="zh_CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>SpringBoot 生成 html</title> </head> <body> ${name} </body> </html>

    右键实行HelloWorldMainApplication.java 会在html文件夹下生成index.html文件

    index.html

    <!DOCTYPE html> <html lang="zh_CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>SpringBoot 生成 html</title> </head> <body> 宫水三叶 </body> </html>

    浏览器效果

    Processed: 0.020, SQL: 8