首页 > 解决方案 > 当您期望空结果时,如何防止从 java 服务器端返回 400 代码?

问题描述

我有一个对服务器端 java servlet 的 ajax 调用,并且 null 响应非常有效。但是,我也收到 400 错误代码。问题是 400 错误填满了我的报告 uri 日志,因此很难找到任何“真正的”错误。有没有办法防止400代码。

ajax 调用是:

      $.ajax({
            url : 'NewsDispView',
            data : {
                ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
                ssAccountID : sessionStorage.getItem('ssAccountID'),
                ssGroupID: sessionStorage.getItem('ssGroupID'),
                ssGroupSection: sessionStorage.getItem('ssGroupSection'),
            },
            type : 'POST',
            cache: false,
        })
        .fail (function(jqXHR, textStatus, errorThrown) {
    //      alert(jqXHR.responseText);
            if(jqXHR.responseText.includes('No News')){
                alert("No news");
            }else{
                alert("News");
            }
            var marquee = "<span class='glyphicon glyphicon-forward'>";
            marquee += " No notices ";
            marquee += "<span class='glyphicon glyphicon-forward'>";
            $("#newsMarquee").empty();
            $('#newsMarquee').append(marquee);
        })
        .done(function(responseJson1a){
            // JSON response to populate the activities table
            dataType: "json";
    
            //alert(JSON.stringify(responseJson1a));
            
            //do stuff
        })

servlet 返回是:

    if (newsList == null || newsList.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No News.");
    } else {
        String json = new Gson().toJson(newsList);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

标签: ajaxservlets

解决方案


您也可以将JSON 格式的错误消息传递给您的 ajax 调用。所以,生成你的 json 然后像下面这样传递它:

if (newsList == null || newsList.isEmpty()) {
   String json = new Gson().toJson(yourjson);
 } else {
   String json = new Gson().toJson(newsList);
 }
 response.setContentType("application/json");
 response.setCharacterEncoding("UTF-8");
 response.getWriter().write(json);

然后,检查您的 ajax 代码是否响应具有密钥 ie :error并相应地更改您的 ajax 逻辑。


推荐阅读