以下 java 代码接收来自 JSP 文件的 POST 请求并将 out ArrayList 作为输出传回。我遇到的问题是弄清楚如何正确地将输出读入 Arraylist,这样我就可以从 Arraylist 中获取每个元素并将其显示在我的 JSP 中。
如何将列名读取为第一个字符串数组,然后将每一行数据读取为以下字符串数组,这样我就有一个巨大的数组列表,其中包含以有组织的方式查询的整个结果,以及将允许我将结果读取到我的 JSP 页面上吗?
编辑:所以我现在唯一遇到的问题是当执行像 SELECT * FROM table 这样的命令时;它只显示列名。但是当我执行 SELECT columnName FROM table 之类的命令时;它完美地显示了该列。下面的代码已经更新以反映我现在的位置。
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
@SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<String[]> out = new ArrayList<String[]>();
ArrayList<String> columns = new ArrayList<String>();
String query = request.getParameter("query");
if (query.toString().toLowerCase().contains("select")) {
//SELECT Queries
//try {
ResultSet resultSet = statement.executeQuery(query.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
columns.add(metaData.getColumnName(i));
}
while (resultSet.next()){
String[] row = new String[numberOfColumns];
for (int i = 0; i < numberOfColumns; i++){
row[i] = (String) resultSet.getObject(i+1);
}
out.add(row);
}
//}
//catch (Exception f) {
//f.printStackTrace();
//}
}
else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
//try {
conn.prepareStatement(query.toString()).executeUpdate(query.toString());
columns.add("\t\t Database has been updated!");
//}
//catch (Exception l){
//l.printStackTrace();
//}
}
else {
//Not a valid response
columns.add("\t\t Not a valid command or query!");
}
request.setAttribute("query", query);
request.setAttribute("resultSize", out.size());
request.setAttribute("queryResults", out);
request.setAttribute("queryColumns", columns);
RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
}
}
这是我的 .JSP 文件,现在当我执行命令时它只打印 [] ,其中没有任何内容。由于之前的测试,我知道命令可以正常工作,但数组显示不正确。
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<%@ page import="java.util.ArrayList" %>
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>This is the MySQL Servlet</h1>
<form action = "/database/database" method = "post">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<textarea name = "query" cols="20" rows="5"></textarea>
<input type = "submit" value = "Run MySQL Servlet" />
<input type = "reset" value = "Clear Command" />
</label>
</p>
</form>
<hr>
<TABLE id="results">
<%
ArrayList<String> columns = (ArrayList<String>)request.getAttribute("queryColumns");
ArrayList<String[]> results = (ArrayList<String[]>)request.getAttribute("queryResults");
out.println("<TR>");
if(columns != null && !columns.isEmpty()){
for(String columnName: columns ){
out.println("<TD>"+columnName+"</TD>");
}
}
out.println("</TR>");
//print data
if(results != null && !results.isEmpty()){
for(String[] rowData: results){
out.println("<TR>");
for(String data: rowData){
out.println("<TD>"+data+"</TD>");
}
out.println("</TR>");
}
}
%>
</TABLE>
<%= request.getAttribute("query") %>
<%= request.getAttribute("resultSize") %>
</body>
</html>