【问题标题】:HTTP Servlet set data response and check it via JavascriptHTTP Servlet 设置数据响应并通过 Javascript 进行检查
【发布时间】:2017-07-27 20:13:20
【问题描述】:

我有一个基于 HTTP servlet 的网络应用程序。 这是对我的 servlet 的 JS 请求:

        $.ajax({
              type:    "POST",
              url:     url,
              xhrFields: {
                  withCredentials: false
               },
              data:{
                  "action"      : action_type,
                  "fingerprint" : fingerprint,
                  "user_id"     : user_id,        

              },
              success: function(data) {

                alert('sdp inviato!');

             },
              // vvv---- This is the new bit
              error:   function(jqXHR, textStatus, errorThrown) {
                    console.log("Error, status = " + textStatus + ", " +
                          "error thrown: " + errorThrown
                    );
              }
            });

这是我的 servlet 代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


String action= request.getParameter("action");

UtenteModel um= new UtenteModel();
SDPLineModel sdpmodel= new SDPLineModel();

     if (action.equals("CheckFingerprint")) {

        String fingerprint = (String) request.getParameter("fingerprint");

        String user_id = request.getParameter("user_id");

        SDPLines sdpline = sdpmodel.findFingerprintNew(fingerprint, user_id);

        if (sdpline == null) {

            String message = "Fingerprint non valida!";

            System.out.println("Fingerprint not found! ");

        }
        else {

            System.out.println("Fingerprint found! ");
        }
    }

我的问题是:谁能告诉我一些修改我的 servlet 和 js 代码的例子,设置一个特定的响应数据(对于这两种情况,找到或未找到指纹)以及如何通过 JS 代码成功检查其值:函数(数据)?

【问题讨论】:

    标签: javascript jquery http servlets


    【解决方案1】:

    如果我非常了解您的问题是您想通过 JS 代码显示来自您的 servlet 到客户端的响应!你可以试试这个:

    if (sdpline == null) {
        String message = "Fingerprint non valida!";
        response.getOutputStream().print(message);
    }else {
        String message = ""Fingerprint found! ""
        response.getOutputStream().print(message);
    } 
    

    所以现在在您的 AJAX 请求中,如果您的请求成功完成,您将收到该消息。

    },
     success: function(data) {
         alert('message coming from your servlet is '+data);
         //here data will contain one of the messages depending on the if statement 
    },
    

    【讨论】:

    • @pier92 很高兴因为它有帮助!请如果我的回答有帮助,您可以将其作为正确答案进行检查,以帮助其他人获得它。
    • 现在,当我尝试检查无效值时,我在浏览器网络控制台中看到 500 错误,并且 getOutputStream() 已被调用以获得此响应.. 我该如何解决这个问题?我正在尝试添加 response.getOutputStream().flush(); response.getOutputStream().close();在 response.getOutputStream().print(message) 之后;在这两种情况下..我是对的吗?
    • @pier92 在任何情况下你都会得到response,这样你就可以在值上创建一个if statement来检查它是否valid,然后不要打印任何东西! !
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2014-05-11
    • 2016-08-01
    • 2022-10-14
    • 1970-01-01
    • 2016-10-25
    • 2013-05-15
    相关资源
    最近更新 更多