Reputation: 103
I am working with Spring MVC and trying to understand how the controller/view part works, but I am getting a 404 error on '/' and any other route I try.
I tried adding @EnableWebMVC
to my main class, but that gives me a 500 error Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'
and an exception, listed below.
My controller:
public class MyController {
@RequestMapping("/")
public String index(Model model) {
return "index";
}
}
I have both /src/main/resources/static/index.html
/.../resources/templates/index.html
, since I'm still new to Spring/Thymeleaf and I'm not sure on which should work
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'
Upvotes: 1
Views: 86
Reputation: 386
You do not need the /src/main/resources/static/index.html
file because that would only be a static page for your application.
In order to have a dynamically generated page as a result of a controller invocation you need a template which should reside in /src/main/resources/templates
.
Additionally you need a view resolution mechanism for Spring MVC to work properly because Spring must be able to find out what to do if you return the view name "index" in your controller method. The framework must "know" somehow that this should trigger rendering of the template src/main/resources/templates/index.html
using an appropriate template engine, e.g. Thymeleaf. See here for details: https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web.html#mvc-viewresolver
Since you want to use Thymeleaf please refer to this tutorial for instructions how to configure it as the template engine for Spring MVC: http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html
Tipp: If you are using Spring Boot this can all be achieved using auto-configuration if you simply add those two dependencies to your application:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Upvotes: 1