发布空的主体(长度为0的字符串)

时间:2018-07-11 11:24:52

标签: javascript xmlhttprequest

要向服务器发布内容,请使用以下代码:

var u1 = new XMLHttpRequest();
u1.open('POST', 'java/packagename');
u1.send(''); // <- string length of 0, a valid packagename in java.

var u2 = new XMLHttpRequest();
u2.open('POST', 'java/packagename');
u2.send('a'); // <- string length of 1, also a valid package name in java.

不幸的是,长度为0的字符串未发布。

1 个答案:

答案 0 :(得分:0)

最后我自己找到了解决方案。

我将u1代码重写为

var h = value === null?'null':(v === ''?'empty-string':(v === undefined?'undefined':null));
if (h != null) {
    u1.setRequestHeader('X-empty-body-interpret-as', h);
}

(我知道你们所有人的想法:嘿,您违反了RFC 6648,但目前我不在乎)

在控制器中,我这样读取标题:

@RequestMapping(value="java/packagename", method = RequestMethod.POST)
public ResponseEntity<Object> updatePackage(@RequestBody(required=false) String entityPackageNew, HttpServletRequest request) {
    String interpretNullAs = request.getHeader("X-empty-body-interpret-as");
    DP databaseMavenRevelation = entityManager.find(DP.class, databaseMavenRevelationId);
    if (entityPackageNew == null) {
        switch (interpretNullAs) {
            case "empty-string":
                databaseMavenRevelation.setEntityPackage("");
                break;
            case "null":
            case "undefined":
                databaseMavenRevelation.setEntityPackage(null);
                break;
        }
    } else { 
        databaseMavenRevelation.setEntityPackage(entityPackageNew);
    }
    entityManager.persist(databaseMavenRevelation);
    return new ResponseEntity<>(HttpStatus.OK);
}