如何从servlet向javascript发送数字数组

时间:2014-04-29 17:45:33

标签: java ajax jsp servlets networking

  

实际上我希望服务器向客户端发送一个数字列表,并希望客户端在其计算机上运行> javascript并将结果发送到服务器,服务器将验证>是否正确。我们怎么能这样做?...... plzzz帮助

//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 个答案:

答案 0 :(得分:0)

在您的情况下使用servlet接缝是合适的。正如我所看到的那样,唯一的障碍就是将您的数字放到视图中,因为您已经使用了AJAX。这样做,您只需从response方法中的processRequest参数中检索Writer即可。我将在servlet中使用JSON表示法:[1, 2, 4, 56, 78]您只需将数组附加到响应Writer,客户端就从它的AJAX请求中接收它。

当这个字符串到达​​客户端时,JavaScript会更喜欢它,因为可以使用JSON.parse([1, 2, 4, 56, 78])进行解析

这应该是......