FreeMarker教你如何生成html静态页面源码

一、 FreeMarker生成静态页原理

众所周知,FreeMarker适合于作为Web应用的表现层,那么我们就把把页面中所需要的样式放入FreeMarker文件中,然后将页面所需要的数据动态绑定,并放入Map中,通过调用FreeMarker模板文件解析类process()方法完成静态页面的生成。了解了上面的原理,接下来四夕就一步步带您实现FreeMarker生成静态页面。


二、 创建FreeMarker模板文件question.ftl。
<head>
<title>生成html静态页面</title>
<meta http-equiv="X-UA-Compatible"     content="IE=edge"; charset=UTF-8" />
</head>
<body>
     <span>生成题干ID${question.id}</span>
     <span>生成题干内容${question.quesContent}</span>   

</body>


三、 创建FreeMarker模板文件解析器类CreatHtml
package com.itstyle.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import com.itstyle.model.Question;


import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**

* @author 科帮网(www.52itstyle.com)
*
*/
public class CreatHtml {
     public static void CreatAllHtml(HttpServletRequest request){
                Map<String,Object> root = new HashMap<String,Object>(); 
                String path = request.getSession().getServletContext().getContextPath();
                String templatePath = request.getSession().getServletContext().getRealPath("/file");
                String templateName = "question.flt";
                        String targetHtmlPath =request.getSession().getServletContext().getRealPath("/file")
+Constants.SF_FILE_SEPARATOR+"question.html";
                        Question question = new Question(1,"我是中国人");
                        root.put("question", question);   
                        root.put("path" , path);
                        crateHTML(root, templatePath, templateName, targetHtmlPath);

     }


     public static void crateHTML(Map<String,Object> data,String templatePath,String templateName,String targetHtmlPath){
             Configuration freemarkerCfg = new Configuration();  
                 //加载模版  
                 Writer out = null;
                 try {  
                         //设置要解析的模板所在的目录,并加载模板文件  
                         freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath));
                         //设置包装器,并将对象包装为数据模型  
                         freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
                     //指定模版路径  
                     Template template = freemarkerCfg.getTemplate(templateName,"UTF-8");  
                     template.setEncoding("UTF-8");  
                     //静态页面路径  
                     FileOutputStream fos = new FileOutputStream(targetHtmlPath);  
                     out = new OutputStreamWriter(fos,"UTF-8");  
                     //合并数据模型与模板  
                 template.process(data, out);  
                 } catch (Exception e) {  
                     e.printStackTrace();  
                 }finally{
                          try {
                                  out.flush();
                                  out.close();  
                         } catch (IOException e) {
                                 e.printStackTrace();
                         }  
                 }
          }
     

}


四、 创建FreeMarker模板文件动态绑定的数据对象类Question.java(实体类)


package com.itstyle.model;
/**

* @author 科帮网(www.52itstyle.com)
*
*/
public class Question {
    private Integer id;
    private String quesContent;
    
        public Question() {
                super();
        }
        public Question(Integer id, String quesContent) {
                super();
                this.id = id;
                this.quesContent = quesContent;
        }
        public Integer getId() {
                return id;
        }
        public void setId(Integer id) {
                this.id = id;
        }
        public String getQuesContent() {
                return quesContent;
        }
        public void setQuesContent(String quesContent) {
                this.quesContent = quesContent;
        }
    

}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Spring Boot 中的 Freemarker 模板引擎来生成静态 HTML 页面,然后让前端通过 HTTP 请求访问这些页面。 下面是一个简单的示例: 1. 在 Spring Boot 项目中添加 Freemarker 依赖,比如: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 Freemarker 相关属性,比如: ``` # 模板文件所在目录 spring.freemarker.template-loader-path=classpath:/templates/ # 静态文件生成目录 spring.freemarker.static-file-location=file:/path/to/static/files/ ``` 3. 创建一个 Freemarker 模板文件,比如 `/templates/index.ftl`: ``` <!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1>Hello, ${name}!</h1> </body> </html> ``` 4. 创建一个 Spring Controller 类,生成静态 HTML 页面: ``` @Controller public class MyController { @Autowired private Configuration freemarkerConfig; @GetMapping("/generate") public void generateHtml(@RequestParam("name") String name, HttpServletResponse response) throws Exception { Template template = freemarkerConfig.getTemplate("index.ftl"); Map<String, Object> model = new HashMap<>(); model.put("name", name); StringWriter stringWriter = new StringWriter(); template.process(model, stringWriter); String html = stringWriter.toString(); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(html); response.getWriter().flush(); response.getWriter().close(); } } ``` 5. 启动 Spring Boot 应用,访问 `http://localhost:8080/generate?name=World`,即可生成静态 HTML 页面,并在浏览器中显示。 注意:在实际生产环境中,你需要将生成静态 HTML 页面放到一个静态文件目录中(比如 `/path/to/static/files/`),然后让前端通过 HTTP 请求访问这些页面

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值