使用Spring Boot自动查找Thymeleaf模板
如何让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
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
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
来确定视图的名称。但是这也很危险,因为现在任何人都可以访问所有内容(甚至是他们可能看不到的东西)。您基本上就是这样打开应用程序的。