Servlet返回"到AngularJS2调用

时间:2016-10-31 16:56:55

标签: java angularjs json servlets

我正在使用Angular2对servlet进行POST调用。我现在必须使用servlet。 servlet在响应中返回JSON,但由于包含

的响应,Angular将所有响应显示为失败
"

在JSON响应中而不是"。我在控制台中看到了这一点:

xhrstatusText: {"status":"OK"}
replaced statusTest={"status":"OK"}

我不确定问题是与servlet还是Angular调用有关。

的Servlet

public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    JsonObject jsonObj = Json.createObjectBuilder().add("status", "OK").build();
    response.setStatus(HttpServletResponse.SC_OK, jsonObj.toString());
}

Angular2 POST调用

makeFileRequest(params: Array<string>, files: Array<File>) {
    return new Promise((resolve, reject) => {
        var formData: any = new FormData();
        var xhr = new XMLHttpRequest();

        for(var i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                // Contains &quot; instead of " in JSON.
                console.log('xhrstatusText: ' + xhr.statusText);
                // This fixes the JSON, but the response is already marked as failed.
                var statusTextJson = xhr.statusText.replace(/(&quot\;)/g,"\"");
                console.log('replaced statusTest=' + statusTextJson);

                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        }

        xhr.open("POST", this.url, true);
        xhr.send(formData);
    });
}

!!!最终解决方案!!!

的Servlet

public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    JsonObject jsonObj = Json.createObjectBuilder().add("status", "OK").build();
    response.getWriter().println(jsonObj.toString());
}

Angular2 POST调用

makeFileRequest(params: Array<string>, files: Array<File>) {
    return new Promise((resolve, reject) => {
        var formData: any = new FormData();
        var xhr = new XMLHttpRequest();

        for(var i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                // {"status":"OK"}
                console.log('xhr.response: ' + xhr.response);

                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        }

        xhr.open("POST", this.url, true);
        xhr.send(formData);
    });
}

1 个答案:

答案 0 :(得分:1)

根据HttpServletResponse的javadoc,setStatus(int, String)方法实际上已经被弃用了这个原因(第二个参数目的的含糊不清)。它并不打算做你想做的事。

相反,请考虑使用setStatus(int)方法设置状态并将JsonObject写入响应的打印编写器:

response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(jsonObj.toString());
相关问题