环境:运行 Tomcat v7.0 的 Eclipse,使用 Java 的 Stripes 框架,并通过 JQuery ajax 调用提交到服务。
Javascript:
jQuery( function(){
jQuery('#testForm').submit( function(e) {
e.preventDefault();
var dataString = jQuery('#testInput').val(); // Pulled from a textarea for testing purposes.
var urlString = jQuery('#urlDropdown').val(); // Pulled from a dropdown for testing purposes.
if( (jQuery('#urlId') != "" ) &&
(!isNaN(parseInt( jQuery('#urlId').val() )) ) ){ // Pulled from an input type=text for testing purposes.
urlString += '?id=' + parseInt( jQuery('#urlId').val() );
}
alert("urlString: " + urlString);
jQuery.ajax({
type: "POST",
url: urlString,
data: dataString,
dataType: 'json',
success: function( returnData ) {
jQuery('#content').html(JSON.stringify(returnData));
},
fail: function( returnData ) {
alert("FAIL");
}
});
});
});
条纹拦截器:
@Before(stages=LifecycleStage.BindingAndValidation, on={"setClient"})
private Resolution intercept() {
String rbody = getRequestBody();
log.info("BODY: " + rbody);
this.setBody( rbody );
return null;
}
以及正在使用的 getRequestBody
方法:
protected String getRequestBody(){
StringBuffer body = new StringBuffer();
String line = null;
try {
BufferedReader reader = getContext().getRequest().getReader();
while ((line = reader.readLine()) != null)
body.append(line);
} catch (Exception e) {
log.error("Buffered Reader Failed", e);
e.printStackTrace();
}
log.info("BODY: " + body.toString());
return body.toString();
}
我正在使用 Firebug 来测试输入,请求的 post body 确实充满了丰富的 json。
log.info
调用输出一个完全空的字符串。如果我在 getRequest 上调用 getContentLength()
,它会告诉我内容具有适当的字符数。但内容本身显示为空。
我 99.99% 确信代码中没有其他地方正在使用请求正文。目前,这是我在 Stripes 框架中唯一的操作文件,因为我已经删除了所有其他文件。
不知何故,请求正文完全是空的。应该是充满肉味的json。帮助我,Stack Overflow,你是我唯一的希望!
最佳答案
感谢 Stripes IRC channel 上的优秀人士,我有了答案!我需要添加 contentType: "application/json",
如下:
jQuery.ajax({
type: "POST",
url: urlString,
contentType: "application/json",
data: dataString,
dataType: 'json',
processData: false,
success: function( returnData ) {
jQuery('#content').html(JSON.stringify(returnData));
},
fail: function( returnData ) {
alert("FAIL");
}
});
关于java - 在 Java 中对 Stripes 框架的 Ajax 调用会导致请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16156181/