使用 Java 配置为 Spring MVC 4 设置欢迎页面

Set the welcome page for Spring MVC 4 with Java configuration

我正在尝试从 XML 迁移到完全 java class 基于 配置 Spring MVC 4。 到目前为止,我所做的是创建一个简单的 WebAppInitializer class 和一个 WebConfig class。

但是,我找不到配置欢迎页面的方法,这是我以前 Web.xml 的摘录:

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

如有任何帮助,我们将不胜感激。

其实你什么都不用做,spring会自动在src/main/webapp下寻找index.html文件,你只需要创建一个index.html文件,然后把它放在这个根下。

您可以通过覆盖 WebMvcConfigurerAdapter class 的 addViewControllers 方法来实现。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.myapp.controllers" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {

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

查看我的了解更多信息。

使用此配置,您可以将任何文件名设置为 welcome/home 页面。

在根控制器中,您可以将路径重定向到您想要显示为欢迎文件的路径,

@Controller
public class WelcomePageController {

  @RequestMapping("/")
  public String redirectPage() {
    return "redirect:Welcome";
  }


  @RequestMapping("/Welcome")
  public String showHomePage() {
    return "index";
  }
}