2017-03-07 61 views
0

我有一个基于HTTP Servlet的Web应用程序。 这是JS请求我的servlet:HTTP Servlet设置数据响应并通过Javascript检查它

 $.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代码成功检查其值:function(data)?

回答

2

如果我很好地理解你的问题是你想显示从你的servlet到客户端通过JS代码的响应!你可以试试这个:

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 
}, 
+0

谢谢@PacMan! – pier92

+0

@ pier92很高兴,因为它帮助!如果我的回答很有帮助,请将其作为正确答案来检查,以帮助其他人获得答案。 – PacMan

+0

现在,当我尝试检查一个无效值时,我在浏览器网络控制台中看到500错误,并且getOutputStream()已被调用此响应。我该如何解决这个问题?我tryind添加response.getOutputStream()。flush(); response.getOutputStream()。close();之后 response.getOutputStream()。print(message);在这两种情况下..我是对的吗? – pier92