如何在Spring Boot中使用Thymeleaf生成XML? [英] How do you generate an XML with Thymeleaf in Spring Boot?
问题描述
我有一个使用Spring Boot,Kotlin和Thymeleaf构建的Web应用程序.我有一些HTML模板正在工作,但是我想让其中一个返回XML文件.该XML将是使用Thymeleaf属性的Thymeleaf模板.在Spring Boot中这样做的正确方法是什么?另外,应该下载XML.
I have a web application I'm building with Spring Boot, Kotlin and Thymeleaf. I have some HTML templates working, but I want to make one return an XML file. This XML would be a Thymeleaf template, using Thymeleaf attributes. What's the correct way of doing that in Spring Boot? Also, the XML should be downloaded.
我已经看到了: Spring Boot& Thymeleaf具有XML模板,但是似乎它将切换Thymeleaf以在整个站点范围内生成XML,而不仅仅是针对单个控制器.
I've seen this: Spring Boot & Thymeleaf with XML Templates, but it seems that would switch Thymeleaf to generate XMLs site-wide, not just for a single controller.
推荐答案
那么,一种实现方法是用一种方法配置Thymeleaf引擎.例如:
Alright then, one way of doing it would be configuring the Thymeleaf engine in a single method. For example:
@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()
方法设置模型变量.
Where the template is located in src/main/resources/xml/template.xml
. You set your model variables using the ctx.setVariable()
method.
这篇关于如何在Spring Boot中使用Thymeleaf生成XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!