其他条件似乎在我的JSP中不起作用

时间:2013-10-13 18:32:01

标签: java jsp if-statement

我的一个JSP中有以下代码。

<% if(rsmatches!=null){%>
              <table>
                  <tr>
                      <td class="captions">Match</td>
                      <td>

                          <select>
                              <%

                               while(rsmatches.next()){ 
                                %>
                                <option value="<%out.print(rsmatches.getString("matchid"));%>"><%out.print(rsmatches.getString("matchid"));%> - <%out.print(rsmatches.getString("team1name"));%> vs <%out.print(rsmatches.getString("team2name"));%></option>
                                <%}%>
                          </select>
                      </td>
                  </tr>
              </table>

              <%} else{%>
              <h1>No Result</h1>
              <%}%>

所以rsmatches是结果集,当它不为null时,它给出了我预期的输出,但是当Resultset没有结果时,它显示

无结果

,而不显示没有值的下拉列表。我在哪里犯了错误?

4 个答案:

答案 0 :(得分:3)

你试过这个吗?

<% if(rsmatches!=null && rsmatches.next()){%>
<table>
    <tr>
        <td class="captions">Match</td>
        <td>

        <select>
        <%

            do{ //Change to do while since result set is already pointing to the first row coz of the statement in if loop
        %>
                <option value="<%out.print(rsmatches.getString("matchid"));%>"><%out.print(rsmatches.getString("matchid"));%> - <%out.print(rsmatches.getString("team1name"));%> vs <%out.print(rsmatches.getString("team2name"));%></option>
            <%} while(rsmatches.next()) ;%>
        </select>
        </td>
    </tr>
</table>
<%} else{%>
<h1>No Result</h1>
<%}%>

答案 1 :(得分:1)

试试这个:

<% if( rsmatches != null && rsmatches.size() > 0 ) { %>

答案 2 :(得分:0)

听起来像rsmatches是空的(实例化)而不是null,这可以解释为什么else不会触发。

答案 3 :(得分:0)

你这样做是错误的。理想情况下,您不应该在内部使用与数据库相关的代码,这些代码显示应用程序的设计不良和违反应用程序层。

现在回答你的问题,即使没有使用查询获取记录,ResultSet也永远不会为null。理想情况下,您应该使用

处理此方案
  1. 在某个类(最好是DAO)中读取结果集,然后构建一个集合。稍后将此集合传递给JSP以显示数据。

  2. 在检查null的同时,触发resultSet.next()方法以确定是否存在下一条记录。之后不使用while循环使用Do ... while循环。