使用 Restlet 2.1.0 Java SE 版本进行原型设计时,我在将 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());
}
在上面的代码中,它将资源视为relative,因此将请求的资源从/hello
到完整的网址。我在这里遗漏了一些明显的东西,但我完全被难住了。
最后通过打开日志记录找到了解决方案(FINE)。我看到了这条日志消息:
默认情况下,应用程序应附加到父组件
为了让应用程序的出站根正确处理呼叫。
我不完全理解它的意思(也许我必须从头到尾阅读文档?)。将应用程序附加到虚拟主机解决了问题:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)