Question

Good Morning, i'am sending a java-script array from JSP to servlet using jQuery.post() but the issue here is that it throws a java.lang.NullPointerException at servlets.DeleteServlet.doPost(DeleteServlet.java:45) when the action is executed here's the java-script method that sends the array to the servlet:

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>

     var myIdsArray = new Array;

function getCarId(tableID) { // these methods fills the array with values
    try {

        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for ( var i = 0; i < rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if (null != chkbox && true == chkbox.checked) {
                if (rowCount <= 2) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                myIdsArray.push(table.rows[i].cells[1].innerHTML);
            }

        }
        sendArrayToServer();

    } catch (e) {
        alert(e);
    }
}
        function sendArrayToServer() {
    alert("Called");
    $.post('DeleteServlet', {
        arrayData : myIdsArray,
        mode : "insert"
    });

and here's my servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String[] arrayData=request.getParameterValues("arrayData");
    PrintWriter out=response.getWriter();
    for (String string : arrayData) { // line 45
        out.println(string);

    }
Was it helpful?

Solution

request.getParameterValues("arrayData") will return a String Array of all HTTP request parameters named "arrayData". The parameters can be either in the query string or in the HTTP POST body.

However,

$.post('DeleteServlet', {
        arrayData : myIdsArray,
        mode : "insert"
});

does not create any parameters by this name. That is why you get a null pointer on line 45.

What is sent to the server in this case is a JSON string. What you need to do is parse this string on the server. This will mean (1) Get the string from the POST body. (2) Parse it. You will probably want to use a 3rd-party JSON parser. json-simple is a good one.

Or if you wish to leave your server code as is, you could change the client code to create these request parameters. Probably the easiest approach would be to put them on the query string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top