1
votes

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.

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.

2

2 Answers

2
votes

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();
}

Where the template is located in src/main/resources/xml/template.xml. You set your model variables using the ctx.setVariable() method.

0
votes

Unless you want to use Thymeleaf attributes in your XML files -- for example, something like:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <node th:each="value: ${values}" th:text="${value} />
</root>

then you shouldn't have to configure any new TemplateResolvers or TemplateEngines (and Thymeleaf doesn't have anything to do with this question).

Other than that, you haven't provided enough information. There are plenty of examples of downloading files with Spring and since I don't know how or from what you are generating your xml, I can't make any suggestions there. Here is something you can start with, I guess.