在显示数据时在JSP页面中获取NullPointerException

时间:2014-03-29 17:17:29

标签: jsp servlets nullpointerexception

我在运行Jsp页面时遇到空指针异常。

这是我的java代码。

private void viewTransactions(HttpServletRequest request, HttpServletResponse response) {                       
        t=new Transactions();
        transactions =new ArrayList<Transactions>();
        transactions1 =new ArrayList<Transactions>();
        Integer count=2;

        String custId;
        custId=request.getParameter("custId");

        System.out.println(custId);

        transactions=dao.ViewTransaction(custId);
        System.out.println(transactions.get(1).getName());

        HttpSession session=request.getSession();
        request.setAttribute("transactions",transactions);
        session.setAttribute("count",count);
        transactions=(List<Transactions>) request.getAttribute("transactions");

        Iterator<Transactions> itr = transactions.iterator();
        while (itr.hasNext()) 
        {
            Transactions trans = new Transactions();
            trans = itr.next();
            //logger.debug(" " + book.getAuthor() + " " + book.getCategory()+ " " + book.getDiscountPercentage() + " " + book.getPrice() + " "+ book.getAvailableQuantity() + " ");
            System.out.println(" "+trans.getName()+" "+trans.getDateOfExpense()+" "+trans.getItemDescription()+" "+trans.getPrice()+" "+trans.getPersonalId()+" ");
        }

        try {
            response.sendRedirect("jsp/Display.jsp");
        } catch (IOException e) {

            System.out.println(e);              
        }                                   
    }

这是我的JSP页面。

<form  name="viemForm">
  <% String custName = (String)session.getAttribute("customerName"); %> 

    <h2>Here is our details Mr.<%=custName %></h2>

   <% List<Transactions> transList = (ArrayList)request.getAttribute("transactions");%>
     <% 

         for(int i=0;i<transList.size();i++)
       {
           Transactions trans = transList.get(i);
      %> 

    <table>
         <tr><td>Name</td>
             <td><%=trans.getName()%></td>
         </tr>

          <tr><td>DateOfExpense</td>
             <td><%=trans.getDateOfExpense()%></td>
         </tr>

         <tr><td>ItemDescription</td>
             <td><%=trans.getItemDescription()%></td>
         </tr>

          <tr><td>Price</td>
             <td><%=trans.getPrice()%></td>
         </tr>

         <tr><td>PersonalId</td>
             <td><%=trans.getPersonalId()%></td>
         </tr>        
    </table>                        
    <%}%>                                
 </form>   

这里有什么问题?请帮帮我。

1 个答案:

答案 0 :(得分:0)

在sevlet中转发请求而不是重定向。 在代码中将response.sendRedirect("jsp/Display.jsp");替换为getServletContext().getRequestDispatcher("jsp/Display.jsp").forward(request, response);。使用response.sendRedirect("jsp/Display.jsp")时,它会在Display.jsp页面中创建一个新的请求对象,因此它不会包含您在上一个transactions对象中设置的request属性。但是,当您使用forward(request, response)时,它会将同一请求对象转发到Display.jsp页面,并且transactions属性将在其请求中可用。