简体   繁体   中英

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 . What I did so far is the creation of a simple WebAppInitializer class and a WebConfig class.

But, I can't find a way to config my welcome page, Here's an excerpt from my old 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.

@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,

@Controller
public class WelcomePageController {

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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