我正在使用JSP和servlet制作购物车,我正在通过数据库中的arraylist将这些项目添加到购物车。我通过设置和获取session的属性值来做到这一点。但是它只添加了1个值,之后输出为null。请告诉我如何解决这个问题。 这是我的Cart.java页面,其中元素被添加到ArrayList
ArrayList al=null;
HttpSession session=request.getSession(false);
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("xyz");
int i=Integer.parseInt(id);
if (session.getAttribute("Il")==null)
{
al=new ArrayList();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
while(rs.next())
{
Item item=new Item();
item.itemid=rs.getInt(1);
String name=rs.getString(2);
item.itemname=rs.getString(2);
item.itemprice=rs.getString(3);
al.add(item);
}
session.setAttribute("Il", al);
con.close();
RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
out.println(e.getMessage());
}
}
else
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/cart","root","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from cake where id="+i+"");
while(rs.next())
{
Item item=new Item();
item.itemid=rs.getInt(1);
String name=rs.getString(2);
item.itemname=rs.getString(2);
item.itemprice=rs.getString(3);
al.add(item);
}
session.setAttribute("Il", al);
con.close();
RequestDispatcher rd=request.getRequestDispatcher("select.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
out.println(e.getMessage());
}
}
这是我的Cart.jsp页面,其中显示了所有值。
<%--
Document : Cart
Created on : Jul 1, 2017, 10:36:09 AM
Author : hp-pc
--%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page import="p1.Item"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cart</title>
<style>
h1{
float: right;
}
</style>
</head>
<body>
<%
String name=(String)session.getAttribute("username");
%>
<h1>
<%=name%>
</h1>
<table>
<tr>
<th> Select</th>
<th>Id</th>
<th> Name</th>
<th> Price</th>
</tr>
<form>
<%
System.out.println("testing.......................");
ArrayList items=(ArrayList)session.getAttribute("Il");
System.out.println("success........................"+items);
Iterator it=items.iterator();
while(it.hasNext())
{
Item i=(Item)it.next();
%>
<tr>
<td>
<div class="radio">
<label><input type="radio" name="optradio"></label>
</div>
</td>
<td><%=i.itemid%></td>
<td><%=i.itemname%></td>
<td><%=i.itemprice%></td>
</tr>
<%
}
%>
</form>
</table>
</body>
</html>
答案 0 :(得分:0)
您需要在al = (ArrayList) session.getAttribute("Il");
之后添加} else {
:
} else {
al = (ArrayList) session.getAttribute("Il"); // add this line
try {
Class.forName("com.mysql.jdbc.Driver");
至少。