krm*_*007 8 spring spring-mvc thymeleaf spring-boot
我在春季靴子里使用百里香,并有几个看法.我不希望将所有视图保留在默认情况下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;
}
Run Code Online (Sandbox Code Playgroud)
所以,我想如果我通过layout1,它将看起来模板,如果我说"a/layout1",它将在/ layout文件夹中查找
谢谢,Manish
Mar*_*rin 12
基本上,您的请求映射和视图名称是分离的,您只需要注意语法.
例如,有
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "layout1";
}
Run Code Online (Sandbox Code Playgroud)
http://localhost:8080/foobar
要呈现模板的请求src/main/resources/templates/layout1.html
.
如果您将模板放在子文件夹上,只要您提供了正确的视图路径,它也可以工作:
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "a/layout1";
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
现在请求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中的分隔符,因此对于您的控制器:
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
Run Code Online (Sandbox Code Playgroud)
我的猜测是当你点击http://localhost:8080/a/layout1
pagename收到"a"并且没有捕获"layout1".所以控制器可能会尝试渲染内容src/main/resources/templates/a.html
在Spring MVC的参考广泛介绍了如何请求映射,你应该仔细阅读.
归档时间: |
|
查看次数: |
6515 次 |
最近记录: |