java - ReSTLet - 使用路由器附加资源类时遇到问题

标签 java rest restlet

使用 ReSTLet 2.1.0 Java SE 版本进行原型(prototype)设计时,我无法将 ServerResource 类映射到 URL。我已经使用 Router.attach 方法尝试了很多变体,但没有任何效果。

我当前的代码如下所示:

/**
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    final Router router = new Router();
    router.attach("/hello", FirstServerResource.class);
    router.attach("/json", Json.class);

    Application myApp = new Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
            router.setContext(getContext());
            return router;
        };
    };

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

当我浏览到 http://localhost:8182/hello 时,它没有正确进行模板匹配。通过源代码调试,我发现匹配逻辑将请求的资源视为 http://localhost:8182/hello 而不是 /hello。发生这种情况的 ReSTLet 代码在这里:

// HttpInboundRequest.java
// Set the resource reference
if (resourceUri != null) {
    setResourceRef(new Reference(getHostRef(), resourceUri));

    if (getResourceRef().isRelative()) {
        // Take care of the "/" between the host part and the segments.
        if (!resourceUri.startsWith("/")) {
            setResourceRef(new Reference(getHostRef().toString() + "/"
                    + resourceUri));
        } else {
            setResourceRef(new Reference(getHostRef().toString()
                    + resourceUri));
        }
    }

    setOriginalRef(getResourceRef().getTargetRef());
}

在上面的代码中,它将资源视为相对,因此将请求的资源从/hello 更改为完整的url。我在这里遗漏了一些明显的东西,但我完全被难住了。

最佳答案

最终通过打开日志记录(FINE)找到了解决方案。我看到了这条日志消息:

By default, an application should be attached to a parent component in order to let application's outbound root handle calls properly.

我不完全理解它的意思(也许我必须从头到尾阅读文档?)。将应用程序附加到 VirtualHost 解决了问题:

public static void main(String[] args) throws Exception {   
    final Router router = new Router();
    router.attach("/hello", FirstServerResource.class);
    router.attach("/json", Json.class);
    router.attachDefault(Default.class);

    Application myApp = new Application() {
        @Override
        public org.restlet.Restlet createInboundRoot() {
            router.setContext(getContext());                
            return router;
        };
    };


    Component component = new Component();
    component.getDefaultHost().attach("/test", myApp);

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

关于java - ReSTLet - 使用路由器附加资源类时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13147772/

相关文章:

javascript - 片段 uri 未在浏览器上执行

java - 关于 JSP Forward 的问题

java - org.aspectj.lang.NoAspectBoundException - 未找到方法 <init>()V

java - 如何在 Android Studio 中添加 commons-math 库

java - 如何按特定顺序批量插入?

php - RESTful API 身份验证流程

web-services - REST 和 POX 的区别

rest - 对不支持的页面格式(例如 xml)的正确 HTTP 响应?

google-app-engine - AppEngine 的 RESTFul 服务框架

java - 如何为 Google AppEngine 配置 ReSTLe