Thymeleaf手动渲染,可做页面缓存.

本文介绍了一种使用Thymeleaf模板引擎结合Redis缓存来高效渲染商品列表页面的方法。通过在控制器中注入ThymeleafViewResolver和ApplicationContext,实现了对商品列表的动态获取和缓存存储,减少了数据库的频繁访问,提高了页面加载速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注入两个类 

	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;
	
	@Autowired
	ApplicationContext applicationContext;

渲染方法

 @RequestMapping(value="/to_list", produces="text/html")
 @ResponseBody
 public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
    	
    	//取缓存
    	String html = redisService.get("goods_list", String.class);
    	if(!StringUtils.isEmpty(html)) {
    		return html;
    	}
        //获取商品列表
    	List<GoodsVo> goodsList = goodsService.listGoodsVo();
    	model.addAttribute("goodsList", goodsList);
        //手动渲染
    	SpringWebContext ctx = new SpringWebContext(request,response,
    			request.getServletContext(),request.getLocale(), model.asMap(), applicationContext );
    	html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        //写缓存
    	if(!StringUtils.isEmpty(html)) {
    		redisService.set("goods_list", html);
    	}
    	return html;
    }

 

Thymeleaf是一款流行的Java模板引擎,它可以将HTML模板与Java代码进行结合,生成动态的Web页面。在使用Thymeleaf时,我们可以使用缓存来提高网站的性能。 Thymeleaf缓存可以分为两种类型: 1. 模板缓存Thymeleaf可以缓存编译后的模板,这样当同一个模板被多次使用时,不需要每次都重新解析、编译和执行,可以直接使用缓存中的模板,从而提高性能。 2. 片段缓存Thymeleaf可以缓存页面中的某些片段,这样当页面需要渲染这些片段时,可以直接使用缓存中的内容,从而减少查询数据库或其他资源的次数,提高性能。 在Thymeleaf中,我们可以通过以下方式启用缓存: 1. 模板缓存:在Spring Boot项目中,默认情况下,Thymeleaf会自动启用模板缓存。如果需要手动配置缓存,可以在application.properties文件中设置相关的属性,例如: ``` spring.thymeleaf.cache=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html ``` 2. 片段缓存Thymeleaf提供了一个th:fragment指令,可以将页面中的某些片段缓存起来。例如: ``` <div th:fragment="header" th:cacheable="true"> ... </div> ``` 在上面的例子中,th:cacheable="true"表示这个片段可以被缓存。当页面需要渲染这个片段时,Thymeleaf会检查缓存中是否已经存在这个片段的内容,如果存在,则直接使用缓存中的内容,否则会查询数据库或其他资源,并将查询结果缓存起来。 需要注意的是,缓存虽然可以提高性能,但也会增加系统的复杂性和内存使用量。因此,在使用缓存时,需要根据具体情况进行权衡和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值