如何在java中将查询字符串值从servlet传递给jsp(文本框值)

时间:2017-04-17 10:25:00

标签: java jsp servlets jdbc

基于Query String值我需要从数据库中获取值并需要将值从servlet传递给jsp我怎样才能在这里传递该值我尝试了它在文本框null值中显示的代码。

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

用于此:

request.setAttribute("BatchID", value);

答案 2 :(得分:0)

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