[英]Unable to set attribute of ResultSet in Servlet
在我的項目中,我將查詢結果從數據庫中獲取到我的servlet中,並在為ResultSet
設置了屬性之后將結果傳遞給JSP,然后在JSP中對其進行了訪問。但是,我能夠以某種方式設置和訪問我的所有其他屬性JSP和Servlet(結果集除外)。
這是我的數據庫訪問函數getcart()
public static ResultSet getCart(int item,int cust){
ResultSet rs=null,res=null;
String i_name;
int price;
try{
rs=stmnt.executeQuery("SELECT i_name,price FROM items WHERE i_id="+item);
rs.next();
i_name=rs.getString(1);
price=rs.getInt(2);
stmnt.executeUpdate("INSERT INTO cart(prod,price,c_id,i_id) VALUES('"+i_name+"',"+price+","+cust+","+item+")");
res=stmnt.executeQuery("SELECT prod,price,count(*) FROM cart WHERE c_id="+cust+" GROUP BY i_id");
res.next();
}catch(SQLException e){}
return res;
}
這是JSP
<%ResultSet r=(ResultSet)request.getAttribute("cart");%>
<div id="pageContent">
<div style="margin:24px; text-align:left;"><br />
<table width="100%" border="2" cellspacing="0" id ="table1">
<tr>
<td width="15%" bgcolor="#000000" align="center"><strong>Product</strong></td>
<td width="10%" bgcolor="#000000" align="center"><strong>Price</strong></td>
<td width="12%" bgcolor="#000000" align="center"><strong>Quantity</strong></td>
<!--<td width="9%" bgcolor="#000000" align="center"><strong>Total</strong></td>-->
</tr>
<%while(r.next()){%>
<tr class="spaceUnder">
<td width="15%" bgcolor="#FFFFFF" align="center"><font color="#000"> <%=re.getString(1)%></font></td>
<td width="10%" bgcolor="#FFFFFF" align="center"><font color="#000"> <%=re.getInt(2)%></font></td>
<td width="12%" bgcolor="#FFFFFF" align="center"><font color="#000"> <%=re.getInt(3)%> </font></td>
</tr>
<%}%>
</table>
<div class="container">
<left><h3 style="color:#FFFFF;padding-top:30px;"><font color="#000">Total: <%=total%> </font></h3></left>
</div>
</div>
</div>
這是servlet片段:
res=accessDB.getCart(it,ci);
request.setAttribute("cart",res);
view=request.getRequestDispatcher("cart.jsp");
view.forward(request, response);
我不知道發生了什么事? 我現在花了很多時間,而且我的數據庫不是空的,所以res.next()是有效的。
一件事情正在工作。當我使用getInt
和getString
在Servlet代碼中分解ResultSet
並將它們分別發送到JSP而不是發送整個ResultSet
,JSP中的getAttribute
可以工作並且我可以打印我的結果。但是不要知道為什么整個ResultSet
無法運行。我正在使用Netbeans 8.0.1。
請幫忙。
根據我的觀察,我認為您的查詢SELECT prod,price,count(*) FROM cart WHERE c_id="+cust+" GROUP BY i_id
僅返回一行。
首先,您不應該使用res.next();
在返回RESULTSET
對象之前。 這是設計功能的錯誤方法。 getCart(int item,int cust)
應該做的只是返回RESULTSET
。
我假設的問題,似乎在這里是,您的query
僅返回一行。 當您調用res.next();
在返回RESULTSET
對象之前。 resultset cursor
已經指向resultset cursor
的第一行。
當您調用<%while(r.next()){%>
,這一次它<%while(r.next()){%>
NULL
,因為結果集中的下一行不存在。 這就是為什么無法打印結果的原因。
我現在觀察到的是,您在jsp代碼中輸入了錯誤。 <%=re.getString(1)%>
應該是<%=r.getString(1)%>
因為您正在創建<%ResultSet r=(ResultSet)request.getAttribute("cart");%>
結果集變量名為 r
但您正在使用re
。 但是re
在文件中不存在。 我認為JSP甚至不應該編譯,因為從未定義過re
變量。
這s the reason it
不起作用s the reason it
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.