其他分享
首页 > 其他分享> > spring – 如何在WebApplicationInitializer.onStartup()中指定welcome-file-list

spring – 如何在WebApplicationInitializer.onStartup()中指定welcome-file-list

作者:互联网

目前我有一个Web应用程序,我们使用web.xml来配置应用程序. web.xml有welcome-file-list.

<web-app>  
   ...
   <welcome-file-list>  
     <welcome-file>home.html</welcome-file>  
   </welcome-file-list>  
</web-app>  

我们计划使用spring框架并使用java类进行应用程序配置.

class MyApplication extends WebApplicationInitializer {
    public void onStartUp(ServletContext context){
        ...
    }
}

如何在此java类中指定welcome-file-list?

解决方法:

在使用纯Java Based Configuration开发Spring MVC应用程序时,我们可以通过使我们的应用程序配置类扩展WebMvcConfigurerAdapter类并覆盖addViewControllers方法来设置主页,我们可以在其中设置默认主页,如下所述.

@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视图,可以作为主页.无需创建自定义控制器逻辑即可返回主页视图.

JavaDoc for addViewControllers方法说 –

Configure simple automated controllers pre-configured with the
response status code and/or a view to render the response body. This
is useful in cases where there is no need for custom controller logic
— e.g. render a home page, perform simple site URL redirects, return a 404 status with HTML content, a 204 with no content, and more.

第二种方法 – 对于静态HTML文件主页,我们可以在配置类中使用下面的代码.它会将index.html作为主页返回 –

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
    }

第三种方式 – 下面的请求映射“/”也将返回主视图,该视图可以作为应用程序的主页.但建议采用上述方法.

@Controller
public class UserController {
    @RequestMapping(value = { "/" })
    public String homePage() {
        return "home";
    }
}

标签:programmatic-config,spring,web-xml,welcome-file
来源: https://codeday.me/bug/20191005/1857274.html