gpt4 book ai didi

spring - 如何在Spring Boot中使用Thymeleaf生成XML?

转载 作者:行者123 更新时间:2023-12-02 13:20:28 26 4
gpt4 key购买 nike

我有一个使用Spring Boot,Kotlin和Thymeleaf构建的Web应用程序。我有一些HTML模板正在工作,但是我想让其中一个返回XML文件。该XML将是使用Thymeleaf属性的Thymeleaf模板。在Spring Boot中这样做的正确方法是什么?另外,应下载XML。

我已经看到了:Spring Boot & Thymeleaf with XML Templates,但似乎它将切换Thymeleaf来生成整个站点的XML,而不仅仅是为单个 Controller 生成。

最佳答案

好的,一种方法是用一种方法配置Thymeleaf引擎。例如:

@GetMapping("/xml")
public void xml(HttpServletResponse res) throws Exception {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(new AnnotationConfigApplicationContext());
resolver.setPrefix("classpath:/xml/");
resolver.setSuffix(".xml");
resolver.setCharacterEncoding("UTF-8");
resolver.setTemplateMode(TemplateMode.XML);

SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(resolver);

Context ctx = new Context();
ctx.setVariable("notes", Arrays.asList("one note", "two note"));
String xml = engine.process("template", ctx);

res.setHeader("Content-Disposition", "attachment; filename=template.xml");
res.setContentType("application/xml");
PrintWriter writer = res.getWriter();
writer.print(xml);
writer.close();
}

模板位于 src/main/resources/xml/template.xml中的位置。您可以使用 ctx.setVariable()方法设置模型变量。

关于spring - 如何在Spring Boot中使用Thymeleaf生成XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com