我正在尝试使用 jQuery/ajax 调用 portlet 的serveResource() 方法。我设法获得了一个在 Pluto 2.0 中工作的简单 JSR-286 portlet,它能够从请求正文中读取 JSON 字符串,从 JSON 创建一个 Java 对象,并将该对象的 toString() 返回给我调用的 JavaScript。然而,当我将同一个 portlet 部署*到 WebSphere Portal 6.1 时,请求正文在到达serveResource() 时为空。
我假设我缺少一些基本的/根本性的东西,所以任何建议将不胜感激。我认为,如果我将 JSON 字符串推送到 URL 参数上,我的示例就可以正常工作,但我现在更愿意避免这种方法,除非我给出了当前方法“不好”的原因。
编辑:*更具体地说,我将相同的 portlet 部署到运行 WSRP Producer 的 WAS7 并通过 WebSphere Portal 6.1 使用该 portlet。
Javascript 片段:
function ajaxPost() {
var url = "<%= testServiceURL %>";
var current = $("input.current").val();
$.ajax(
{
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
data: "{data: " + current + "}",
type: 'POST',
success: testSuccess,
error: testError
}
);
$("div.trace").append("ajax post fired<br />");
}
function testSuccess(data, textStatus, XMLHttpRequest)
{
$("div.trace").append("testSuccess(): " + data + "<br />");
}
Portlet 片段:
public class TestPortlet extends GenericPortlet {
...
@Override
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
String res = "Failed to read body";
boolean bodyRead = true;
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
reader.close();
} catch (Exception e) {
bodyRead = false;
}
Foo f = null;
if (bodyRead) {
try {
Gson gson = new Gson();
f = gson.fromJson(sb.toString(), Foo.class);
res = "Received: " + f.toString();
} catch (Exception e) {
res = "Failed to convert body into Foo: '" + sb.toString() + "'";
}
}
response.setContentType("text/html");
response.getWriter().println(res);
}
}
请您参考如下方法:
终于开始工作了......有点。
通过将我的ajax调用中的contentType参数更改为“application/x-www-form-urlencoded”(并使用不同的方法来表示我的数据),我现在可以在我的WebSphere环境中的帖子正文中使用我的数据,尽管是 URL 参数形式而不是 JSON。
不幸的是,执行此更改会导致 Pluto 中的功能中断。该环境中的请求正文现在为空。
现在要么更改代码以从 request.getParameter() 检索数据(我相信在我的更改下,这在两种环境中都有效,但需要进一步测试),要么查找将在两种环境中生成填充请求正文的 contentType .
