我在 Spring 季靴子里使用百里香,并有几个看法 . 我不希望将所有视图保留在默认情况下src / main / resources / templates的同一文件夹中 .
是否可以在src / main / resources / templates / folder1中移动一些视图,我将传递“folder1 / viewname”来访问该页面?
当我尝试http://localhost:8080/folder1/layout1它没有在src / main / resources / templates / folder1 /中找到我的html,但是当我在模板主文件夹src / main / resources / templates /中移动html时,http://localhost:8080/layout1工作正常 .
我的控制器类看起来像:
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
所以,我想如果我通过layout1,它将看起来模板,如果我说“a / layout1”,它将在/ layout文件夹中查找
谢谢,Manish
1 回答
基本上,您的请求映射和视图名称是分离的,您只需要注意语法 .
例如,用
对
http://localhost:8080/layout1
的请求将呈现位于src/main/resources/templates/pagename.html
的模板 .如果您将模板放在子文件夹上,只要您提供了正确的视图路径,它也可以工作:
对
http://localhost:8080/foobar
的请求将呈现位于src/main/resources/templates/a/layout1.html
的模板 .您还可以使用@PathVariable参数化url endpoints :
现在,对
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中的分隔符,因此对于您的控制器:
我的猜测是当你点击
http://localhost:8080/a/layout1
pagename收到"a"并且没有抓到"layout1" . 所以控制器可能会尝试渲染src/main/resources/templates/a.html
的内容Spring MVC reference广泛地描述了如何映射请求,您应该仔细阅读 .