【问题标题】:Context of RESTlet Application is null using internal RESTlet Server使用内部 RESTlet 服务器的 RESTlet 应用程序的上下文为空
【发布时间】:2011-11-23 09:24:08
【问题描述】:

我有一个 Restlet (2.0.10) 应用程序,我从以下代码开始:

public static void main(final String[] args) {
    try {
        // Create a new Component
        final Component component = new Component();

        // Add a new HTTP server listening on port 8182
        component.getServers().add(Protocol.HTTP, SERVER_PORT);

        // Add a client protocol connector for static files
        component.getClients().add(Protocol.FILE);

        // Attach the sample application.
        component.getDefaultHost().attach("/myApp", new MyApplication(Context.getCurrent()));

        // Start the component.
        component.start();

    } catch (Exception e) {
        LOGGER.error(e);
    }

}

现在我需要应用程序内的应用程序根目录(即 /myApp),我尝试根据 Java accessing ServletContext from within restlet Resource 获取它:

Client serverDispatcher = context.getServerDispatcher();
ServletContext servletContext = (ServletContext)serverDispatcher.getContext().getAttributes()
                    .get("org.restlet.ext.servlet.ServletContext");
String contextPath = servletContext.getContextPath();

这在将我的应用程序部署到 Tomcat 服务器时工作得非常好,但是一旦我使用如上所示的组件启动服务器,我的 Context 始终为空。有人可以告诉我如何使用 restlets 内部服务器功能获得正确初始化的上下文吗?

【问题讨论】:

    标签: java rest restlet restlet-2.0


    【解决方案1】:

    看起来很合乎逻辑。

    您想要一个 servlet 上下文,但您没有在 servlet 容器中运行,因此 servlet 上下文为 NULL。

    在执行 component.start() 时,您使用的是 Restlet 连接器来处理 HTTP/HTTPS 请求,而不是像 Tomcat 这样的 servlet 容器。

    【讨论】:

      【解决方案2】:

      您需要从 Component 类中获取上下文:

      component.getDefaultHost().attach("/myApp", 
           new MyApplication(component.getContext().createChildContext());
      

      这只会为您提供 Restlet 上下文,但 Servlet 上下文仍然不可用,因为这是一个独立的 Java 应用程序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多