【问题标题】:Restlet framework: how to bind to localhost only?Restlet框架:如何仅绑定到本地主机?
【发布时间】:2015-11-28 17:37:07
【问题描述】:

我需要构建一个(独立的 Java)基于 restlet 的服务,该服务只侦听 localhost,即不允许来自网络的请求。

我试图做显而易见的事情:

Server srv = new Server(Protocol.HTTPS, "localhost", httpsPort); 
component.getServers().add(srv);

但该服务仍在侦听 0.0.0.0。 :-(

进入代码发现HttpsServerHelper在创建服务时忽略了主机名:

this.server = HttpsServer.create(new InetSocketAddress(getHelped().getPort()), 0);

类似的代码存在于普通 HTTP 的 HttpServerHelper 中,这里更加清晰。

那么我的问题是:

如何将 Restlet 组件/服务配置为仅侦听 localhost?

【问题讨论】:

  • component.getDefaultHost()

标签: java localhost bind restlet restlet-2.3.1


【解决方案1】:

我不知道您在独立的 Restlet 应用程序中使用哪个服务器。您应该使用默认连接器以外的服务器连接器,我建议您使用 Jetty 连接器。

为此,只需将扩展 org.restlet.ext.jetty 的 jar 放入您的类路径中。

在这种情况下,使用以下代码应该符合您的需求:

component.getServers().add(Protocol.HTTP, "localhost", 8182);

这是应用程序启动时的相应跟踪:

2015-09-03 09:47:22.180:INFO::jetty-7.1.6.v20100715
2015-09-03 09:47:22.211:INFO::Started SelectChannelConnector@localhost:8182

此外,这里是 Restlet 文档中有关 Restlet 连接器的链接:http://restlet.com/technical-resources/restlet-framework/guide/2.3/core/base/connectors

希望对你有帮助 蒂埃里

【讨论】:

  • 谢谢,这是罪魁祸首。我使用的是内部 Web 服务器(因为在另一个打包变体中我必须部署到 Weblogic),而内部 Web 服务器显然只是忽略了监听主​​机规范。当我添加 Jetty 时,现有代码无需更改即可立即运行。
  • P.S.如果代码尝试指定主机,可能是内部 Web 服务器应记录警告。花了我 2 天的时间 :-)
  • 不客气!是的,同意你的警告!
【解决方案2】:

更简单的方法是使用虚拟主机。 虚拟主机是处理请求时的第一个路由障碍,尤其是它有助于在域上进行路由。

这里有一个示例代码来说明这一点:

    Component c = new Component();
    c.getServers().add(Protocol.HTTP, 8182);

    VirtualHost host = new VirtualHost();
    host.setHostDomain("localhost");
    c.getHosts().add(host);
    host.attach(new Restlet() {
        @Override
        public void handle(Request request, Response response) {
            response.setEntity("hello, world", MediaType.TEXT_PLAIN);
        }
    });

    c.start();

通常,应用程序附加在组件的默认主机上。这个默认主机什么都不做,除了根据附加应用程序的上下文路径路由请求:

    c.getDefaultHost().attach("/contextPath1", new Test1Application());
    c.getDefaultHost().attach("/contextPath2", new Test2Application());

当您想根据请求路径以外的其他数据过滤调用时,虚拟主机可能是解决方案。

这是一张可能对您有所帮助的图表:

http://restlet.com/technical-resources/restlet-framework/tutorials/2.3#part05

【讨论】:

  • 感谢您的教育帖子,我学到了很多关于虚拟主机的知识。对您的代码的一条评论:新的 VirtualHost() 应该采用 c.getContext(),否则我将在附加步骤中获得 NPE。
猜你喜欢
  • 2016-05-23
  • 1970-01-01
  • 2017-09-07
  • 2021-09-24
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多