这件事让我头疼了过去3天。我试图存储我从数据库中获得的结果集并存储在对象的arraylist中,然后将其传递给jsp进行显示,但是在运行程序之后,它给了我这个错误: enter image description here
任何人都知道如何解决这个问题?提前致谢! 下面是我的代码: 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 :(得分:0)
尝试从jsp页面中删除此类food
:
class food {
String name;
double price;
String imageurl;
}
而是尝试在您的页面jsp中导入类似<%@ page import="package.food " %>
的类食物。
并在路径中添加反斜杠:
RequestDispatcher req = request.getRequestDispatcher("/menu.jsp");
答案 1 :(得分:0)
您尝试传递的列表ArrayList<food> foodDetail = new ArrayList<food>();
中使用的servlet中的食物类正试图转换在jsp本身中定义的org.apache.jsp_menu$1food
。删除类食物的jsp中的声明并使用<%@ page import="your.package.food" %>
它应该与我在servlet中使用的声明相同。