Using NetBeans IDE 7.0.1 with Java SDK 1.7.1 and Glassfish 3.x:

I am trying to load an ArrayList from a database in the Servlet to be used on the JSP page in a dropdown box that would show stock symbol and company name.

I get the following message when trying to setup the session to transfer the array object equivalent to userBean from a tutorial on here (note I can display the text value):

INFO: Database connection established - menuServlet
INFO: menuServlet: numRows = 19
INFO: textValue 1 = AAPL
WARNING: StandardWrapperValve[menuServlet]: PWC1406: Servlet.service() for servlet menuServlet threw exception
java.lang.NullPointerException
at stock.eval.menuServlet.processRequest(menuServlet.java:92)
at stock.eval.menuServlet.doPost(menuServlet.java:179)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:722)
------------------------------------------------------------------------------------
This is the code that fails in the line marked below:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stock.eval;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

/**
 *
 * @author jaykool74
 */
public class menuServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private StkBean stkBean;
    private ArrayList<StkBean> stkList;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = "";
        String url = "";
        String sqlResult = "";
        String textValue = "";

        /*
         * Process request to gather the stock symbols for the drop down box
         * to display on the report.jsp page
         */

        try
        {
            // get a connection
            //String dbURL = "jdbc:mysql://localhost:3306/murach";
            String dbURL = "jdbc:derby://localhost:1527/stock";
            String username = "app";
            String password = "app";

            try
            {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
                System.out.println("Database connection established - menuServlet");
            }
            catch (Exception e)
            {
                System.out.println("Cannot connect to database server - menuServlet");
                sqlResult = "Error executing the SQL statement: <br>"
                        + e.getMessage();
            }//end try-catch

            Connection connection = DriverManager.getConnection(
                dbURL, username, password);

            // create a statement
            Statement statement = connection.createStatement
                (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            // parse the SQL string
            String sqlStatement = ("select stock_symbol, company_name from stock"
                                    + " order by stock_symbol");

            HttpSession session = request.getSession(true);               
            
            ResultSet results = statement.executeQuery(sqlStatement);
            //ResultSetMetaData metaData = results.getMetaData();
            results.last();
            int numRows = results.getRow();
            results.beforeFirst();
            System.out.println("menuServlet: numRows = " + numRows);            

            //add each stock symbol to the list to be displayed on report.jsp
            //List<String> myList = new ArrayList<String>();            
            while (results.next() )
            {
                //myList.add((results.getString(1)).trim() );
                textValue = results.getString((1)).trim ();
                System.out.println("textValue 1 = " + textValue);
//****** The next line of code here fails even though textValue = "APPL" ******
                stkBean.setStkSymbol(textValue);                
                textValue = results.getString((2)).trim();
                System.out.println("textValue 2 = " + textValue);
                stkBean.setCompanyName(textValue);
                stkList.add(stkBean);
            }//end do-while

            //close db connections & queries
            results.close();
            statement.close();
            connection.close();             
            
            //set session array list variables for use by jsp
            request.getSession().setAttribute("stkBean", stkBean);
            request.getSession().setAttribute("stkList", stkList);            
            
            //System.out.println("myList = " + myList);
            //session.setAttribute("myList", myList);
            //System.out.println("session attribute set to myList");                       
        }
        catch (SQLException e)
        {
            System.out.println("menuServlet - DB read error: " + e.getMessage());
        }//end catch

        /* Go to page choose by user in the menu */
        try
        {
             System.out.println("getting choice");
             action = request.getParameter("choice");
             if (action.equals("report"))
                 url = "/report.jsp";
             if (action.equals("discount"))
                 url = "/discount.jsp";
             if (action.equals("historical"))
                 url = "/historical.jsp";
             if (action.equals("stkInfo"))
                 url = "/stkInfo.jsp";
             if (action.equals("stkPrice"))
                 url = "/stkPrice.jsp";
             if (action.equals("user"))
                 url = "/user.jsp";

            System.out.println("url = " + url);
            RequestDispatcher dispatcher = request.getRequestDispatcher(url);
            //   = getServletContext().getRequestDispatcher(url);

            try
            {
                dispatcher.forward(request, response);
            }
            catch (IllegalStateException ie)
            {
                ie.printStackTrace();
            }//end try-catch
        } 
        finally
        {
            out.close();
        }//end try block
    }//end of menuServlet

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

This code is equivalent to the UserBean from the tutorial:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stock.eval;

/**
 *
 * @author jaykool74
 */
public class StkBean 
{
    private String stkSymbol;         //Stock Symbol
    private String companyName;       //Company Name    

    public StkBean() 
    {
        
    }//end method: StkBean

    public void setStkSymbol(String str) 
    {
        stkSymbol = str;
    }//end method: setStkSymbol
    
    public String getStkSymbol() 
    { 
        return stkSymbol;
    }//end method: getStkSymbol

    public void setCompanyName(String str) 
    {
        companyName = str;
    }//end method: setCompanyName
    
    public String getCompanyName() 
    { 
        return companyName;
    }//end method: getCompanyName   
}//end class: StkBean

