-1

I have to generate a bidimensional array for my extjs application.

I have the mysql interrogation from the servlet but I need to save these values to a bidimensional array in javascript.

The thing that I have thought to work about is saving the bidimensional array from the servlet (using tomcat) in a bidimensional array in my jsp page, where I use the script for the extjs.

My problem is understanding how can recall from servlet to jsp page the variable which I need and save her value in a javascript variable. Example:

Servlet

package connect;

import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Driver;
import jdk.nashorn.internal.runtime.JSONFunctions;

@WebServlet("/learn")
public class iServlet_debug_1 extends HttpServlet {
private static final long serialVersionUID = 1L;

public iServlet_debug_1() {
    super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String connectionString = "jdbc:mysql://localhost:3306/mydb?user=root&password=pass";

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(connectionString);
        Statement stm = connection.createStatement();
        ResultSet rs = ((java.sql.Statement) stm).executeQuery("select * from romanzi");

        //ArrayList<ArrayList<Object>> storeArray = new ArrayList<ArrayList<Object>>();
        //String[][] storeArray;
        String storeArray = null;
        //int n = 0;
        //int m = 0;
        while (rs.next()) {
            //first method
            /*ArrayList<Object> arr =  new ArrayList<Object>();
            ArrayList<Object> arr =  new ArrayList<Object>();
            arr.add(rs.getInt("id"));
            arr.add(rs.getString("titolo"));
            arr.add(rs.getString("ISBN"));
            arr.add(rs.getString("genere"));
            arr.add(rs.getInt("Npagine"));
            arr.add(rs.getInt("editore"));
            storeArray.add(arr);*/

            //second method
            /*storeArray[n][m]= rs.getString("id");
            m++;
            storeArray[n][m]= rs.getString("titolo");
            m++;
            storeArray[n][m]= rs.getString("ISBN");
            m++;
            storeArray[n][m]= rs.getString("genere");
            m++;
            storeArray[n][m]= rs.getString("Npagine");
            m++;
            storeArray[n][m]= rs.getString("editore");
            m=0;
            n++;*/
            storeArray += "["+rs.getString("id")
                        +","+rs.getString("titolo")
                        +","+rs.getString("ISBN")
                        +","+rs.getString("genere")
                        +","+rs.getString("Npagine")
                        +","+rs.getString("editore")
                        +"]";
            if(rs.next())
            {
                storeArray+= ",";
                rs.previous();
            }

        }
        response.setContentType("text/plain"); // sets the content type
        response.setCharacterEncoding("UTF-8"); // sets the encoding
        PrintWriter out = response.getWriter();
        out.append(storeArray); // writes the value of the String to the response
    }
    catch (SQLException e) {
        e.printStackTrace();
    } 
    catch (Exception e) {
        PrintWriter err = response.getWriter();
        err.print("<html><head></head><body>" + e.getMessage() + "</body></html>");
    } 
    finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {

        }
    }
  }

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);

}

  }

Javascript

var temp = (storeArray Servlet variable);
var finalArray = JSON.parse("[" + temp + "]");

or

var finalArray = eval("[" + temp + "]");

The result that i need is something like this:

var finalArray = [
      ['value10','value11','value12'],
      ['value20','value21','value22'],
      ['value30','value31','value32']
];

For next implementation I need to understand how can i retrieve the servlet value and convert it in javascript variable onload of the jsp page.

Substantially:

  • I have to pass: an array of arrays variable from servlet to javascript (because i need the method that allows me to do the communication from servlet variable and javascript variable)
  • Or a String from servlet to javascript variable and after split in an array of arrays

That's all.

Thanks in advance and sorry for my "not really good" english.

2
  • Possible duplicate of How to transfer java array to javaScript array using jsp? Commented Apr 2, 2019 at 11:39
  • Not exactly ... There is only one for saving the elements dimensional java in an equally javascript. My array is two-dimensional and all the data transfer part between servlet and javascript is missing .... Thanks anyway. Commented Apr 2, 2019 at 14:56

1 Answer 1

0

I finally resolved my problem with GSON/JSON libraries. Bottom the code:

Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String connectionString = "jdbc:mysql://localhost:3306/mydb?user=root&password=pass";

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(connectionString);
        Statement stm = connection.createStatement();
        ResultSet rs = ((java.sql.Statement) stm).executeQuery("select * from novels");

        ArrayList<ArrayList<Object>> storeArray = new ArrayList<ArrayList<Object>>();
        ArrayList<Object> arr =  new ArrayList<Object>();
        while (rs.next()) {
            arr.add(rs.getInt("id"));
            arr.add(rs.getString("title"));
            arr.add(rs.getString("ISBN"));
            arr.add(rs.getString("genre"));
            arr.add(rs.getInt("Npages"));
            arr.add(rs.getString("publisher"));
            storeArray.add(arr);
            arr = new ArrayList<Object>();
        }
        Gson gson = new Gson();
        String jsonStore = gson.toJson(storeArray);
        response.setContentType("text/plain"); // sets the content type
        response.setCharacterEncoding("UTF-8"); // sets the encoding
        request.setAttribute("array", jsonStore);
    }
    catch (SQLException e) {
        e.printStackTrace();
    } 
    catch (Exception e) {
        PrintWriter err = response.getWriter();
        err.print("<html><head></head><body>" + e.getMessage() + "</body></html>");
    } 
    finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            // error management
        }
    }
}

With

Gson gson = new Gson();
String jsonStore = gson.toJson(storeArray);

is possible translate the storeArray in a JSON string for javascript;

With this

response.setContentType("text/plain"); // sets the content type
response.setCharacterEncoding("UTF-8"); // sets the encoding
request.setAttribute("array", jsonStore);

we can send the JSON string to front end part;

The JSON string variable can we retrived from jsp with the part below:

<%
    RequestDispatcher rd = request.getRequestDispatcher("/generate");
    rd.include(request, response);
    String store = (String)request.getAttribute("array");
%>

And finally we can store the variable to a javascript variable with this:

var temp = <%=store%>;

that read the variable as a javascript "ArrayList" variable!

I hope you will find it useful.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.