【问题标题】:EnableWebMvc throws ServletException: Could not resolve view with nameEnableWebMvc 抛出 ServletException:无法解析带有名称的视图
【发布时间】:2017-05-23 10:48:28
【问题描述】:

在静态 HTML 页面中使用 Spring Boot + MVC,同时注意到这个东西:

首先,我有什么:

索引控制器:

@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\我得到index.html页面内容

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

@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' 但根据this spring doc,这是一个有效的配置。

也许有人可以解释一下为什么?我是不是理解错了?

【问题讨论】:

    标签: java spring-mvc spring-boot static-html


    【解决方案1】:

    根据 Spring Boot MVC 结构,您应该在 templates 文件夹中找到您的 html 文件。然后将在 Spring Boot 中可见

    src\main\resources\templates\index.html
    

    【讨论】:

    • By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext... 而动态内容需要templates
    • 但是你可以使用thymeleaf,它基本上是一个带有th属性的html,不需要动态可以是完全静态的
    【解决方案2】:

    其实我觉得当你选择使用spring boot时你应该使用spring boot的默认配置。这意味着您只需编辑文件application.properties。现在如果你使用spring mvc,你必须提供你自己的servlet。所以我认为混合 to 不是一个好主意。要么你使用 spring Boot 而不需要做太多配置,要么你使用 spring mvc 并进行所有必要的配置。

    【讨论】:

      【解决方案3】:

      根据spring-boot's docs

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

      • 静态index.html 支持。

      ...

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

      因此,通过添加 @EnableWebMvc,您只需禁用 spring-boot 自动配置。即静态index.html支持。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2019-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        相关资源
        最近更新 更多