4

我有一个 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 从 restlet Resource 访问 ServletContext来获取它:

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

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

4

2 回答 2

2

似乎有逻辑。

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

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

于 2011-11-28T15:26:58.983 回答
1

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

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

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

于 2012-02-15T15:44:06.100 回答