【问题标题】:Error message from Java to Ajax is not returned properly从 Java 到 Ajax 的错误消息未正确返回
【发布时间】:2018-09-04 03:55:23
【问题描述】:

当 java 程序找不到所需的信息时,我想返回适当的错误消息(可能是许多已确定的原因之一)。我的java代码是:

}else{
    response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");
    response.getWriter().write("Captcha description incorrect.");
}

而ajax是:

$.ajax({
    type: "POST",
    url: "AccountRecoveryQuestionsView",
    cache: false,
    data: $(questionForm).serialize(),
    success: function(data){
        $('#ajaxGetUserServletResponse').text(data);
    },
    error: function(data) {
        $("#accountName").focus();
        //$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
        $('#ajaxGetUserServletResponse').text(data);
    }
});

错误函数被触发;但是,该消息不显示。

我已将代码更改为:

          statusCode: {
                400: function(jqXHR, textStatus, errorThrown){
                    alert(jqXHR.status);
                    alert(textStatus);
                    alert(errorThrown);
                    $("#accountName").focus();
                    $('#ajaxGetUserServletResponse').text(errorThrown);
                }
            },

结果是400,错误,空白。

我已经把ajax改成:

          .fail (function(jqXHR, textStatus, errorThrown) {
                alert(jqXHR.status);
                alert(textStatus);
                alert(errorThrown);
                alert(jqXHR.statusText);
                alert(jqXHR.responseText);
                $("#accountName").focus();
                //$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
                //$('#ajaxGetUserServletResponse').text(errorThrown);
                $('#ajaxGetUserServletResponse').text(jqXHR.responseText);
            });

和警报(jqXHR.responseText);正在返回:

<!doctype html><html lang="en"><head><title>HTTP Status [400] – [Bad Request]</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status [400] – [Bad Request]</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Captcha description not correct</p><p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).</p><hr class="line" /><h3>Apache Tomcat/8.5.15</h3></body></html>

我如何才能收到错误消息“验证码描述不正确”。这包含在上面。

【问题讨论】:

  • SC_BAD_REQUEST400 你应该这样做:$.ajax({ statusCode: { 400: function() { //do something } } });
  • 关于#sendError:“如果响应已经被提交,则该方法抛出IllegalStateException。使用该方法后,应认为响应已提交,不应该写给。”
  • 谢谢@Aniket Sahrawat。这行得通。有没有办法为每个异常返回不同的错误消息,因为我可能会发生大约五种不同的异常(例如,验证码名称不正确、问题未正确回答、电子邮件地址未存档)。
  • 如果您为它们抛出异常,那么这不是处理客户端错误的正确方法。您只需编写适当的响应代码和消息,并在发生客户端错误时将其发送回客户端。
  • 我在做这个 statusCode: { 400: function() {$('#ajaxGetUserServletResponse').text("Captch not correct.");} },

标签: java ajax


【解决方案1】:

尝试刷新并关闭你的 writer

...
response.getWriter().flush();
response.getWriter().close();

如果没有帮助,让sendError像这样调用最后一个

response.getWriter().write("Captcha description incorrect.");
response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");

【讨论】:

  • 哦,我刚刚意识到,mb sendError 正在刷新缓冲区,所以你应该让它最后 - 看我的更新
【解决方案2】:

您可以返回以下内容

Response.status(500).entity("Captcha description incorrect. ").build();

根据您的要求修改错误代码,

【讨论】:

  • 对不起,这并没有回答 OP。您似乎对 OP 中的措辞感到迷惑。
【解决方案3】:

HttpServletResponse 对象不应写入 #sendError 已被调用,如上所述

如果响应已经提交,这个方法会抛出一个 非法状态异常。使用此方法后,响应应该是 被视为已提交,不应写入。

因此:

response.sendError(...);
response.getWriter().write(...); // Should not be done

您应该使用错误代码的静态字段访问。在您的代码中,您使用response.SC_BAD_REQUEST,而您应该使用HttpServletResponse.SC_BAD_REQUEST。自己编写 int 代码,例如sendError(400, ...),不会改变结果。

jQuery 中$.ajax 函数的.error 调用自3.0 版以来已被删除,因此不要使用它。相反,您应该使用.done.fail.always.done 等价于.success,而.fail 等价于.error,而.always 有点像try-catch 中的finally-block(顾名思义,总是运行,不管)。

$.ajax 总是返回一个 jQuery XMLHttpRequest 对象,jqXHR。因此,您可以直接在$.ajax-call 上运行方法调用,例如

var jqxhrobj = $.ajax({
    type: "POST",
    url: "AccountRecoveryQuestionsView",
    cache: false,
    data: $(questionForm).serialize()
})
.done(function(jqXHR, textStatus, errorThrown) {
    // Success here
    $('#ajaxGetUserServletResponse').text(jqXHR.responseText);
})
.fail(function(jqXHR, textStatus, errorThrown) {
    // Fail, do something about the error
    // Since you have several error codes you want to handle
    // you could for instance use a switch case
    switch(jqXHR.status) {
        case "400":
            // It might be an int, or even "400 Bad request",
            // change accordingly

            // Do something to handle the error
            break;
        default:
            // Handle errors not specified with a case
            break;
    }
});


// Later in the js code

jqxhrobj.always(function() {
    // Execute something here, regardless of success/failure of the $.ajax-call
});

关于jqXHR对象的更多信息可以阅读here

responseText 将包含一个完全格式化的 html 输出,包括头部、正文等。如果你看一下 responseText 的正文,它看起来像这样:

<body>
    <h1>HTTP Status [errorCode] – [errorCode description]</h1>
    <hr class="line" />
    <p><b>Type</b> Status Report</p>
    <p><b>Message</b> [message passed as 2nd argument in the sendError-call]</p>
    <p><b>Description</b> [full errorCode description]</p>
    <hr class="line" />
    <h3>Apache Tomcat/8.5.15</h3>
</body>

您可以在 jqXHR.responseText 上使用.find(请参阅here) - 在正文中找到 p-tags。您应该返回 3 个元素;消息将在第二个结果元素内。你可能想做某种substr,以摆脱&lt;b&gt;Message&lt;/b&gt;

一种简单但幼稚的方法,它依赖于输出到总是具有完全相同的结构:

var message = jqXHR.responseText.find("p:eq(1)").text();
// text() will not return the <b>-tags, just "Message [msg passed as argument]"
// We'll just substr from the end of "Message"
message = message.substr(7));
// Remove any leading/trailing whitespace
message = message.trim();
// message now contains the error message from #sendError
alert(message);

【讨论】:

  • 我已经做出了改变。请参阅我上面的编辑。但是,我无法显示错误消息。它嵌入在 HTML 的长字符串中。
  • 我可以替换 "response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");"带有“response.sendError(401,“验证码描述不正确”);”为每个错误测试使用不同的错误代码(例如,401、402、403)使用案例来测试每个错误并显示相应的错误消息。这是正确的方法还是糟糕的 hack?
  • 我添加了一条关于如何获取错误消息的建议,尽管它不包含书面示例。如果你需要帮助,你必须问。我还在顶部的代码块response.sendError... 之后包含了有关使用静态字段(例如 SC_BAD_REQUEST)的信息
  • 我在开始时遇到了麻烦。我试过 var message = $(jqXHR.responseText).find("p"); alert(message) 并返回“[object Object]”。
  • 我添加了一个相当幼稚但可以接受的方法。
猜你喜欢
  • 2012-10-14
  • 1970-01-01
  • 2019-07-30
  • 2012-03-29
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 2016-08-27
  • 2015-07-03
相关资源
最近更新 更多