How to resolve org.thymeleaf.exceptions.TemplateInputException: Error resolving template, template might not exist or might not be accessible by any of the configured Template Resolvers when using spring framework with thymeleaf
Problem
When running a Spring Boot or Spring MVC application with Thymeleaf, you might encounter the following error when visiting a URL:
The error message is:
The core exception is:
Spring framework is complaining that it cannot find the view resolver for the specified URL.
Environment
- Spring Boot 1.x and 2.x
The Codes and Configurations
The project layout is as follows:
The build.gradle
file includes the necessary dependencies:
The HelloController
defines a method to handle HTTP GET requests for the /hello2
URL:
There is also a configuration class to configure Spring MVC view controllers:
However, running the application results in the following exception:
Solution
Step 1: Remove the WebMvcConfigurer Subclass
Since Spring MVC has a default view resolver for Thymeleaf, you do not need to configure the views explicitly. Remove the MvcConfig
class. The directory structure now looks like this:
Step 2: Modify the Controller
Update the HelloController
to include the @ResponseBody
annotation:
The @ResponseBody
annotation indicates that the method returns a plain string and should not be resolved as a view template.
After making these changes, rerun the application. The error should disappear:
It works!
About the View Resolver in Spring MVC
Spring relies on the view resolver to resolve the view name from the controller. Thymeleaf is a Java library that acts as a template engine for XML/XHTML/HTML5. It applies transformations to template files to display data or text produced by your applications.
If you want to use Thymeleaf, simply add the dependency to your project.
All the example code and configuration files can be found in this GitHub project.
Summary
In this post, we explored how to resolve the TemplateInputException
in Spring Boot applications using Thymeleaf. The key steps include removing unnecessary view configurations and using the @ResponseBody
annotation to indicate that a method returns a plain string. By following these steps, you can avoid common pitfalls related to view resolution in Spring MVC.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!