EnableWebMvc抛出ServletException:无法解析具有名称的视图

Bub*_*lik 3 java spring-mvc static-html spring-boot

使用静态HTML页面玩Spring Boot + MVC,同时注意到这件事:

首先,我有:

指数控制器:

@Controller
public class IndexController {

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

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

Html文件是:...\src\main\resources\static\index.html

所以当我的主应用程序类是:

@SpringBootApplication
public class MyApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

一切运作良好,默认路径:localhost:8080\我得到index.html页面内容

但是,如果我使用注释Application类 @EnableWebMvc

@SpringBootApplication
@EnableWebMvc
public class MyApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到例外:javax.servlet.ServletException: Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet' 但根据这个春季文档,它是一个有效的配置.

也许有人可以解释我为什么?我理解错了吗?

Rus*_*nko 11

根据spring-boot的文档

自动配置在Spring的默认值之上添加了以下功能:

  • 静态index.html支持.

...

如果你想保留Spring Boot MVC功能,并且你只想添加额外的MVC配置(拦截器,格式化程序,视图控制器等),你可以添加自己的@Configuration类类型 WebMvcConfigurerAdapter,但没有 @EnableWebMvc.如果您希望提供自定义实例RequestMappingHandlerMapping, RequestMappingHandlerAdapter或者ExceptionHandlerExceptionResolver您可以声明WebMvcRegistrationsAdapter提供此类组件的实例.

所以通过添加@EnableWebMvc你只需禁用spring-boot自动配置为你.即静态index.html支持.