3

I have a Spring Boot application with a controller that returns a ModelAndView and Thymeleaf to render templates, where the templates live in /src/main/resources/templates/*.html

This works fine, but How can I configure Spring and/or Thymeleaf to look for xml files instead of html?

If it helps, I'm using Gradle with the org.springframework.boot:spring-boot-starter-web dependency to set things up. I am currently running the server using a class with a main method.

user605331
  • 3,718
  • 4
  • 33
  • 60

2 Answers2

4

After trying and failing at various bean defs for viewResolver and related things, I finally got this working with a change to my application.yaml file:

spring:
  thymeleaf:
    suffix: .xml
    content-type: text/xml

For those reading this later, you can do similar with your application.properties file (with dot notation in place of the yaml indentation).

user605331
  • 3,718
  • 4
  • 33
  • 60
3

This works too :

@Configuration
public class MyConfig
{
    @Bean
    SpringResourceTemplateResolver xmlTemplateResolver(ApplicationContext appCtx) {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

        templateResolver.setApplicationContext(appCtx);
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".xml");
        templateResolver.setTemplateMode("XML");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);

        return templateResolver;
    }

    @Bean(name="springTemplateEngine")
    SpringTemplateEngine templateEngine(ApplicationContext appCtx) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(xmlTemplateResolver(appCtx));
        return templateEngine;
    }
}

And for the usage

@RestController
@RequestMapping("/v2/")
public class MenuV2Controller {
    @Autowired
    SpringTemplateEngine springTemplateEngine;

    @GetMapping(value ="test",produces = {MediaType.APPLICATION_XML_VALUE})
    @ResponseBody
    public String test(){
        Map<String, String> pinfo = new HashMap<>();
        Context context = new Context();
        context.setVariable("pinfo", pinfo);
        pinfo.put("lastname", "Jordan");
        pinfo.put("firstname", "Michael");
        pinfo.put("country", "USA");

       String content = springTemplateEngine.process("person-details",context);
       return content;

  }
}

Don't forget the template in resources/templates folder

<?xml version="1.0" encoding="UTF-8"?>
<persons >
    <person>
        <fname th:text="${pinfo['lastname']}"></fname>
        <lname th:text="${pinfo['firstname']}"></lname>
        <country th:text="${pinfo['country']}"></country>
    </person>
</persons>
freemanpolys
  • 1,848
  • 20
  • 19