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

2024-01-05

在使用 Spring Boot + MVC 和静态 HTML 页面时,注意到了这一点:

首先,我有什么:

索引控制器:

@Controller
public class IndexController {

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

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

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

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

@SpringBootApplication
public class MyApplication extends WebMvcConfigurerAdapter {

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

一切正常并且在默认路径中:localhost:8080\ I get index.html页面内容

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

@SpringBootApplication
@EnableWebMvc
public class MyApplication extends WebMvcConfigurerAdapter {

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

我得到异常:javax.servlet.ServletException: Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'但根据今年春天的医生 http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/config/annotation/EnableWebMvc.html这是一个有效的配置。

也许有人可以解释我为什么?我理解有问题吗?


根据spring-boot 的文档 https://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration

自动配置在 Spring 默认设置的基础上添加了以下功能:

  • Static index.html支持。

...

如果你想保留 Spring Boot MVC 功能,并且你只想添加 额外的 MVC 配置(拦截器、格式化程序、视图 控制器等)您可以添加自己的@Configuration类型类别WebMvcConfigurerAdapter, but without @EnableWebMvc。如果您愿意 提供自定义实例RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver你 可以声明一个WebMvcRegistrationsAdapter提供此类的实例 成分。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