springboot中thymeleaf实现新闻页面静态化

整体结构:
在这里插入图片描述

1、实体类

package com.hdit.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * @基本功能:
 * @ClassName: News
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/17 15:43
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class News {
   
    private int id;
    private String newsId;
    private String newsTitle;
    private String newsContent;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date    newsDate;
}

2、thymeleaf模板引擎(TemplateEngine)实现数据与模板组合。

package com.hdit.util;

import com.hdit.domain.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Administrator
 * @version v1.0
 * @className PageStaticUtil
 * @Date 2021/3/17
 */
@Component
public class PageStaticUtil {
   

    @Autowired
    private TemplateEngine  templateEngine;

    public  void  toHTML(News news){
   
//      thymeleaf上下文
        Context   context=new Context();
//        设置数据
        context.setVariable("news",news);

//        输出
        FileWriter   out=null;
        try {
   
            out=new FileWriter("C:\\Users\\ljm\\Desktop\\news\\"+news.getNewsId()+".html");
            templateEngine.process("news.html",context,out);
        }catch (Exception  e){
   

        }finally {
   
            try {
   
                out.close();
            } catch (IOException e) {
   
                e.printStackTrace();
            }
        }

    }

}

3、配置将生成的组合后的html文件分别存放在服务器下和本地。

package com.hdit.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Administrator
 * @version v1.0
 * @className PageStaticPathConfig
 * @Date 2021/3/17
 */
@Configuration
public class PageStaticPathConfig implements WebMvcConfigurer{
   
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
   
            registry.addResourceHandler("/news/**").addResourceLocations("file:C:/Users/ljm/Desktop/news/");
        }
}

4、controller层

package com.hdit.controller;

import com.hdit.domain.News;
import com.hdit.service.NewService;
import com.hdit.util.PageStaticUtil;
import org
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值