Spring Boot:在没有控制器的情况下使用 thymeleaf 处理 html 文件

Posted

技术标签:

【中文标题】Spring Boot:在没有控制器的情况下使用 thymeleaf 处理 html 文件【英文标题】:Spring Boot: process a html file with thymeleaf without controller 【发布时间】:2018-09-03 18:49:31 【问题描述】:

我想用我的 Spring Boot 应用程序提供国际化的 html 页面,我正在使用 Thymeleaf 和 messages_XX.properties 用于 i18n。我更喜欢以http://localhost:8080/some/path/test.html 的身份访问这些并将它们放入例如/src/main/resources/html 但我无法将 Spring Boot 配置为默认使用 thymeleaf 处理页面。

作为临时解决方法,我有一个控制器

@RequestMapping(value="**/*.html")
public String serve(HttpServletRequest req) 
    String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);
    res = res.substring(1);
    return res;

现在这对我有用:http://localhost:8080/some/path/file.html 处理和服务src/templates/some/path/file.html,但我可以在某个地方配置 src/resources/html 将由 thymeleaf 处理然后服务吗?

到目前为止我已经尝试过

spring.thymeleaf.prefix=classpath:/html/

application.properties,但它似乎对我不起作用。

环境: spring-boot-starter-2.0.0.RELEASE, spring-webmvc-5.0.4.RELEASE, thymeleaf-spring5-3.0.9.RELEASE

【问题讨论】:

【参考方案1】:

由于您要在以下位置剪切 .html:

String res = req.getRequestURI().substring(0, req.getRequestURI().length() - 5);

你应该设置

spring.thymeleaf.suffix=.html

或者使用配置:

@Bean
public SpringResourceTemplateResolver templateResolver()
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("classpath:/html/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCacheable(true);
    return templateResolver;

【讨论】:

我不介意剪切 .html 部分。我一开始就不想拥有这个控制器。无论如何,看来我将不得不忍受它。

以上是关于Spring Boot:在没有控制器的情况下使用 thymeleaf 处理 html 文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有spring-boot的情况下使用eureka+feign?

在没有 Spring Boot 应用程序的情况下使用 Spring Data JPA

在没有父POM的情况下使用Spring Boot

如何在没有spring boot的情况下使用spring批处理的java配置?

如何在没有spring boot actuator的情况下在spring cloud中使用zuul?

Spring Boot RestController 在没有 SpringBootApplication 的情况下如何工作?