Spring mvc 弹簧靴;使用XML模板的Thymeleaf
我有一个带有控制器的Spring启动应用程序,它返回ModelAndView和Thymeleaf来呈现模板,模板位于/src/main/resources/templates/*.html中 这很好,但是如何配置Spring和/或Thymeleaf来查找xml文件而不是htmlSpring mvc 弹簧靴;使用XML模板的Thymeleaf,spring-mvc,configuration,spring-boot,thymeleaf,Spring Mvc,Configuration,Spring Boot,Thymeleaf,我有一个带有控制器的Spring启动应用程序,它返回ModelAndView和Thymeleaf来呈现模板,模板位于/src/main/resources/templates/*.html中 这很好,但是如何配置Spring和/或Thymeleaf来查找xml文件而不是html 如果有帮助的话,我将使用Gradle和org.springframework.boot:springbootstarterweb依赖项来进行设置。我目前正在使用一个带有main方法的类运行服务器。在尝试viewResol
如果有帮助的话,我将使用Gradle和org.springframework.boot:springbootstarterweb依赖项来进行设置。我目前正在使用一个带有main方法的类运行服务器。在尝试viewResolver的各种bean定义和相关内容并失败后,我终于通过对application.yaml文件的更改实现了这一点:
spring:
thymeleaf:
suffix: .xml
content-type: text/xml
对于稍后阅读此内容的读者,您可以对application.properties文件执行类似操作(使用点符号代替yaml缩进)。这也适用于:
@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;
}
}
以及使用方法
@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;
}
}
@RestController
@请求映射(“/v2/”)
公共类菜单2控制器{
@自动连线
SpringTemplateEngine;SpringTemplateEngine;
@GetMapping(value=“test”,products={MediaType.APPLICATION\uxml\uvalue})
@应答器
公共字符串测试(){
Map pinfo=newhashmap();
上下文=新上下文();
setVariable(“pinfo”,pinfo);
pinfo.put(“姓氏”、“约旦”);
pinfo.put(“名字”、“迈克尔”);
pinfo.put(“国家”、“美国”);
String content=springTemplateEngine.process(“人员详细信息”,上下文);
返回内容;
}
}
不要忘记资源/模板文件夹中的模板
<?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>
content-type位于
spring.thymeleaf.servlet.content-type下