Issue
I am using thymeleaf in spring boot, and have several views. I don't want to keep all the views in the same folder which is src/main/resources/templates by default.
Is it possible to move some of the view in src/main/resources/templates/folder1, and I will pass "folder1/viewname" to access that page?
When I tried http://localhost:8080/folder1/layout1 it didn't found my html in src/main/resources/templates/folder1/, but when I move the html in templates main folder src/main/resources/templates/, http://localhost:8080/layout1 worked fine.
My controller class looks like:
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
So, I thought if I pass layout1, it will look int the templates, and if I say "a/layout1", it will look in /layout folder
Thanks, Manish
Solution
Basically, your request mapping and the name of your view are decoupled, you just need to pay attention to the syntax.
For instance, with
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "layout1";
}
a request to http://localhost:8080/foobar
will render the template located in src/main/resources/templates/layout1.html
.
It also works if you put your templates on a subfolder, as long as you provide the correct path to the view:
@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
return "a/layout1";
}
A request to http://localhost:8080/foobar
will render the template located in src/main/resources/templates/a/layout1.html
.
You can also parameterized the url endpoint with @PathVariable:
@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;
}
Now a request to http://localhost:8080/foobar/layout1
will render the template in src/main/resources/templates/a/layout1.html
and a request to http://localhost:8080/foobar/layout2
will render what's in src/main/resources/templates/a/layout2.html
But beware the forward slash acts as a separator in URLs, so with your controller:
@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
return pagename;
}
My guess is when you hit http://localhost:8080/a/layout1
pagename receives "a" and "layout1" is not caught. So the controller probably tries to render the contents of src/main/resources/templates/a.html
The Spring MVC reference extensively describes how to map requests, you should read it carefully.
Answered By - Marc Tarin
Answer Checked By - Mildred Charles (JavaFixing Admin)