【发布时间】:2017-09-12 23:06:48
【问题描述】:
基于查询字符串值,我需要从数据库中获取值,并且需要将值从 servlet 传递到 jsp,我如何在此处传递该值,我尝试了它在文本框 null 值中显示的这段代码。
【问题讨论】:
-
到目前为止您尝试了什么?请提供您的代码和相应的错误!
基于查询字符串值,我需要从数据库中获取值,并且需要将值从 servlet 传递到 jsp,我如何在此处传递该值,我尝试了它在文本框 null 值中显示的这段代码。
【问题讨论】:
您必须使用void setAttribute(java.lang.String name, java.lang.Object o) 还必须检查您的 ResultSet 是否不为空,您必须使用它来代替:
ResultSet res = st.executeQuery(s);
int id = 0;
if(res.next()){
id = res.getInt("BatchID");
}
request.setAttribute("BatchID", id);
注意为避免任何语法错误或 sql 注入,您必须改用 PreparedStatement
String s = "select BatchID from CPWorkDetails where BatchId = ?";
st = conn.createStatement();
ResultSet res = st.executeQuery(s);
int Id = res.getInt("BatchID");
try (PreparedStatement st = connection.prepareStatement(s)) {
st.setString(1, BatchId1[1]);
ResultSet res = st.executeQuery(s);
int id = 0;
if(res.next()){
id = res.getInt("BatchID");
}
request.setAttribute("BatchID", id);
}
【讨论】:
<%= (String)request.getAttribute("patient") %> 代替
if(res.next()){ id = res.getInt("BatchID"); request.setAttribute("BatchID", id); } 吗?你确定你的id != null你可以在控制台打印它并检查试试然后告诉我
使用 request.setAttribute() 方法在 servlet 中设置 BatchID
Servlet
try {
conn = ds.getConnection();
if (request.getQueryString() != null) {
String Batch = request.getQueryString();
String[] BatchId1 = Batch.split("=");
String s = "select BatchID from CPWorkDetails where BatchId='" + BatchId1[1] + "'";
st = conn.createStatement();
ResultSet res = st.executeQuery(s);
int Id = res.getInt("BatchID");
request.setAttribute("BatchID",Id );
}
}
Jsp
<input type="text" id="txtBatchName" class="form-control"
name="txtBatchName" value=" <%=request.getAttribute("BatchID")%>">
【讨论】:
用于此:
request.setAttribute("BatchID", value);
【讨论】: