Search code examples
restlet

How to get hold of Component instance


I am running a tomcat server and my web.xml is as follows. I need to get an instance of TaskService from the Component class. I am not explicitly creating a Component. I believe the ServerServlet class is internally creating an implicit Component. My question is how do I get access to the implicit Component instance?

<servlet>
    <servlet-name>ServiceGateway</servlet-name>
    <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
        <param-name>org.restlet.application</param-name>
        <param-value>com.test.ServiceApplication</param-value>
    </init-param>
</servlet>

Solution

  • Yes, you're right! The servlet extension of Restlet creates a component under the hood for you.

    There is no really direct way to get it. That said, you can browse contexts to reach its instance.

    public class TestApplication extends Application {
        @Override
        public Restlet createInboundRoot() {
            // Get restlet context
            Context context = getContext();
    
            // Get servlet context
            ServletContext servletContext = (ServletContext) attrs.get(
                      "org.restlet.ext.servlet.ServletContext");
    
            // Get restlet component
            Component component = (Component) servletContext.getAttribute(
             "org.restlet.ext.servlet.ServerServlet.component.ServerServlet");
    
            (...)
        }
    }
    

    Here is the configuration I used within the file web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"   
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
               http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="myApplication" version="2.5">
        <display-name>My Application</display-name>
    
        <servlet>
            <servlet-name>ServerServlet</servlet-name>
            <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
            <init-param>
                <param-name>org.restlet.application</param-name>
                <param-value>test.RestletApplication</param-value>
            </init-param>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>ServerServlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    </web-app>
    

    Hope it helps you, Thierry