如何使用jsp在选择框中根据结果集值设置所选选项

时间:2013-10-31 08:44:05

标签: java mysql jsp

我使用以下代码从数据库获取用户表值

 <%
String userid=(String)session.getAttribute("userid");
Connection con=Singleton.getMySqlConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user where mail='"+userid+"'");
%>

并在jsp页面中显示值,如

<%while(rs.next()){%>

     <div class="divRegTableColF"><label for="USER_FIRST_NAME">First name: </label></div>
     <%if((rs.getString(2))!=null){%>
     <div class="divRegTableColS"><span> <input class="inputRegBox" name="fname" id="USER_FIRST_NAME" size="60" maxlength="50" value="<%=rs.getString(2)%>"></span>
     </div>
     <%}
     else
     {%>
     <input class="inputRegBox" name="fname" id="USER_FIRST_NAME" size="60" maxlength="50" value=""></span><span class="astRegPad"><font color="#000000">*</font>
     <%}%>


<select class="inputRegBox" name="country" size=1 maxlength=30 value="<%=rs.getString(13)%>">   
    <option>select</option>
    <option >Afghanistan</option>
    <option >Aland Islands</option>
    <option>Albania</option>
    <option>Algeria</option>
    <option>American Samoa</option>
    <option>Andorra</option>
    <option>Angola</option>
    <option>Anguilla</option>
    <option>Antarctica</option>
    <option>Antigua and Barbuda</option>
    <option>Argentina</option>
    <option>Armenia</option>
    <option>Aruba</option>
    <option>Australia</option>
    <option>Austria</option>
    <option>Azerbaijan</option>
    <option>Bahamas</option>
    <option>Bahrain</option>
    <option>Bangladesh</option>
    <option>Barbados</option>
    <option>Belarus</option>
    <option>Belgium</option>
    <option>Belize</option>
    <option>Benin</option>
    <option>Bermuda</option>
    <option>Bhutan</option>
    <option>Bolivia</option>
    <option>Bonaire, Saint Eustatius and Saba</option>
    <option>Bosnia and Herzegovina</option>
    <option>Botswana</option>
    <option>Bouvet Island</option>
    <option>Brazil</option> 
</select>
</div></div>
   </div>
<%}%>


enter code here

我在select box.how中获取国家/地区值以选择选项值并在选择框中显示该值。

1 个答案:

答案 0 :(得分:4)

在选项选择标记中添加条件,因为我不是jsp开发人员,但很容易在数组中添加所有选项值并执行,

<select class="inputRegBox" name="country" size=1 maxlength=30 >   
    <option value="Afghanistan"  <%if((rs.getString(13))=='Afghanistan'){%> selected <%}%> >Afghanistan</option>
</select>