在页面加载时编辑jsp页面的下拉列表中显示所选值(Spring MVC)

rom*_*rav 1 javascript jquery spring jsp spring-mvc

我想在页面加载的下拉列表中显示所选值.我的编辑页面显示一个值,国家/地区.现在用户属于美国,因此默认情况下应在页面加载时选择USA.我可以使用javascript或jquery.

我在互联网上找不到任何帮助,但是他们使用了scriplets(<%%>)并且我不想使用它们.

我传递的是具有Id和Value的List.另外我还有另一个对象.我可以通过在jsp中引入for循环并显示值来编写代码,但可能是我在那里做了一些错误.还想知道是否有更好的方法来做到这一点.

我正在使用Spring MVC.

谢谢.

Pra*_*sad 5

"现在用户属于美国,因此默认情况下应在页面加载时选择美国." 您知道之前用户属于某个国家/地区.

假设你有一个pojo国家:

    public class Country{ 
        String countryName;
        String countryId;
        //setters and getters
    }

    public class YourForm{
        List<Country> countryList;
        String selectedCountryId;
        ...
        //setters and getters
    }
Run Code Online (Sandbox Code Playgroud)

在委托给jsp的controller方法中:

    ...
    YourForm form = new YourForm();
    //set your countrylist to form 
    //set  country user belongs to - selectedCountryId - since you know before hand user belongs to some country.
    model.addAttribute("yourForm", form):
    ...
Run Code Online (Sandbox Code Playgroud)

现在在jsp中访问它:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    </head>
    <body>
    <form:form id="yourForm" modelAttribute="yourForm" method="post">

    <tr>
        <td width="50%" class="label">
            <form:select id="countryId" path="selectedCountryId" title='Select Country'>
                <option value="">Please Select</option>
                <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/>
            </form:select>
        </td>
    </tr>
    </body>
Run Code Online (Sandbox Code Playgroud)

由于selectedCountryId已在控制器中设置,因此您将在jsp中看到该国家/地区已自动选中.