springboot+thymeleaf Solution not found for view
- 2021-09-20 20:16:35
- OfStack
springboot+thymeleaf view not found
Situation:
After springboot + thymeleaf is made into jar package, an error is reported, but running locally in eclipse can:
template might not exist or might not be accessible by any of the configured Template Resolvers
yml configuration:
spring:
thymeleaf:
cache: false # Turn off caching at development time , Otherwise, you can't see the real-time page
mode: HTML5 # With non-strict HTML
#enabled: true
encoding: UTF-8
prefix: classpath:/templates/
suffix: .html
servlet:
content-type: text/html
controller Return View:
@RequestMapping("demo")
public String demo(Model model) {
//return "/demo";// This is problematic
return "demo";
}
Explanation:
In fact, the/templates/has been configured in our yml configuration, so if we return the/demo, it will not be found, because the mapping view becomes://demo, so it is best to remove one of the "/" here;
Otherwise, after the jar package is made, it will not be found. This should be used as the specification of the project. Otherwise, when it is officially released later, too many are not easy to modify; If there is a better way, please let me know, thank you.
Some problems encountered by springboot using thymeleaf template
There are 1 problem with springboot+thymeleaf, which can be grouped into the following:
1. Create a custom directory/my under the/templates directory, and create index. html under this directory. How to access index. html in the program
2. How to configure if you do not use the/templates directory as the default path
Question 1
Solution:
In the controller layer method, by setting the ModelAndView name to: my/index, and then returning the ModelAndView, the interface method will jump to index. html
The sample code is as follows:
@RequestMapping(value="getIndex")
public ModelAndView getIndex(ModelAndView model)throws Exception
{
// Access the custom directory /templates/my/index.html Pay attention to the path format
model.setViewName("my/index");
return model;
}
Question 2
Solution:
Set in the application. properties configuration file through the spring. thymeleaf. prefix property, for example, setting the default path/templates/my
The sample code is as follows:
spring.thymeleaf.prefix=classpath:/templates/my
The code used by springboot+thymeleaf is as follows:
https://github.com/ingorewho/springboot-develope/tree/master/springboot-thymeleaf