通过迭代显示选择列表

时间:2014-04-25 06:39:49

标签: java jsp select jdbc

<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="java.util.*" %>


      <%
      Connection con =null;
      PreparedStatement pstmt=null;
      List<String> list=null;
      ResultSet rs=null;
      try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "xyz", "abc");
        String strQuery = "SELECT batch_id,course_name FROM t_students_batch";
        pstmt = con.prepareStatement(strQuery);
        rs = pstmt.executeQuery();
        list = new ArrayList<String>();

        while(rs.next()) {
         list.add(rs.getString("batch_id"));
         list.add(rs.getString("course_name"));
            }

      }catch(Exception e) {
          System.out.println("Error:: "+e.getMessage());
      }

        %>

        <html>
        <head>
        <title>pay</title>
        </head>
        <body>
        <form action="payment.jsp" method="get">

        BatchId ::<select name="batchid">
        <%

        for (String temp : list) {


            // how to i get this..
        out.println("<option>"+ temp +"</option>");


        }


        %>

        <input type="submit" value="continue" action="payment.jsp" />

        </select>
        </form>
        </body>
        </html>

输出:::

1 java 

2 jsp 

总列值显示如下

当我点击&#34; 1&#34;它的工作...... 当我单击java或jsp时,它会显示一个空指针异常..

我想把java值1显示为逻辑..

2 个答案:

答案 0 :(得分:0)

缺少值attr,现在它应该提交值。

<%
    for (String temp : list) {
        // how to i get this..
        out.println("<option  value='"+temp +"'>"+ temp +"</option>");
    }
%>

答案 1 :(得分:0)

试试这个。

<%
    for (int i = 0; i < list.size(); i = i+2) {
        out.println("<option  value='"+list.get(i) +"'>"+ list.get(i+1) +"</option>");
    }
%>