您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Boot:将另一个端口上的请求发送到自定义Servlet

Spring Boot:将另一个端口上的请求发送到自定义Servlet

要隔离Connector供单个应用程序使用的,该连接器需要与其自己的连接器关联,Service然后您需要Context将该应用程序的连接器与关联Service

您可以在Spring Boot应用程序中通过提供您自己的TomcatEmbeddedServletContainerFactory子类a@Bean并进行覆盖来进行设置getEmbeddedServletContainer(Tomcat tomcat)。这使您有机会进行所需的配置更改:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            Server server = tomcat.getServer();

            Service service = new StandardService();
            service.setName("other-port-service");
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(8081);
            service.addConnector(connector);
            server.addService(service);

            Engine engine = new StandardEngine();
            service.setContainer(engine);

            Host host = new StandardHost();
            host.setName("other-port-host");
            engine.addChild(host);
            engine.setDefaultHost(host.getName());

            Context context = new StandardContext();
            context.addLifecycleListener(new FixContextListener());
            context.setName("other-port-context");
            context.setPath("");
            host.addChild(context);

            Wrapper wrapper = context.createWrapper();
            wrapper.setServlet(new MyServlet());
            wrapper.setName("other-port-servlet");
            context.addChild(wrapper);
            context.addServletMapping("/", wrapper.getName());

            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

private static class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().println("Hello, world");
    }

}

将此bean添加到您的应用程序后,应该由http:// localhost:8081处理MyServlet并返回包含“ Hello,world”的响应。

Jave 2022/1/1 18:16:09 有387人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