如何在WebApplicationInitializer.onStartup()中指定欢迎文件列表 [英] how to specify welcome-file-list in WebApplicationInitializer.onStartup()
问题描述
当前,我有一个Web应用程序,我们在其中使用web.xml来配置该应用程序. web.xml具有欢迎文件列表".
Currently I have a web application where we are using web.xml to configure the application. The web.xml has welcome-file-list.
<web-app>
...
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
我们计划使用spring框架,并使用java类进行应用程序配置.
We are planning to use spring framework and use java class for application configuration.
class MyApplication extends WebApplicationInitializer {
public void onStartUp(ServletContext context){
...
}
}
如何在此Java类中指定welcome-file-list?
How do I specify welcome-file-list in this java class?
推荐答案
在开发基于纯Java的Configuration的Spring MVC应用程序时,我们可以通过扩展应用程序的配置类扩展WebMvcConfigurerAdapter 类并覆盖
While developing Spring MVC application with pure Java Based Configuration, we can set the home page by making our application configuration class extending the WebMvcConfigurerAdapter class and override the addViewControllers method where we can set the default home page as described below.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.myapp.controllers" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
它返回home.jsp
视图,该视图可用作主页.无需创建自定义控制器逻辑即可返回首页视图.
It returns home.jsp
view which can be served as home page. No need to create a custom controller logic to return the home page view.