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>