【发布时间】:2015-04-08 05:40:09
【问题描述】:
我正在尝试在 servlet 中进行搜索查询并将其加载到 jsp 表的原始数据中。
Connection dbCon = null;
PreparedStatement state = null;
ResultSet rs = null;
String insert_sql = "insert into item(name,unit_price) values(?,?)";
String search_sql = "select * from item";
try {
String item_name = request.getParameter("item_name");
String up = request.getParameter("unit_price");
try {
dbCon = DB.JDBC.getConnection();
state = dbCon.prepareStatement(insert_sql);
dbCon.setAutoCommit(false);
state.setString(1, item_name);
state.setString(2, up);
state.executeUpdate();
dbCon.commit();
rs = state.executeQuery(search_sql);
while (rs.next()) {
String item_id = rs.getString("item_id");
String name = rs.getString("name");
String unit_price = rs.getString("unit_price");
String qty = rs.getString("qty");
try {
response.sendRedirect("index.jsp?item_id=" + item_id + "&name=" + name + "&unit_price=" + unit_price + "&qty" + qty);
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("index.jsp?msg=New Item added successfully");
} catch (Exception e) {
e.printStackTrace();
dbCon.rollback();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
插入工作正常。搜索的第一条记录也加载到浏览器的搜索栏中。这是我的jsp查询。
<tr>
<td><% request.getParameter("item_id");%></td>
<td><% request.getParameter("name");%></td>
<td><% request.getParameter("unit_price");%></td>
<td><% request.getParameter("qty");%></td>
</tr>
我认为问题在于参数传递。我对jsp有点新奇。所以不知道所有的语法。请帮我。
编辑 1
我像这样改变了jsp。
<%
ResultSet rs = (ResultSet) session.getAttribute("rs");
while (rs.next()) {
String item_id = rs.getString("item_id");
String name = rs.getString("name");
String unit_price = rs.getString("unit_price");
String qty = rs.getString("qty");
%>
<tr>
<td><%=item_id%></td>
<td><%=name%></td>
<td><%=unit_price%></td>
<td><%=qty%></td>
</tr>
<%}%>
</tbody>
还有像这样的servlet
rs = state.executeQuery(search_sql);
session.setAttribute("rs", rs);
response.sendRedirect("index.jsp"); //redirect to jsp without any params
现在我在 jsp 中启动时的行中有 org.apache.jasper.JasperException。
这是错误。
【问题讨论】:
-
您需要转发而不是发送重定向。像这里 rs 一样将您的对象添加到响应中。
-
@Naman 可以解释一下