自动重定向根路径到 Spring Boot 上下文路径

Rah*_*wal 9 spring spring-boot

我正在使用 application.properties 文件中指定的 Spring Boot Context Path,并且效果很好

server.port=5000
server.context-path=/services
Run Code Online (Sandbox Code Playgroud)

Spring Boot 2.0 及以上

server.port=5000
server.servlet.context-path=/services
Run Code Online (Sandbox Code Playgroud)

但是我们如何才能实现 root 的默认重定向,即“/”到“/services”

http://localhost:5000/services - 效果很好!

但我希望http://localhost:5000/自动重定向到 -> http://localhost:5000/services以便最终用户应该能够访问域的根目录并自动重定向到上下文路径

当前访问 root 会抛出 404(这对默认配置有意义)

如何实现root ie“/”到上下文路径的自动重定向?

小智 6

我想我可以提供一个解决方案。请参考以下代码。

@Configuration
public class RootServletConfig {

    @Bean
    public TomcatServletWebServerFactory servletWebServerFactory() {
        return new TomcatServletWebServerFactory() {

            @Override
            protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
                super.prepareContext(host, initializers);
                StandardContext child = new StandardContext();
                child.addLifecycleListener(new Tomcat.FixContextListener());
                child.setPath("");
                ServletContainerInitializer initializer = getServletContextInitializer(getContextPath());
                child.addServletContainerInitializer(initializer, Collections.emptySet());
                child.setCrossContext(true);
                host.addChild(child);
            }
        };
    }

    private ServletContainerInitializer getServletContextInitializer(String contextPath) {
        return (c, context) -> {
            Servlet servlet = new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    resp.sendRedirect(contextPath);
                }
            };
            context.addServlet("root", servlet).addMapping("/*");
        };
    }
}
Run Code Online (Sandbox Code Playgroud)