JSP 从 Java servlet 获取空值

JSP getting null values from Java servlet

我正在尝试将值从 servlet 传递到 JSP 文件。我已经确认数据是从 JSP 到 Servlet,而不是相反。这是 Java 片段

//Here is where I get a List<String> of the column names
List<String> columns = DataAccess.getColumns(query);

//Turn the List<String> into a 1D array of Strings
for(int i = 0 ; i < numArrays ; i++)
    request.setAttribute("rows["+i+"]", rows[i]);

//Set the attribute to the key "columns"
request.setAttribute("columns", arColumns);

//Launch result.jsp
request.getRequestDispatcher("result.jsp").forward(request, response);

我希望将一维字符串数组链接到键 "columns"。当我从 JSP 文件中获取它时,我得到 null。以下是我检索它并确认它为空的方式:

<%  String[] columns = (String[])request.getParameterValues("columns"); 
    if(columns == null){
        System.out.print("columns is null\n");
    }
    int colNum = columns.length; //How many columns we have
%>

在 Eclipse 中,当我 运行 代码时,我在控制台上得到字符串 "columns is null",然后当我试图获取列的长度时出现 NullPointerException。

我确认 java 文件中的 arColumns 不为空,当我尝试将它们打印到控制台时,它确实打印了 headers 列。

我做错了什么?

感谢您的帮助。

我相信你应该试试:

String[] columns = (String[]) request.getAttribute("columns"); 
String[] columns = (String[]) request.getAttribute("columns"); 

getParameterValues() 通常在您使用 HTML 复选框时使用。

<form action="someServlet" method="POST">
<input type="checkbox" name="delete" value="1">
<input type="checkbox" name="delete" value="2">
<input type="checkbox" name="delete" value="3">
</form>

//in someServlet:
String[] itemsToBeDeleted = request.getParameterValues("delete");

for(String s : itemsToBeDeleted) {
    System.out.println(s); //prints 1,2,3 if they're checked
 }