我在 Spring Boot 中使用 thymeleaf,并且有几个 View 。我不想将所有 View 保留在同一个文件夹中,默认情况下是 src/main/resources/templates。
是否可以移动 src/main/resources/templates/folder1 中的某些 View ,然后我将传递“folder1/viewname”来访问该页面?
当我尝试http://localhost:8080/folder1/layout1时它没有在 src/main/resources/templates/folder1/中找到我的 html,但是当我将 html 移动到模板主文件夹 src/main/resources/templates/中时,http://localhost:8080/layout1工作得很好。
我的 Controller 类如下所示:
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
所以,我想如果我传递layout1,它会在模板中查找,如果我说“a/layout1”,它会在/layout文件夹中查找
谢谢, 曼尼什
最佳答案
基本上,您的请求映射和 View 名称是解耦的,您只需要注意语法即可。
例如,与
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "layout1";
}
请求http://localhost:8080/foobar
将渲染位于 src/main/resources/templates/layout1.html
的模板.
如果您将模板放在子文件夹中,只要您提供正确的 View 路径,它也可以工作:
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "a/layout1";
}
请求http://localhost:8080/foobar
将渲染位于 src/main/resources/templates/a/layout1.html
的模板.
您还可以使用 @PathVariable 参数化 url 端点:
@RequestMapping(value = "/foobar/{layout}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable(value = "layout") String layout) { // I prefer binding to the variable name explicitely
return "a/" + layout;
}
现在请求http://localhost:8080/foobar/layout1
将在 src/main/resources/templates/a/layout1.html
中渲染模板并向 http://localhost:8080/foobar/layout2
提出请求将渲染 src/main/resources/templates/a/layout2.html
中的内容
但请注意,正斜杠在 URL 中充当分隔符,因此对于您的 Controller :
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
我的猜测是当你点击http://localhost:8080/a/layout1
时pagename 收到“a”并且“layout1”未被捕获。因此 Controller 可能会尝试渲染 src/main/resources/templates/a.html
的内容
Spring MVC reference详细描述了如何映射请求,您应该仔细阅读。
关于spring - thymeleaf spring boot templates 子文件夹中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577778/