Servlet数组到javascript变量

时间:2019-04-02 10:59:21

标签: javascript mysql jsp servlets

我必须为我的extjs应用程序生成一个二维数组。

我收到了来自servlet的mysql询问,但是我需要将这些值保存到javascript中的二维数组中。

我想着要解决的事情是将servlet中的二维数组(使用tomcat)保存到我的jsp页面中的二维数组中,在其中我将脚本用于extjs

我的问题是了解如何从servlet调回jsp页面我需要的变量并将其值保存在javascript变量中。 示例:

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 + "]");

我需要的结果是这样的:

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

对于下一个实现,我需要了解如何检索servlet值并将其转换为jsp页面的javascript变量onload。

基本上:

  • 我必须通过:从servlet到javascript的数组变量数组(因为我需要允许我进行从servlet变量和javascript变量进行通信的方法)
  • 或者从servlet到javascript变量的字符串,然后拆分成数组数组

仅此而已。

在此先感谢我的英语水平不是很好。

1 个答案:

答案 0 :(得分:0)

我终于解决了GSON / JSON库的问题。 代码底部:

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
        }
    }
}

使用

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

可以将javascript中的storeArray转换为JSON字符串;

有了这个

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

我们可以将JSON字符串发送到前端部分;

我们可以使用以下部分从jsp中检索JSON字符串变量:

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

最后,我们可以使用以下命令将变量存储到javascript变量中:

var temp = <%=store%>;

将变量读取为javascript“ ArrayList”变量!

希望您会发现它有用。