Spring Boot & Thymeleaf with XML Templates

老子叫甜甜 提交于 2020-01-13 18:57:09

问题


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.


回答1:


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).




回答2:


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>


来源:https://stackoverflow.com/questions/28774903/spring-boot-thymeleaf-with-xml-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!