简体   繁体   English

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

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

Im trying to migrate from XML to full java class based config in Spring MVC 4 . 我试图在Spring MVC 4中从XML迁移到完全基于 java 类的配置。 What I did so far is the creation of a simple WebAppInitializer class and a WebConfig class. 到目前为止我所做的是创建一个简单的WebAppInitializer类和一个WebConfig类。

But, I can't find a way to config my welcome page, Here's an excerpt from my old Web.xml : 但是,我找不到配置我的欢迎页面的方法,这里是我旧的Web.xml的摘录:

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

Any help would be appreciated. 任何帮助,将不胜感激。

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

You can do this by overriding the addViewControllers method of WebMvcConfigurerAdapter class. 您可以通过覆盖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");
    }
}

See my answer for more information. 请参阅我的回答以获取更多信息

Using this configuration you can set any filename as a welcome/home page. 使用此配置,您可以将任何文件名设置为欢迎/主页。

In the root controller,you can redirect the path to your path which you want to show as a welcomefile, 在根控制器中,您可以将路径重定向到要显示为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