编程语言
首页 > 编程语言> > java-Restlet-使用路由器附加资源类时遇到麻烦

java-Restlet-使用路由器附加资源类时遇到麻烦

作者:互联网

使用Java SE版本的Restlet 2.1.0进行原型制作时,我无法将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();
}

标签:restlet,rest,java
来源: https://codeday.me/bug/20191031/1977796.html