注入redisservice以及其余两个bean.
@Autowired private RedisService redisService; @Autowired private ThymeleafViewResolver thymeleafViewResolver; @Autowired private WebApplicationContext applicationContext;
@RequestMapping(value="/list",produces = "text/html;charset=utf-8") @ResponseBody public String showGoods(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response){ //1.从redis缓存中查询 String listHtml = redisService.get("goosList",String.class); if(StringUtils.isNotEmpty(listHtml)){ return listHtml; } //2.使用thymeleaf模板引擎手动渲染视图 List<MiaoshaGoods> 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);
SpringBoot支持的视图技术之Thymeleaf
FreeMarker
Groory
Thymeleaf
Mustache
<!DOCTYPE html> <html lang = "en" xmlns:th="http://www.thymeleaf.org"> #引入thymeleaf标签 <head> <meta charset = "UTF-8"> <meta name = "viewport" content = "width = device - width, initial - scale = 1.0"> <meta http-equiv = "X-UA-Compatible" content = "ie-edge"> <link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" rel="external nofollow" th:href="@{/css/gtvg.css}" rel="external nofollow" /> #引入外联样式文件 <title>Title</title> </head> <body> <p th:text="#{hello}">Hello world</p> </body> </html>
${...} //获取上下文中的变量值
*{...} //用于从被选定的对象获取属性值
#{...} //用于Thymeleaf模板页面国际化内容的动态替换和展示
@{...} //用于页面跳转或者资源的引入
~{...} //用来标记一个片段模板,并根据需要移动或传递给其他模板
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf<artifactId> </dependency>
#模板缓存开启 spring.thymeleaf.cache=true #模板编码 spring.thymeleaf.encoding=UTF-8 #模板样式 spring.thymeleaf.mode=HTML5 #指定模板页面存放路径 spring.thymeleaf.prefix=classpath:/templates/ #指定模板页面名称的后缀 spring.thymeleaf.suffix=.html
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。