2011-11-23 32 views
4

我有一个的Restlet(2.0.10)应用程序,我开始用下面的代码:语境的Restlet应用的是空使用内部的Restlet服务器

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服务器工作完全正常,但只要我使用组件启动服务器如上图所示,我的背景是始终为空。有人可以告诉我如何使用restlets内部服务器功能获得正确初始化的上下文吗?

回答

2

似乎逻辑。

你想要一个servlet上下文,但是你没有在servlet容器中运行,所以servlet上下文是NULL。

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

1

你需要拿起从Component类上下文:

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

这将只是给你的Restlet范围内,但Servlet上下文仍然无法使用,因为这是一个独立的Java应用程序。