【发布时间】:2016-06-22 11:28:30
【问题描述】:
我想在 Rhino 中实现类似以下的功能(在 JavaScript 中)。
myService.http('http://localhost:9000')
.path('foo/bar')
.get();
然后让最终的 get() 返回实际响应。它以 Jersey 的 Java 网络请求构建器为蓝本。
我目前的Java代码是:
class MyHttpRequestBuilder {
private final String baseUrl;
private final StringBuilder path = new StringBuilder();
private final Map<String, String> queryParams = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
public MyHttpRequestBuilder(String baseUrl) {
this.baseUrl = baseUrl;
}
public MyHttpRequestBuilder path(String path) {
this.path.append(path);
return this;
}
public MyHttpRequestBuilder header(String headerKey, String headerValue) {
headers.put(headerKey, headerValue);
return this;
}
public MyHttpRequestBuilder queryParam(String queryKey, String queryValue) {
queryParams.put(queryKey, queryValue);
return this;
}
public String get() {
return "Testing - Accessed " + baseUrl + " with path " + path;
}
}
我已经在这样的服务类中注册了它:
public class MyService {
public MyHttpRequestBuilder http(String baseUrl) {
return new MyHttpRequestBuilder(baseUrl);
}
}
然后,根据各种示例,我将其添加到 Rhino 上下文中的 Scriptable 容器中。
如果我只是直接调用简单地返回字符串或其他对象的函数,它很好。
不幸的是,生成器方法是“return this;” (这将允许在 JS 端更流畅的代码)不想玩球。 Rhino甚至可以做到这一点吗?
我正在使用 Java 8 和 Rhino 1.7.7.1。
【问题讨论】:
-
到底是什么问题? (另外,为什么是 Rhino 而不是 Nashorn?)
标签: javascript java builder rhino