2017-03-07 18 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