EnableWebMvc抛出ServletException:无法解析具有名称的视图 [英] EnableWebMvc throws ServletException: Could not resolve view with name
问题描述
使用静态HTML页面玩Spring Boot + MVC,同时注意到这一点:
Playing around with Spring Boot + MVC with static HTML pages, while noticed this thing:
首先,我有:
索引控制器:
@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
所以当我的主应用程序类是:
So when my main application class is:
@SpringBootApplication
public class MyApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
一切正常并且在默认路径中: localhost:8080 \
我得到 index.html
页面内容
Everything works well and in default path: localhost:8080\
I get index.html
page content
但是,如果我使用 @EnableWebMvc
@SpringBootApplication
@EnableWebMvc
public class MyApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
我得到例外: javax .servlet.ServletException:无法解析名为'dispatcherServlet'的servlet中名为'index.html'的视图
但是根据今年春季文档它是一个有效的配置。
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?
推荐答案
自动配置在Spring的默认值之外添加以下功能:
The auto-configuration adds the following features on top of Spring’s defaults:
- 静态
index.html
支持。
- Static
index.html
support.
...
如果你想保留Spring Boot MVC功能,你只想添加
额外的MVC配置(拦截器,格式化程序,查看
控制器等),你可以添加你的拥有 @Configuration
类型
WebMvcConfigurerAdapter
,但没有 @EnableWebMvc
。如果你希望
提供 RequestMappingHandlerMapping
的自定义实例,
RequestMappingHandlerAdapter
或 ExceptionHandlerExceptionResolver
你
可以声明一个 WebMvcRegistrationsAdapter
实例,提供这样的
组件。
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.
因此,通过添加 @EnableWebMvc
,您只需为您禁用spring-boot自动配置。即静态 index.html
支持。
So by adding @EnableWebMvc
you just disable what spring-boot autoconfiguring for you. Namely static index.html
support.
这篇关于EnableWebMvc抛出ServletException:无法解析具有名称的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!