springboot+thymeleaf+nginx实现动态页面纯静态化方案

时间:2025-03-27 09:36:41
  • @Service
  • public class StaticHtmlService {
  • protected Logger logger = (StaticHtmlService.class);
  • @Autowired
  • private TemplateEngine templateEngine;//这是thymeleaf模板处理引擎
  • @Autowired
  • private ApplicationContext appContext;//这是Spring容器上下文
  • @Autowired
  • private ConfigProperties config;//这是工程中的配置属性,如静态文件的根目录/usr/local/nginx/html
  • /**
  • * 生成html静态页面
  • * @param modelAndView
  • * @param request
  • * @param response
  • */
  • public void genHtmlPage(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) {
  • FileWriter fileWriter = null;
  • try {
  • String fileName = ();
  • if(!(".html")) {//将.html结尾的请求生成静态页面
  • return;
  • }
  • fileName = () + fileName;//构造静态html文件完整路径
  • File file = new File(fileName);
  • if(!file.getParentFile().exists()) {
  • file.getParentFile().mkdirs();
  • }
  • fileWriter = new FileWriter(file);
  • SpringWebContext context = new SpringWebContext(request, response, (), (), (), appContext);
  • ((), context, fileWriter);//将thymeleaf模板生成的结果存入静态文件中
  • ("已生成静态文件:" + fileName);
  • }catch(Exception e) {
  • ();
  • }finally {
  • (fileWriter);
  • }
  • }
  • /**
  • * 用于更新时删除之前生成的静态页面
  • * @param fileName
  • */
  • public void deleteHtmlPage(String fileName) {
  • try {
  • fileName = () + fileName;
  • File file = new File(fileName);
  • //删除文件或目录
  • (file);
  • ("已删除静态文件:" + fileName);
  • }catch(Exception e) {
  • ();
  • }
  • }
  • }