使用Thymeleaf模板生成静态页面

本文介绍了如何在Java应用中使用Thymeleaf模板引擎生成静态页面。首先,要在build.gradle文件中添加Thymeleaf和NekoHTML的依赖。接着,配置application.yml以指定模板路径和相关设置。然后,创建一个简单的index.html模板,包含Thymeleaf的表达式。在运行时,为了避免错误,遵循特定的文件命名规则。为了实现动态生成,文章提出使用Redis创建生产队列,Disruptor作为消费者队列,处理商品详情页的生成,而不处理列表页。

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

引入gradle依赖

build.gradle文件中,添加

dependencies {

compile('org.springframework.boot:spring-boot-starter-thymeleaf')

        compile('net.sourceforge.nekohtml:nekohtml:1.9.22')

}

如果能保证网页完全是复合html5规范,nekohtml可以不使用。

application.yml中配置thymeleaf

spring:

  thymeleaf:

    prefix: classpath:/templates/

    suffix: .html

    mode: LEGACYHTML5

    encoding: UTF-8

    content-type: text/html

    cache: false  


创建模板

templates/index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org"

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

<meta charset="UTF-8">

<title>Title</title>

</head>

<body>

<h1 th:text="${name}">列表名称</h1>

<ul>

<li th:each="item: ${array}" th:text="${item}">条目</li>

</ul>

</body>

</html>



使用Thymeleaf生成静态页面

//构造模板引擎
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");//模板所在目录,相对于当前classloader的classpath。
        resolver.setSuffix(".html");//模板文件后缀
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(resolver);

        
        List<String> list = new ArrayList<>();
        list.add("需求");
        list.add("成果");
        list.add("人力");
        list.add("进度");

        //构造上下文(Model)
        Context context = new Context();
        context.setVariable("name", "列表数据");
        context.setVariable("array", list);



        //渲染模板
        FileWriter write = new FileWriter("result.html");
        templateEngine.process("example", context, write);

注意:这里必须是resolver.setPrefix("templates/");不能是resolver.setPrefix("/templates/");

不然就会出现运行时错误:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "example", template might not exist or might not be accessible by any of the configured Template Resolvers

文件名命名规定:

商品分类:/category/159-0-0-0-0-0-1.htm

大类id-品牌id-

商品详情页:直接使用产品id来命名网页,例如“product/132476500.htm”。

1、使用Redis来建立生产队列。

创建generate redis队列

注入

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

TaskModel task = new TaskModel();String key = "generate:" + "version:" + "v1.0.0";redisTemplate.opsForList().leftPush(key, task);

使用Disruptor来作为消费者队列。


使用此机制,来处理所有的详情页。不处理列表页。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值