如何比较在jsp中选择的两个arraylist和set选项?

时间:2013-11-08 10:26:34

标签: java jsp

我有两张桌子:

表1 geoCountry

country_name | country_code

表2 user_countries

country_name | username 

我想设置预先选择的用户国家(即从db获取)

以下是我尝试过的代码

     <select multiple="multiple" class="country" style="width: 200px">
         <%
           sql6 = "SELECT DISTINCT countryname FROM user_countries WHERE username = ?";
           ps6 = connection.prepareStatement(sql6);
           ps6.setString(1, user);
           rs6 = ps6.executeQuery();

            while (rs6.next()) {
                usercountries.add(rs6.getString(1));
             }

            for (int i = 0; i < geoCountry.size(); i++) {
                 for (int j = 0; j < usercountries.size(); j++) {
                    if (usercountries.get(j).equals(geoCountry.get(i))) {
                 %>
                <option value="<%=geoCountry.get(i)%>" selected="selected"><%=geoCountry.get(i)%></option>
                 <% } else {%>
                 <option value="<%=geoCountry.get(i)%>"><%=geoCountry.get(i)%></option>
              <% }
              }
           } %>
      </select>

它在选择框中显示重复的值..为什么?

1 个答案:

答案 0 :(得分:0)

使用“usercountries”删除第二个循环。像:

  for (int i = 0; i < geoCountry.size(); i++) {
         if (usercountries.contains(geoCountry.get(i)) {
             %>
            <option value="<%=geoCountry.get(i)%>" selected="selected"><%=geoCountry.get(i)%></option>
             <% } else {%>
             <option value="<%=geoCountry.get(i)%>"><%=geoCountry.get(i)%></option>
          <% }
       } %>