2016-03-02 103 views
-2

这件事情让我头痛了3天。我试图来存储我从数据库和存储对象的ArrayList内得到结果集,然后将它传递给JSP进行显示,但在运行程序后,它给了我这个错误: enter image description here将对象的ArrayList从servlet传递给jsp失败

人有任何想法如何解决这个问题呢?提前致谢!下面 是我的代码: menu.java

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse  response) 
     throws ServletException, IOException { 
    PrintWriter out = response.getWriter(); 
    try { 
     Class.forName("com.mysql.jdbc.Driver"); 

     //Create connection object 
     conn = DriverManager.getConnection(request.getServletContext().getInitParameter("url"), request.getServletContext().getInitParameter("username"), request.getServletContext().getInitParameter("password")); 
     String sql = "select name,price,imageurl from food"; 
     stmt = conn.createStatement(); 
     rs = stmt.executeQuery(sql); 
     class food { 

      String name; 
      double price; 
      String imageurl; 

     } 
     ArrayList<food> foodDetail = new ArrayList<food>(); 

     while (rs.next()) { 
      food temp = new food(); 

      temp.name = rs.getString("name"); 
      temp.price = rs.getDouble("price"); 
      temp.imageurl = rs.getString("imageurl"); 

      foodDetail.add(temp); 

     } 
     request.setAttribute("menu", foodDetail); 
     RequestDispatcher req = request.getRequestDispatcher("menu.jsp"); 
     req.forward(request, response); 

    } catch (ClassNotFoundException ex) { 
     Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (SQLException ex) { 
     Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); 
    } finally { 

     try { 
      rs.close(); 
      stmt.close(); 
      conn.close(); 
     } catch (SQLException ex) { 
     } 

    } 

引入了menu.jsp

<% 
     class food { 

      String name; 
      double price; 
      String imageurl; 
     } 


     ArrayList<food> foodDetail = (ArrayList<food>) request.getAttribute("menu"); 
     food temp = new food(); 
java.util.Iterator it = foodDetail.iterator(); 
     while (it.hasNext()) { 

      food z = (food) it.next(); 

      out.println(z.getName()); 


     } 


    %> 
+0

控制台中的任何错误? –

+3

你的食物类别与你传递的不同,以及你想要在 –

+0

中遇到的情况你需要导入食物类别在jsp中使用的servlet中<%@ page import =“your.package.food”%>,而不是定义另一个类别在jsp中 –

回答

0

尝试从JSP页面中删除这个类food

class food { 

     String name; 
     double price; 
     String imageurl; 
    } 

,而是尝试导入类像这样的食物<%@ page import="package.food " %>在你的页面jsp中。 并添加一个反斜杠路径:

RequestDispatcher req = request.getRequestDispatcher("/menu.jsp"); 
0

你的servlet中的食品类列表这是你试图通过ArrayList<food> foodDetail = new ArrayList<food>();使用正试图org.apache.jsp_menu$1food投这是在JSP定义本身。删除类食物的jsp中的声明并使用<%@ page import="your.package.food" %>它应该与您在servlet中使用的相同,正如我所评论的。