The JSP code below is what MenuServlet opens

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*" %>

<html>

<head>
    <title>Stock Analysis Results</title>
</head>

<body>

<h1>Stock Evaluation Method</h1>
<p>
<b>Stock Analysis, please choose a stock symbol:</b><br>

<select>
    <%
    ArrayList optionList = (ArrayList)session.getAttribute("stkList");
    //List<String> optionList = new ArrayList<String>();
    
   /* problem occurs with getting the attribute of the arraylist variable
    * called myList 
    */ 
    
    optionList = (ArrayList)session.getAttribute("stkList");
    
        for (int i=0; i < optionList.size(); i++ ){%>
        <option>
            <%out.print(optionList.get(i)); }%>
        </option>
</select>

<form action="historicalResultsServlet" method="post">
    <input type="submit" value="Execute">
</form>

<p>
    ${sqlResult}
</p>
<a href="./menu.jsp">Go Home</a>
</body>
</html>

This JSP code invokes menuServlet:

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
    <title>Stock Analysis Administrative Menu</title>
</head>

<body>

<h1>Choose an action to perform:</h1>
<p><br>

<form action="menuServlet" method="post">
<table border="1">
    <tbody>
        <tr>
            <td><input type="radio" name="choice" value="report" /></td>
            <td>Run Stock Analysis Report</td>
        </tr>
        <tr></tr>
        <tr>
            <td></td>
            <td><b>View or Update Table</b></td>
        </tr>
        <tr>
            <td><input type="radio" name="choice" value="discount" /></td>
            <td>Discount Factor</td>
        </tr>
        <tr>
            <td><input type="radio" name="choice" value="historical" /></td>
            <td>Historical</td>
        </tr>
        <tr>
            <td><input type="radio" name="choice" value="stkInfo" /></td>
            <td>Stock Information</td>
        </tr>
        <tr>
            <td><input type="radio" name="choice" value="stkPrice" /></td>
            <td>Stock Price</td>
        </tr>
        <tr>
            <td><input type="radio" name="choice" value="user" /></td>
            <td>User Information</td>
        </tr>
    </tbody>
</table>
    <br>
    <input type="submit" value="Submit" name="menuChoice" />
</form>

</body>
</html>

I don't see where you have initialized "stkBean" prior to that line.

Please note the variable is declared in line 27, and then it is set to a value in line 93. Please tell me why I would have to initialize the variable any further than what I have already done? What line of code are you recommending that I need to add?

Yes, you declared the variable on line 27, but you haven't actually initialized it prior to using it. You still have to create an instance of new StkBean() before you can assign any values to it.

Thank you that fixed the java null pointer exception error!

May I please ask if you know why my dropdown textbox on the report.jsp (opened by menuServlet) is showing 19 iterations (there are 19 rows retrieved from the DB) of stock.eval.StkBean@1eebf0c instead of the text values below:

INFO: textValue 1 = AAPL
INFO: textValue 2 = Apple Computer
INFO: textValue 1 = AKS
INFO: textValue 2 = AK Steel Holding
INFO: textValue 1 = AXAS
INFO: textValue 2 = Abraxas Petroleum
INFO: textValue 1 = BRK.A
INFO: textValue 2 = Berkshire Hathaway
INFO: textValue 1 = BRK.B
INFO: textValue 2 = Berkshire Hathaway (Class B)
INFO: textValue 1 = CNP
INFO: textValue 2 = Cars-N-Parts, Inc.
INFO: textValue 1 = CPWR
INFO: textValue 2 = Compuware Corporation
INFO: textValue 1 = F
INFO: textValue 2 = Ford Motor Company
INFO: textValue 1 = GPOR
INFO: textValue 2 = Gulfport Energy
INFO: textValue 1 = KEG
INFO: textValue 2 = Key Energy Services
INFO: textValue 1 = LKQX
INFO: textValue 2 = LKQ Corporation
INFO: textValue 1 = MEE
INFO: textValue 2 = Massey Energy
INFO: textValue 1 = MSFT
INFO: textValue 2 = Microsoft Corporation
INFO: textValue 1 = NTES
INFO: textValue 2 = NetEase.com
INFO: textValue 1 = RRC
INFO: textValue 2 = Range Resources Corporation
INFO: textValue 1 = STLD
INFO: textValue 2 = Steel Dynamics
INFO: textValue 1 = WFT
INFO: textValue 2 = Weatherford International
INFO: textValue 1 = WLT
INFO: textValue 2 = Walter Energy
INFO: textValue 1 = WMB
INFO: textValue 2 = Williams Companies

Are you creating a new StkBean each iteration of your loop to add to the array list?

I changed it to do that and I get stock.eval.StkBean@180bf87 for all 19 values of the dropdown text box.

Here is the revised code for the menuServlet:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stock.eval;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

/**
 *
 * @author pmijme0
 */
