繁体   English   中英

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

[英]Set the welcome page for Spring MVC 4 with Java configuration

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

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

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

任何帮助,将不胜感激。

你不需要做任何事情,spring会自动在src/main/webapp下查找index.html文件,你需要做的就是创建一个index.html文件并把它放在这个root下面。

您可以通过覆盖WebMvcConfigurerAdapter类的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");
    }
}

请参阅我的回答以获取更多信息

使用此配置,您可以将任何文件名设置为欢迎/主页。

在根控制器中,您可以将路径重定向到要显示为welcomefile的路径,

@Controller
public class WelcomePageController {

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM