简体   繁体   中英

Context of RESTlet Application is null using internal RESTlet Server

I have a Restlet (2.0.10) application, I start with the following code:

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);
    }

}

Now I require the applications root (ie /myApp) inside the application and I try to get this according to 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();

This works perfectly fine while deploying my application to a Tomcat Server, but as soon as I start the server using a Component as shown above, my Context is always null. Can someone please tell me how to get a properly initialized context using restlets internal server capabilities?

Seems logic.

You want a servlet context but you are not running in a servlet container, so the servlet context is NULL.

When doing component.start() you are using the Restlet connectors to server HTTP/HTTPS requests, not a servlet container like Tomcat.

You would need to pick up the context from the Component Class:

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

That would just give you the Restlet context, but Servlet Context still won't be available since this is a standalone Java application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM