使用Spring Boot自动查找Thymeleaf模板

使用Spring Boot自动查找Thymeleaf模板,spring,spring-boot,thymeleaf,Spring,Spring Boot,Thymeleaf,如何让Spring Boot和Thymeleaf在浏览器访问时自动查找和映射要处理的模板文件 src/main/resources/templates/index.xhtml src/main/resources/templates/bar.xhtml src/main/resources/application.properties包含spring.thymeleaf.suffix=.xhtml FooController.java包含@RequestMapping(“/foo”)和返回ba

如何让Spring Boot和Thymeleaf在浏览器访问时自动查找和映射要处理的模板文件

  • src/main/resources/templates/index.xhtml
  • src/main/resources/templates/bar.xhtml
  • src/main/resources/application.properties
    包含
    spring.thymeleaf.suffix=.xhtml
  • FooController.java
    包含
    @RequestMapping(“/foo”)
    和返回
    bar
如果我输入
http://localhost:8080/
在浏览器中,Thymeleaf处理并显示
index.xhtml
页面,无需额外配置。但是
http://localhost:8080/index
http://localhost:8080/index.xhtml
http://localhost:8080/index.html
所有结果均导致未找到
404

我的
索引
视图向
foo
发送
POST
FooController
被激活并返回
bar
;Thymeleaf处理并显示
bar.xhtml
,即使
bar.xhtml
未映射到配置中的任何位置。然而访问
http://localhost:8080/bar
http://localhost:8080/bar.xhtml
http://localhost:8080/bar.html
在浏览器中,所有结果均导致未找到
404

  • 为什么
    得到
    http://localhost:8080/
    处理
    index.xhtml
    模板,但
    获取
    http://localhost:8080/index
    没有
  • Thymleaf如何使用
    作为视图,但我无法访问
    http://localhost:8080/bar
    直接
  • 如何配置Thymeleaf,以便添加
    src/main/resources/templates/example.xhtml
    ,并将其自动处理为可通过
    http://localhost:8080/example
    在浏览器中,没有专门针对
    example.xhtml
    文件的显式配置
如果我必须配置控制器(请参阅my),是否有一种方法至少可以在我的代码之外的某个声明性文件中执行此操作?

如中所述,我可以在实现
WebMVCConfiguer
@Configuration
类中执行类似操作

@覆盖
public void addViewController(最终ViewControllerRegistry注册表){
registry.addViewController(“/bar”);
}
这将允许我自动处理
bar.xhtml
。(我假定存在一些默认配置
registry.addViewController(“/”).setViewName(“index”)
,这就是通过访问根路径来处理我的
index.xhtml
文件的原因

我甚至可以使用以下工具自动选取任何模板:

@覆盖
public void addViewController(最终ViewControllerRegistry注册表){
registry.addViewController(“/**”);
}

不幸的是,这会删除从
/
/index
的映射,也会阻止从
src/main/resources
访问任何静态资源。如果可以,我不确定如何告诉Thymeleaf使用模板,如果不可以,则返回到静态文件。

您需要为每个文件指定一个视图控制器。如果需要另外,您必须自己构建它。理论上,您可以使用
@RequestMapping
为所有内容创建映射,并返回void。这将使用
RequestToViewNameTranslator
来确定视图的名称。但是这也很危险,因为现在任何人都可以访问所有内容(甚至是他们可能看不到的东西)。您基本上就是这样打开应用程序的。