将一个arraylist从一个jsp返回到另一个jsp并给出json视图

时间:2015-07-27 09:26:58

标签: java json jsp

我有两个jsp文件,一个是query.jsp,另一个是b.jsp。在b.jsp中,我连接了一个数据库,从数据库表testemployee中选择了所有值并创建了一个rows函数内的所有值的arraylist public List select()然后返回列表。在query.jsp我试图使该列表的json格式调用b.jsp的选择函数

  <% Gson gson = new Gson();
   String json = gson.toJson(select());    %>

但它没有显示数据库值的json格式。当我写

  

<%=select() %>

它完美地显示了数据库值列表。我该如何解决?请考虑我的问题。

我的代码   query.jsp

<%@page import="com.google.gson.Gson"%>

<%@include file="b.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>
</head>
<body>
    <h2><%
          Gson gson = new Gson();
    String json = gson.toJson(select()); 
  // select()      
    %>

    </h2>
</body>
</html>

b.jsp

<%!
Connection connection = null;
Statement statement = null;
      String query;
%>
<%
    try {
        Class.forName("org.postgresql.Driver");
        connection =   DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
        statement = connection.createStatement();

    } catch (Exception e) {
    out.println(e.getMessage());
    }
%>
<%!
  public List select() {
    List rows = new ArrayList();
    Map row = null;


    try {
        query="select * from testemployee";
        ResultSet resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();
        int numColumns = metaData.getColumnCount();

        while (resultSet.next()) {
            row = new HashMap();
            for (int i = 1; i < numColumns + 1; i++) {
                row.put(metaData.getColumnName(i), resultSet.getObject(i));
            }
            rows.add(row);
        }

        resultSet.close();
    } catch (Exception e) {

    }

    return rows;
}
%>​

我导入了所有必要的文件,并在b.jsp

中添加了query.jsp

1 个答案:

答案 0 :(得分:0)

&lt;%= select()%&gt;是一个表达式,它将右侧部分上的任何内容转换为String,在本例中为select method的输出,即List。

  • select()是一个java方法而不是函数

因此,为了查看您的列表,您需要迭代它并在表中绘制,这意味着HTML否则您将只执行java方法。

这是example

编辑:

<body>
    <h2><%
          Gson gson = new Gson();
    String json = gson.toJson(select()); 
  // select()      
    %>
    <%=json%>
    </h2>
</body>