-4

我想使用 JSP 从 Oracle 获取数据。应该从表单文本框传递多个参数。

<form method="post" action="num_post.jsp">
Enter Number: <input name="num" type="text" id="num" />

<input type="submit" name="Submit" value="Submit" />
</form>

在文本字段中,我想传递多个参数,例如 123,456,789,896 等。

现在在 num_post.jsp 我有这段代码来请求 JSP 中传递的参数。

<%
 String[] num=request.getParameterValues("num");

 int i=0;

 for(i=0;i<num.length;i++)
 {
      out.println("number Elements       :"+num[i]+"<br/>");
 }
%>

现在我想使用数组参数从 Oracle 获取数据,例如:num[i]

<%@page import="java.sql.*"%>
<%@ page import = "java.io.*"%>
<%
 Class.forName("oracle.jdbc.OracleDriver");
 Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
 Statement st=con.createStatement();
 String sql = "SELECT * from jha where num IN '"+num[i]+"'" ;
 ResultSet rs = st.executeQuery(sql);
 %>

这会引发ArrayOutOfBound异常。

4

1 回答 1

0

尝试这个

String[] num=(request.getParameter("num").toString()).split(",");

代替

String[] num=request.getParameterValues("num");

=====更新=====

正如您所指定的ArrayIndexOutOfBound,这意味着您正在尝试从数组中访问超出索引。而且,很明显

String[] num=(request.getParameter("num").toString()).split(","); // let say array size would be 4
int i=0;  // i initialized by 0

 for(i=0;i<num.length;i++)
 {
      out.println("number Elements       :"+num[i]+"<br/>"); 
 }
  // when control reached here, the value of i will be 4 (which is out of index)

现在,在您的查询中,您尝试访问4不存在的索引元素。

"SELECT * from jha where num IN '"+num[i]+"'"   // here value  of i is 4

这就是您获得ArrayIndexOutOfBound的原因。知道了 ???

还有一件事,您在那里编写的查询适用于仅检查数组中的一个值。因此,您需要更改查询。它不会显示您的预期输出。

于 2012-12-23T05:41:12.710 回答