EnableWebMvc throws ServletException: Could not resolve view with name

23.7k views Asked by At

Playing around with Spring Boot + MVC with static HTML pages, while noticed this thing:

Firstly, what I have:

Index controller:

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index.html";
    }

    @RequestMapping("/{path:[^\\.]+}/**")
    public String forward() {
        return "forward:/";
    }
}

The Html file is:...\src\main\resources\static\index.html

So when my main application class is:

@SpringBootApplication
public class MyApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Everything works well and in default path: localhost:8080\ I get index.html page content

But if I annotate Application class with @EnableWebMvc

@SpringBootApplication
@EnableWebMvc
public class MyApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

I get exception: javax.servlet.ServletException: Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet' But according to this spring doc it is a valid configuration.

Maybe someone can explain me why? Do I understand something wrong?

3

There are 3 answers

0
Ruslan Stelmachenko On BEST ANSWER

According to spring-boot's docs

The auto-configuration adds the following features on top of Spring’s defaults:

  • Static index.html support.

...

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

So by adding @EnableWebMvc you just disable what spring-boot autoconfiguring for you. Namely static index.html support.

2
cralfaro On

According to Spring Boot MVC structure, you should locate your html file in the templates folder. Then will be visible for Spring Boot

src\main\resources\templates\index.html
0
Vivien SA'A On

Actually I think when you choose to use spring boot you should use the default config of spring Boot. It means you just have to edit the file application.properties. Now if you use spring mvc, you have to provide your own servlet. So I think mixing up the to is not a good idea. Either you use spring Boot wiht no much config to do or you use spring mvc and you make all the necessary config.