RESTLET GAE ECLIPSE initializate method

旧城冷巷雨未停 提交于 2019-12-13 02:35:53

问题


I'm developing an application with Restlet, GAE and Eclipse. Oks, I got this:

public class MainRestletApplication extends Application {

public MainRestletApplication()
{
//init code?
} 


@Override
public Restlet createInboundRoot() {
    Router router = new Router(getContext());

    router.attach("/v1/mainstatus",MainStatus.class);
    router.attach("/v1/game/{id}/result",GameResult.class);

    return router;
}

}

and this:

<servlet>
    <servlet-name>RestletServlet</servlet-name>
    <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
        <param-name>org.restlet.application</param-name>
        <param-value>com.example.MainRestletApplication
        </param-value>
    </init-param>
</servlet>

<!-- Catch all requests -->
<servlet-mapping>
    <servlet-name>RestletServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Well, where can I put a method to init the Web Service, ergo, some code to init some data only when the app starts (one time), not when the first call coming.

Thanks


回答1:


wether you use Restlet or not, AppEngine or not, you can setup a context listener in any servlet environment in your web.xml like this :

<listener>
    <listener-class>
        example.ServletContextExample
    </listener-class>
</listener>

And implement this ;

public class ServletContextExample implements ServletContextListener{
    ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        System.out.println("Context Created");
        context = contextEvent.getServletContext();
        // set variable to servlet context
        context.setAttribute("TEST", "TEST_VALUE");
    }
    public void contextDestroyed(ServletContextEvent contextEvent) {
        context = contextEvent.getServletContext();
        System.out.println("Context Destroyed");
    }
}

When your instance on GAE is started, the init code will be executed, before a call is processed; on the other hand, a new instance is most likely started because a call must be processed. chicken and egg story...




回答2:


You can override the start() method of your com.example.MainRestletApplication class for this purpose. Its lifecycle is synchronized with the wrapper RestletServlet.



来源:https://stackoverflow.com/questions/13706084/restlet-gae-eclipse-initializate-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!