更改部署为战争的spring-boot应用程序的默认欢迎页面

pVi*_*aca 18 spring tomcat7 spring-boot

我试图找到一种方法来更改一个弹簧启动应用程序的默认欢迎页面,该应用程序在生产中被部署为战争,但是如果没有web.xml文件,我找不到办法.

根据文档,我们可以使用EmbeddedServletContainerFactory和以下代码来完成它:

@Bean
public EmbeddedServletContainerFactory servletContainer() {

    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();

    TomcatContextCustomizer contextCustomizer = new TomcatContextCustomizer() {
        @Override
        public void customize(Context context) {
            context.addWelcomeFile("/<new welcome file>");
        }
    };
    factory.addContextCustomizers(contextCustomizer);

    return factory;
}
Run Code Online (Sandbox Code Playgroud)

虽然,因为我们正在创建一个war文件并将其部署到tomcat而不使用Embedded Tomcat,但这并没有做任何事情.

任何的想法?如果我们真的需要添加一个web.xml文件,我们怎么做呢仍然使用spring boot?我们是否应该将Application bean(使用main方法)指定为DispatcherServlet的应用程序上下文?文档不是很清楚.

较旧的Servlet容器不支持Servlet 3.0中使用的ServletContextInitializer引导过程.您仍然可以在这些容器中使用Spring和Spring Boot,但是您需要在应用程序中添加web.xml并将其配置为通过DispatcherServlet加载ApplicationContext.

提前致谢!

佩德罗

Edd*_*e B 25

做起来并不难...你只需要转发默认映射......

@Configuration
public class DefaultView extends WebMvcConfigurerAdapter{

    @Override
    public void addViewControllers( ViewControllerRegistry registry ) {
        registry.addViewController( "/" ).setViewName( "forward:/yourpage.html" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
        super.addViewControllers( registry );
    }
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*aly 7

按照迈克尔的教程,我能够只映射/到我的index.gsp文件.

@Controller
class Routes {

    @RequestMapping({
        "/",
        "/bikes",
        "/milages",
        "/gallery",
        "/tracks",
        "/tracks/{id:\\w+}",
        "/location",
        "/about"
    })
    public String index() {
        return "forward:/index.gsp";
    }
}
Run Code Online (Sandbox Code Playgroud)


Yos*_*ssi 7

好吧,自上次回答以来已经过去了几年 - 代码也在发展。

这不适用于 Spring 5 / Java 8+,您应该实现该接口并覆盖默认方法。

import org.springframework.core.Ordered;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class DefaultViewConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/homepage.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}
Run Code Online (Sandbox Code Playgroud)