springboot整合freemarker生成静态HTML页面

springboot整合freemarker生成静态HTML页面

这篇博客是基于ftl模板文件生成静态html页面,供大家参考,首先是pom:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
   <version>1.4.1.RELEASE</version>
<dependency>

接下来是freemarker的一些基本设置,包括他的ftl文件路径,也就是他的模板路径,我在resources下templates下,后边是application.properties中的设置:

spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.content-type=text/html

接下来就是模本文件ftl,其中第一行的代码非常关键,我刚开始出现生成的页面浏览器打开是中文乱码,工具打开正常,后来查资料发现,文件默认保存是GBK

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type='text/css'>
    *{
        margin: 0;
        padding:0;
    }
    html{
        font-size: 14px;
    }
    p{
        width: 100%;
        margin-bottom: 5px;
    }
    p img{
        width: 100%;
    }
</style>
<!DOCTYPE html>
<html>
<body>
<h4>标题:${title}</h4>
</br>
${content}
</br>
</body>
</html>

接下来就是后台代码其中注意保存的路径问题

//获得freeMarker对象
@Autowired
private Configuration configuration;
/**
 * 添加内容文件同时生成静态页面
 *
 * @param weixinContent 内容实体对象
 * @param request
 * @param
 * @return
 */
@ResponseBody
@RequestMapping(value = "/service", method = RequestMethod.POST)
public String ContentAdd(WeixinContent weixinContent,  HttpServletRequest request,HttpServletResponse response) {

    try {
        //设置创建时间
        weixinContent.setGmtCreate(new Date());
        //设置修改时间
        weixinContent.setGmtModified(new Date());
        //设置是不否删除
        weixinContent.setDelFlag(1);

        //设置状态 未测试状态
        weixinContent.setState(1);
        //设置创建人
        weixinContent.setFounder("哈哈");
        //设置修改人
        weixinContent.setModifier("嘿嘿");
        //设置内容类型
        weixinContent.setContentType("嘻嘻");
        //设置菜单ID
        weixinContent.setMenuId(25L);
        //调用service代理对象进行添加操作
        weixinContentService.insert(weixinContent);
            Long id=weixinContent.getId();

        //获得保存静态资源路径
     	String htmlRealPath=request.getSession().getServletContext().getRealPath("/")+"\\freeMarker\\";
        System.out.println("保存的绝对路径是:"+htmlRealPath+ "/" + id + ".html");
        // 创建文件对象
        File htmlFile = new File(htmlRealPath + "/" + id + ".html");
        // 判断是否有静态页面文件 若没有
        if (!htmlFile.exists()) {
            // 获得模板对象
            Template template = configuration.getTemplate("content.ftl");

            //先得到文件的上级目录,并创建上级目录,在创建文件
            htmlFile.getParentFile().mkdir();
            try {
                //创建文件
                htmlFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建集合
            //创建map集合
            Map<String,Object> map=new HashMap<>();
            map.put("title",weixinContent.getTitle());
            map.put("content",weixinContent.getContent());
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"UTF-8"));
            // 合并输出 创建页面文件
            template.process(map,out);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值