HTTP Servlet设置数据响应并通过Javascript进行检查

时间:2017-03-07 14:52:53

标签: javascript jquery http servlets

我是基于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代码成功检查其值:功能(数据)?

1 个答案:

答案 0 :(得分:5)

如果我非常了解您的问题是您希望通过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 
},