How to set the welcome-file when developing spring

2019-05-27 11:43发布

问题:

I am developing a web application using Spring MVC with pure Java based and no web.xml configuration. I did code the class below to load the beans and set the url pattern. How can I set the the welcome-file?

public class MyAppWebAppIntializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext appCtx = new AnnotationConfigWebApplicationContext();
        appCtx.register(ApplicationContextConfig.class);

        Dynamic dispatcher = servletContext.addServlet(
                "SpringDispatcher", new DispatcherServlet(appCtx));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

回答1:

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");
  }

}

It returns home.jsp view which can serve as a home page. No need to create a custom controller logic to return the home page view.

The JavaDoc for addViewControllers method says -

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.

2nd way - For static HTML file home page we can use the code below in our configuration class -

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

3rd way - The request mapping "/" below will also return home.jsp which can be served as a home page for an app. But the above process is recommended.

@Controller
public class UserController {

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

}