public class menuServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    private StkBean stkBean = new StkBean();
    private ArrayList<StkBean> stkList = new ArrayList<StkBean>(); 
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = "";
        String url = "";
        String sqlResult = "";

        /*
         * Process request to gather the stock symbols for the drop down box
         * to display on the report.jsp page
         */

        try
        {
            // get a connection
            //String dbURL = "jdbc:mysql://localhost:3306/murach";
            String dbURL = "jdbc:derby://localhost:1527/stock";
            String username = "app";
            String password = "app";

            try
            {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
                System.out.println("Database connection established - menuServlet");
            }
            catch (Exception e)
            {
                System.out.println("Cannot connect to database server - menuServlet");
                sqlResult = "Error executing the SQL statement: <br>"
                        + e.getMessage();
            }//end try-catch

            Connection connection = DriverManager.getConnection(
                dbURL, username, password);

            // create a statement
            Statement statement = connection.createStatement
                (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            // parse the SQL string
            String sqlStatement = ("select stock_symbol, company_name from stock"
                                    + " order by stock_symbol");

            HttpSession session = request.getSession(true);               
            
            ResultSet results = statement.executeQuery(sqlStatement);
            //ResultSetMetaData metaData = results.getMetaData();
            results.last();
            int numRows = results.getRow();
            results.beforeFirst();
            System.out.println("menuServlet: numRows = " + numRows);            
            
            //add each stock symbol to the list to be displayed on report.jsp
            //List<String> myList = new ArrayList<String>();            
            while (results.next() )
            {
                //myList.add((results.getString(1)).trim() );
                stkBean.setStkSymbol(results.getString((1)).trim () );                
                stkBean.setCompanyName(results.getString((2)).trim() );
                stkList.add(stkBean);
                StkBean stkBean = new StkBean();                
            }//end do-while

            //close db connections & queries
            results.close();
            statement.close();
            connection.close();             
            
            //set session array list variables for use by jsp
            request.getSession().setAttribute("stkBean", stkBean);
            request.getSession().setAttribute("stkList", stkList);            
            
            //System.out.println("myList = " + myList);
            //session.setAttribute("myList", myList);
            //System.out.println("session attribute set to myList");                       
        }
        catch (SQLException e)
        {
            System.out.println("menuServlet - DB read error: " + e.getMessage());
        }//end catch

        /* Go to page choose by user in the menu */
        try
        {
             System.out.println("getting choice");
             action = request.getParameter("choice");
             if (action.equals("report"))
                 url = "/report.jsp";
             if (action.equals("discount"))
                 url = "/discount.jsp";
             if (action.equals("historical"))
                 url = "/historical.jsp";
             if (action.equals("stkInfo"))
                 url = "/stkInfo.jsp";
             if (action.equals("stkPrice"))
                 url = "/stkPrice.jsp";
             if (action.equals("user"))
                 url = "/user.jsp";

            System.out.println("url = " + url);
            RequestDispatcher dispatcher = request.getRequestDispatcher(url);
            //   = getServletContext().getRequestDispatcher(url);

            try
            {
                dispatcher.forward(request, response);
            }
            catch (IllegalStateException ie)
            {
                ie.printStackTrace();
            }//end try-catch
        } 
        finally
        {
            out.close();
        }//end try block
    }//end of menuServlet

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

And the report.jsp that the menuServlet directs the output:

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="stock.eval.StkBean"%>
<jsp:useBean id="stkBean" class="stock.eval.StkBean" scope="session" />
<jsp:useBean id="stkList" type="ArrayList<stock.eval.StkBean>" scope="session" />

<html>

<head>
    <title>Stock Analysis Results</title>
</head>

<body>

<h1>Stock Evaluation Method</h1>
<p>
<b>Stock Analysis, please choose a stock symbol:</b><br>

<select>
    <%
    ArrayList optionList = (ArrayList)session.getAttribute("stkList");
    //List<String> optionList = new ArrayList<String>();
    
   /* problem occurs with getting the attribute of the arraylist variable
    * called myList 
    */ 
    
    //optionList = (ArrayList)session.getAttribute("stkList");
    
        for (int i=0; i < optionList.size(); i++ ){%>
        <option>
            <%out.print(optionList.get(i)); }%>
        </option>
</select>

<form action="historicalResultsServlet" method="post">
    <input type="submit" value="Execute">
</form>

<p>
    ${sqlResult}
</p>
<a href="./menu.jsp">Go Home</a>
</body>
</html>

Actually, on line 93 you are declaring a new variable "stkBean" which immediately goes out of scope in your loop.

StkBean stkBean = new StkBean();

Remove the declaration from that and just assign the new instance to your class-level stkBean reference.

Your current code is still using the single instance of stkBean that you initialized at declaration.

Alternately, you could move line 93 up to the beginning of the loop and do away with the class-level variable altogether. You don't have any use for stkBean other than adding to the arraylist.

while (results.next() )
            {
                StkBean stkBean = new StkBean();   
                //myList.add((results.getString(1)).trim() );
                stkBean.setStkSymbol(results.getString((1)).trim () );                
                stkBean.setCompanyName(results.getString((2)).trim() );
                stkList.add(stkBean);
             
            }//end do-while

Edit: Also, you may want to either override toString() in your StkBean class or print one of the properties like getCompanyName() in your option list output.

Thank you! issue is resolved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.