javajspservletstomcat8java-server

JSP getting null values from Java servlet


I am trying to pass values from the servlet to the JSP file. I already confirmed that the data is going from the JSP to the Servlet, but not the other way around. Here is the Java snippet

//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);

There I am expecting to have the 1D array of Strings linked to the key "columns". When I get it from the JSP file, I get null. Here is how I retrieve it and confirm that it is 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
%>

In Eclipse, when I run the code I get the string "columns is null" ont he console, followed by a NullPointerException when I tried to get the length of columns.

I confirmed that arColumns is not null in the java file, it does print the column headers when I try to print them to console.

What am I doing wrong here?

Thank you for your help.


Solution

  • I believe you should instead try:

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