【问题标题】:How to Pass Query String value from servlet to jsp(text box value) in java如何在java中将查询字符串值从servlet传递给jsp(文本框值)
【发布时间】:2017-09-12 23:06:48
【问题描述】:

基于查询字符串值,我需要从数据库中获取值,并且需要将值从 servlet 传递到 jsp,我如何在此处传递该值,我尝试了它在文本框 null 值中显示的这段代码。

【问题讨论】:

  • 到目前为止您尝试了什么?请提供您的代码和相应的错误!

标签: java jsp servlets jdbc


【解决方案1】:

您必须使用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);
}

【讨论】:

  • 我需要显示从servlet到jsp的查询字符串值
  • @RobertE 你可以尝试使用<%= (String)request.getAttribute("patient") %> 代替
  • @RobertE 我不知道您在servelt 或jsp 工作的地方,请问您可以组织您的问题吗?
  • 嗨,我在我的 servlet 中也有插入查询,它只会在我点击按钮时起作用,但在点击按钮之前,并且在显示页面时,只有我需要显示的时间
  • @RobertE 你试过if(res.next()){ id = res.getInt("BatchID"); request.setAttribute("BatchID", id); } 吗?你确定你的id != null你可以在控制台打印它并检查试试然后告诉我
【解决方案2】:

使用 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")%>">

【讨论】:

  • 以这种方式传递BatchID并检查。 request.setAttribute("BatchID","hello");
  • 不,它在文本框中显示仍然为空值我更新了我的图像,它是怎么来的
【解决方案3】:

用于此:

request.setAttribute("BatchID", value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2013-02-13
    • 2017-03-18
    • 2014-06-22
    • 1970-01-01
    相关资源
    最近更新 更多