2014-04-29 97 views
0

實際上,我想要一個服務器發送一個數字列表給客戶端,並希望客戶端運行>在其機器上的JavaScript,並將結果發送到服務器和服務器將驗證>是否正確。我們如何能做到這一點??? .... plzzz幫助如何發送一個數組從servlet到一個javascript

//this is the servlet code 

import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 


@WebServlet(urlPatterns = {"/NewServlet"}) 

public class NewServlet extends HttpServlet { 

/** 
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
* methods. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8"); 
    try (PrintWriter out = response.getWriter()) { 
     /* TODO output your page here. You may use following sample code. */ 
     System.out.println("Received following data from client:"); 
     // System.out.println(request.getParameter("type")); 

     if(request.getParameter("type").equals("first")) { 
     String ip= request.getLocalAddr(); 
     int[] arr = {1, 2, 4, 56, 78}; 

     String str=""; 
     for(int i=0; i<arr.length; i++) 
      str += arr[i]+"#";//creating a seperator 

     System.out.println("The string to be sent is: "+str); 
     out.println(str);//to check if client is sending right request 
     } 
     else if(request.getParameter("type").equals("second")) { 
      System.out.println("hiii"); 
      out.println("Sum received from client is: "+request.getParameter("sum")); 
     } 
    } 

} 

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
/** 
* Handles the HTTP <code>GET</code> method. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    processRequest(request, response); 
} 

/** 
* Handles the HTTP <code>POST</code> method. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    processRequest(request, response); 
} 

/** 
* Returns a short description of the servlet. 
* 
* @return a String containing servlet description 
*/ 
@Override 
public String getServletInfo() { 
    return "Short description"; 
}// </editor-fold> 
} 

這是JSP代碼

<%@page contentType="text/html" pageEncoding="UTF-8"%> 

<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
     <script> 

    var list=[]; 

    function myFun() { 
     alert("fun called"); 
     var obj = new XMLHttpRequest(); 
     var j=0; 
     obj.open("POST", "NewServlet", true); 
     obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     obj.onreadystatechange = function() { 
      if(obj.readyState===4 && obj.status===200) { 
       alert(obj.responseText);//alert("response received from server- "+obj.responseText); 

       var str = obj.responseText; 
       var arr = str.split("#"); 
       alert(arr); 
       var j=0; 
       for(var i=0; i<arr.length-1; i++) { 
        j+=parseInt(arr[i]); 
       } 
       alert(j); 
       myFun1(j); 
     }    
     }; 
     obj.send("type=first"); 
     //obj.send("sum="+j); 

    } 


    function myFun1(j) { 

     var obj = new XMLHttpRequest(); 
     obj.open("POST", "NewServlet", true); 
     obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

     obj.onreadystatechange = function() { 
      if(obj.readyState===4 && obj.status===200) { 
       alert("sum sent to server"); 
       } 
      }; 


     obj.send("sum="+j+"&type=second"); 

    } 
    </script> 

</head> 
<body> 
    <h1>Hello World!</h1> 


    <input type="submit" onclick="javascript:myFun()" value="click here to get list of Numbers" /> 

    <!-- 
    <form method="post" action="NewServlet"> 
     <input type="text" name="text1"><input type="submit" name="sub"> 
    </form> 
    --> 
</body> 

+1

你需要編寫代碼來form.submit()在你的javascript以便將值返回給服務器。而且我不會使用servlet來編寫html內容。爲什麼不用jsp呢? – Hirak

+1

研究使用AJAX爲您的頁面和服務器進行通信。 –

+0

我已經使用AJAX來實現相同的,但在代碼IM從servlet來JSP發送一串數字,然後發送總和servlet的回..但servlet不是能夠收到可變 的總和,我已經更新相同的..plz的代碼檢查出來 – user3586365

回答

0

在你的情況使用servlet接縫是適當的。正如我所看到的,唯一的障礙就是您已經使用AJAX將您的數字放到視圖中。這樣做,你只需要檢索來自response參數作家在processRequest方法。我會用JSON對象在servlet:[1, 2, 4, 56, 78]你只是你的陣列追加到響應作家與客戶端接收從它的AJAX請求。

當此字符串中的客戶端的JavaScript到達會喜歡它更好,因爲分解可以通過使用JSON.parse([1, 2, 4, 56, 78])

這應該是它做...

相關問題