springboot如何使用thymeleaf完成页面缓存

目录

  • 使用thymeleaf完成页面缓存
    • 直接看Demo
    • 控制层
    • 核心点是
  • thymeleaf简要基础知识
    • 1.SpringBoot可整合的模板引擎技术
    • 2.Thymeleaf常用标签(示例代码)
    • 3.Thymeleaf主要语法
    • 4.Thymeleaf基本使用

使用thymeleaf完成页面缓存
直接看Demo
注入redisservice以及其余两个bean.
@Autowiredprivate RedisService redisService; @Autowiredprivate ThymeleafViewResolver thymeleafViewResolver; @Autowiredprivate WebApplicationContext applicationContext;


控制层
@RequestMapping(value="https://www.it610.com/list",produces = "text/html; charset=utf-8")@ResponseBodypublic String showGoods(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response){ //1.从redis缓存中查询String listHtml = redisService.get("goosList",String.class); if(StringUtils.isNotEmpty(listHtml)){returnlistHtml; } //2.使用thymeleaf模板引擎手动渲染视图List goodsList = miaoshaGoodsService.selectAllMiaoshaGoods(); model.addAttribute("user",user); model.addAttribute("goodsList",goodsList); // 无法导入SpringWebContext的包SpringWebContext context = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext); String html = thymeleafViewResolver.getTemplateEngine().process("goods_list",context); //3.将手动渲染后的html存入redis缓存if(StringUtils.isNotEmpty(html)){redisService.set("goosList",html); } return html; }


核心点是
SpringWebContext context = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext); String html = thymeleafViewResolver.getTemplateEngine().process("goods_list",context);


thymeleaf简要基础知识 SpringBoot支持的视图技术之Thymeleaf
【springboot如何使用thymeleaf完成页面缓存】
1.SpringBoot可整合的模板引擎技术
  • FreeMarker
  • Groory
  • Thymeleaf
  • Mustache
  • 等等

2.Thymeleaf常用标签(示例代码)
#引入thymeleaf标签#引入外联样式文件TitleHello world


3.Thymeleaf主要语法
  • 变量表达式
${...}//获取上下文中的变量值

  • 选择变量表达式
*{...}//用于从被选定的对象获取属性值

  • 消息表达式
#{...}//用于Thymeleaf模板页面国际化内容的动态替换和展示

  • 链接URL表达式
@{...}//用于页面跳转或者资源的引入

  • 片段表达式
~{...}//用来标记一个片段模板,并根据需要移动或传递给其他模板


4.Thymeleaf基本使用
  • 4.1 在SpringBoot项目中使用Thymeleaf模板,必须保证引入Thymeleaf依赖。
org.springframework.bootspring-boot-starter-thymeleaf

  • 4.2 其次在全局配置文件中配置Thymeleaf模板的一些参数。(如设置模板缓存、模板编码、模板样式、指定模板页面存放路径、指定模板页面名称的后缀)
#模板缓存开启spring.thymeleaf.cache=true#模板编码spring.thymeleaf.encoding=UTF-8#模板样式spring.thymeleaf.mode=HTML5#指定模板页面存放路径spring.thymeleaf.prefix=classpath:/templates/#指定模板页面名称的后缀spring.thymeleaf.suffix=.html

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读