使用Restlet发出绑定上下文路由

时间:2015-01-25 09:45:54

标签: restlet restlet-2.0

我在概念验证中使用了restlet,如下所示:

    final Component component = new Component();
    component.getServers().add(Protocol.HTTP, 8182);
    final Router router = new Router(component.getContext().createChildContext());
    router.attachDefault(HttpListener.class);
    component.start();

这应该给我一个http://localhost:8182/*的网址路径。但是,我尝试从此URL获取时只收到404错误:

http://localhost:8182/      -> 404
http://localhost:8182/xyz   -> 404

Restlet没有将任何请求路由到我的HttpListener类。

我的HttpListener类:

public class HttpListener extends ServerResource {

    public static void main(String[] args) throws Exception {
        final Component component = new Component();
        component.getServers().add(Protocol.HTTP, 8182);
        final Router router = new Router(component.getContext().createChildContext());
        router.attachDefault(HttpListener.class);
        component.start();
    }

    @Get()
    public Representation getDBName() {
        String body = "hello, world";
        Representation representation = new StringRepresentation(body, MediaType.APPLICATION_JSON);
        representation.setCharacterSet(CharacterSet.UTF_8);
        return representation;
    }
}

1 个答案:

答案 0 :(得分:1)

我必须按照以下方式附加路线:

public static void main(String[] args) throws Exception {

    final Router router = new Router();
    router.attachDefault(HttpListener.class);

    Application myApp = new Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
            router.setContext(getContext());
            return router;
        };
    };
    Component component = new Component();
    component.getDefaultHost().attach("/", myApp);

    new Server(Protocol.HTTP, 8182, component).start();
}

感谢https://stackoverflow.com/a/13165900/1033422获得此答案。